vendor: update missing test deps for ci

pull/5766/head
unknwon 2019-07-28 16:03:54 -07:00
parent 00a3e368b4
commit 025972ef64
No known key found for this signature in database
GPG Key ID: 25B575AE3213B2B3
63 changed files with 2427 additions and 924 deletions

View File

@ -0,0 +1,12 @@
# Contributing
In general, the code posted to the [SmartyStreets github organization](https://github.com/smartystreets) is created to solve specific problems at SmartyStreets that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted.
Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines:
- _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a SmartyStreets team member prior to opening a pull request.
- _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **SmartyStreets, LLC**. Code submitted to SmartyStreets projects becomes property of SmartyStreets and must be compatible with the associated license.
- _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set.
- _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out.
- "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc...
- "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc...

View File

@ -1,4 +1,4 @@
Copyright (c) 2015 SmartyStreets, LLC Copyright (c) 2016 SmartyStreets, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

11
vendor/github.com/smartystreets/assertions/Makefile generated vendored Executable file
View File

@ -0,0 +1,11 @@
#!/usr/bin/make -f
test:
go test -timeout=1s -short ./...
compile:
go build ./...
build: test compile
.PHONY: test compile build

View File

@ -1,3 +1,5 @@
[![Build Status](https://travis-ci.org/smartystreets/assertions.svg?branch=master)](https://travis-ci.org/smartystreets/assertions)
# assertions # assertions
-- --
import "github.com/smartystreets/assertions" import "github.com/smartystreets/assertions"
@ -8,6 +10,8 @@ referenced in goconvey's `convey` package
(github.com/smartystreets/gunit) for use with the So(...) method. They can also (github.com/smartystreets/gunit) for use with the So(...) method. They can also
be used in traditional Go test functions and even in applications. be used in traditional Go test functions and even in applications.
https://smartystreets.com
Many of the assertions lean heavily on work done by Aaron Jacobs in his Many of the assertions lean heavily on work done by Aaron Jacobs in his
excellent oglematchers library. (https://github.com/jacobsa/oglematchers) The excellent oglematchers library. (https://github.com/jacobsa/oglematchers) The
ShouldResemble assertion leans heavily on work done by Daniel Jacques in his ShouldResemble assertion leans heavily on work done by Daniel Jacques in his
@ -25,7 +29,7 @@ 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 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 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 assertions in this package will not serializer a JSON result, making standalone
ussage more convenient. usage more convenient.
#### func ShouldAlmostEqual #### func ShouldAlmostEqual
@ -67,7 +71,7 @@ to "".
```go ```go
func ShouldBeChronological(actual interface{}, expected ...interface{}) string func ShouldBeChronological(actual interface{}, expected ...interface{}) string
``` ```
ShouldBeChronological receives a []time.Time slice and asserts that the are in ShouldBeChronological receives a []time.Time slice and asserts that they are in
chronological order starting with the first time.Time as the earliest. chronological order starting with the first time.Time as the earliest.
#### func ShouldBeEmpty #### func ShouldBeEmpty
@ -79,6 +83,15 @@ 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 calling len(actual) would return `0`. It obeys the rules specified by the len
function for determining length: http://golang.org/pkg/builtin/#len function for determining length: http://golang.org/pkg/builtin/#len
#### func ShouldBeError
```go
func ShouldBeError(actual interface{}, expected ...interface{}) string
```
ShouldBeError asserts that the first argument implements the error interface. It
also compares the first argument against the second argument if provided (which
must be an error message string or another error value).
#### func ShouldBeFalse #### func ShouldBeFalse
```go ```go
@ -187,7 +200,19 @@ ends with the second.
```go ```go
func ShouldEqual(actual interface{}, expected ...interface{}) string func ShouldEqual(actual interface{}, expected ...interface{}) string
``` ```
ShouldEqual receives exactly two parameters and does an equality check. ShouldEqual receives exactly two parameters and does an equality check using the
following semantics: 1. If the expected and actual values implement an Equal
method in the form `func (this T) Equal(that T) bool` then call the method. If
true, they are equal. 2. The expected and actual values are judged equal or not
by oglematchers.Equals.
#### func ShouldEqualJSON
```go
func ShouldEqualJSON(actual interface{}, expected ...interface{}) string
```
ShouldEqualJSON receives exactly two parameters and does an equality check by
marshalling to JSON
#### func ShouldEqualTrimSpace #### func ShouldEqualTrimSpace
@ -322,6 +347,14 @@ func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string
ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is
equal to "". equal to "".
#### func ShouldNotBeChronological
```go
func ShouldNotBeChronological(actual interface{}, expected ...interface{}) string
```
ShouldNotBeChronological receives a []time.Time slice and asserts that they are
NOT in chronological order.
#### func ShouldNotBeEmpty #### func ShouldNotBeEmpty
```go ```go
@ -349,6 +382,14 @@ func ShouldNotBeNil(actual interface{}, expected ...interface{}) string
``` ```
ShouldNotBeNil receives a single parameter and ensures that it is not nil. ShouldNotBeNil receives a single parameter and ensures that it is not nil.
#### func ShouldNotBeZeroValue
```go
func ShouldNotBeZeroValue(actual interface{}, expected ...interface{}) string
```
ShouldBeZeroValue receives a single parameter and ensures that it is NOT the Go
equivalent of the default value, or "zero" value.
#### func ShouldNotContain #### func ShouldNotContain
```go ```go
@ -386,7 +427,8 @@ does not end with the second.
```go ```go
func ShouldNotEqual(actual interface{}, expected ...interface{}) string func ShouldNotEqual(actual interface{}, expected ...interface{}) string
``` ```
ShouldNotEqual receives exactly two parameters and does an inequality check. ShouldNotEqual receives exactly two parameters and does an inequality check. See
ShouldEqual for details on how equality is determined.
#### func ShouldNotHappenOnOrBetween #### func ShouldNotHappenOnOrBetween
@ -521,6 +563,10 @@ Example:
log.Println(message) log.Println(message)
} }
For an alternative implementation of So (that provides more flexible return
options) see the `So` function in the package at
github.com/smartystreets/assertions/assert.
#### type Assertion #### type Assertion
```go ```go

View File

@ -1,3 +0,0 @@
#ignore
-timeout=1s
-coverpkg=github.com/smartystreets/assertions,github.com/smartystreets/assertions/internal/oglematchers

View File

@ -227,7 +227,7 @@ func ShouldHaveLength(actual interface{}, expected ...interface{}) string {
if int64(value.Len()) == expectedLen { if int64(value.Len()) == expectedLen {
return success return success
} else { } else {
return fmt.Sprintf(shouldHaveHadLength, actual, value.Len(), expectedLen) return fmt.Sprintf(shouldHaveHadLength, expectedLen, value.Len(), actual)
} }
case reflect.Ptr: case reflect.Ptr:
elem := value.Elem() elem := value.Elem()
@ -236,7 +236,7 @@ func ShouldHaveLength(actual interface{}, expected ...interface{}) string {
if int64(elem.Len()) == expectedLen { if int64(elem.Len()) == expectedLen {
return success return success
} else { } else {
return fmt.Sprintf(shouldHaveHadLength, actual, elem.Len(), expectedLen) return fmt.Sprintf(shouldHaveHadLength, expectedLen, elem.Len(), actual)
} }
} }
} }

View File

@ -5,6 +5,8 @@
// They can also be used in traditional Go test functions and even in // They can also be used in traditional Go test functions and even in
// applications. // applications.
// //
// https://smartystreets.com
//
// Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library. // Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library.
// (https://github.com/jacobsa/oglematchers) // (https://github.com/jacobsa/oglematchers)
// The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library. // The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library.
@ -26,7 +28,7 @@ var serializer Serializer = new(noopSerializer)
// are very helpful and can be rendered in a DIFF view. In that case, this function // 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, // 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 // the assertions in this package will not serializer a JSON result, making
// standalone ussage more convenient. // standalone usage more convenient.
func GoConveyMode(yes bool) { func GoConveyMode(yes bool) {
if yes { if yes {
serializer = newSerializer() serializer = newSerializer()
@ -82,6 +84,8 @@ func (this *Assertion) So(actual interface{}, assert assertion, expected ...inte
// log.Println(message) // log.Println(message)
// } // }
// //
// For an alternative implementation of So (that provides more flexible return options)
// see the `So` function in the package at github.com/smartystreets/assertions/assert.
func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) { func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) {
if result := so(actual, assert, expected...); len(result) == 0 { if result := so(actual, assert, expected...); len(result) == 0 {
return true, result return true, result

View File

@ -0,0 +1,75 @@
package assertions
import "reflect"
type equalityMethodSpecification struct {
a interface{}
b interface{}
aType reflect.Type
bType reflect.Type
equalMethod reflect.Value
}
func newEqualityMethodSpecification(a, b interface{}) *equalityMethodSpecification {
return &equalityMethodSpecification{
a: a,
b: b,
}
}
func (this *equalityMethodSpecification) IsSatisfied() bool {
if !this.bothAreSameType() {
return false
}
if !this.typeHasEqualMethod() {
return false
}
if !this.equalMethodReceivesSameTypeForComparison() {
return false
}
if !this.equalMethodReturnsBool() {
return false
}
return true
}
func (this *equalityMethodSpecification) bothAreSameType() bool {
this.aType = reflect.TypeOf(this.a)
if this.aType == nil {
return false
}
if this.aType.Kind() == reflect.Ptr {
this.aType = this.aType.Elem()
}
this.bType = reflect.TypeOf(this.b)
return this.aType == this.bType
}
func (this *equalityMethodSpecification) typeHasEqualMethod() bool {
aInstance := reflect.ValueOf(this.a)
this.equalMethod = aInstance.MethodByName("Equal")
return this.equalMethod != reflect.Value{}
}
func (this *equalityMethodSpecification) equalMethodReceivesSameTypeForComparison() bool {
signature := this.equalMethod.Type()
return signature.NumIn() == 1 && signature.In(0) == this.aType
}
func (this *equalityMethodSpecification) equalMethodReturnsBool() bool {
signature := this.equalMethod.Type()
return signature.NumOut() == 1 && signature.Out(0) == reflect.TypeOf(true)
}
func (this *equalityMethodSpecification) AreEqual() bool {
a := reflect.ValueOf(this.a)
b := reflect.ValueOf(this.b)
return areEqual(a, b) && areEqual(b, a)
}
func areEqual(receiver reflect.Value, argument reflect.Value) bool {
equalMethod := receiver.MethodByName("Equal")
argumentList := []reflect.Value{argument}
result := equalMethod.Call(argumentList)
return result[0].Bool()
}

View File

@ -1,20 +1,22 @@
package assertions package assertions
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"math" "math"
"reflect" "reflect"
"strings" "strings"
"github.com/smartystreets/assertions/internal/oglematchers"
"github.com/smartystreets/assertions/internal/go-render/render" "github.com/smartystreets/assertions/internal/go-render/render"
"github.com/smartystreets/assertions/internal/oglematchers"
) )
// default acceptable delta for ShouldAlmostEqual // ShouldEqual receives exactly two parameters and does an equality check
const defaultDelta = 0.0000000001 // using the following semantics:
// 1. If the expected and actual values implement an Equal method in the form
// ShouldEqual receives exactly two parameters and does an equality check. // `func (this T) Equal(that T) bool` then call the method. If true, they are equal.
// 2. The expected and actual values are judged equal or not by oglematchers.Equals.
func ShouldEqual(actual interface{}, expected ...interface{}) string { func ShouldEqual(actual interface{}, expected ...interface{}) string {
if message := need(1, expected); message != success { if message := need(1, expected); message != success {
return message return message
@ -24,27 +26,35 @@ func ShouldEqual(actual interface{}, expected ...interface{}) string {
func shouldEqual(actual, expected interface{}) (message string) { func shouldEqual(actual, expected interface{}) (message string) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual)) message = serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual))
return
} }
}() }()
if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil { if spec := newEqualityMethodSpecification(expected, actual); spec.IsSatisfied() && spec.AreEqual() {
expectedSyntax := fmt.Sprintf("%v", expected) return success
actualSyntax := fmt.Sprintf("%v", actual) } else if matchError := oglematchers.Equals(expected).Matches(actual); matchError == nil {
if expectedSyntax == actualSyntax && reflect.TypeOf(expected) != reflect.TypeOf(actual) { return success
message = fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual)
} else {
message = fmt.Sprintf(shouldHaveBeenEqual, expected, actual)
}
message = serializer.serialize(expected, actual, message)
return
} }
return success return serializer.serialize(expected, actual, composeEqualityMismatchMessage(expected, actual))
}
func composeEqualityMismatchMessage(expected, actual interface{}) string {
var (
renderedExpected = fmt.Sprintf("%v", expected)
renderedActual = fmt.Sprintf("%v", actual)
)
if renderedExpected != renderedActual {
return fmt.Sprintf(shouldHaveBeenEqual+composePrettyDiff(renderedExpected, renderedActual), expected, actual)
} else if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
return fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual)
} else {
return fmt.Sprintf(shouldHaveBeenEqualNoResemblance, renderedExpected)
}
} }
// ShouldNotEqual receives exactly two parameters and does an inequality check. // ShouldNotEqual receives exactly two parameters and does an inequality check.
// See ShouldEqual for details on how equality is determined.
func ShouldNotEqual(actual interface{}, expected ...interface{}) string { func ShouldNotEqual(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success { if fail := need(1, expected); fail != success {
return fail return fail
@ -95,7 +105,7 @@ func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64
delta, err := getFloat(expected[1]) delta, err := getFloat(expected[1])
if err != nil { if err != nil {
return 0.0, 0.0, 0.0, "delta must be a numerical type" return 0.0, 0.0, 0.0, "The delta value " + err.Error()
} }
deltaFloat = delta deltaFloat = delta
@ -104,15 +114,13 @@ func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64
} }
actualFloat, err := getFloat(actual) actualFloat, err := getFloat(actual)
if err != nil { if err != nil {
return 0.0, 0.0, 0.0, err.Error() return 0.0, 0.0, 0.0, "The actual value " + err.Error()
} }
expectedFloat, err := getFloat(expected[0]) expectedFloat, err := getFloat(expected[0])
if err != nil { if err != nil {
return 0.0, 0.0, 0.0, err.Error() return 0.0, 0.0, 0.0, "The comparison value " + err.Error()
} }
return actualFloat, expectedFloat, deltaFloat, "" return actualFloat, expectedFloat, deltaFloat, ""
@ -139,10 +147,38 @@ func getFloat(num interface{}) (float64, error) {
numKind == reflect.Float64 { numKind == reflect.Float64 {
return numValue.Float(), nil return numValue.Float(), nil
} else { } else {
return 0.0, errors.New("must be a numerical type, but was " + numKind.String()) return 0.0, errors.New("must be a numerical type, but was: " + numKind.String())
} }
} }
// ShouldEqualJSON receives exactly two parameters and does an equality check by marshalling to JSON
func ShouldEqualJSON(actual interface{}, expected ...interface{}) string {
if message := need(1, expected); message != success {
return message
}
expectedString, expectedErr := remarshal(expected[0].(string))
if expectedErr != nil {
return "Expected value not valid JSON: " + expectedErr.Error()
}
actualString, actualErr := remarshal(actual.(string))
if actualErr != nil {
return "Actual value not valid JSON: " + actualErr.Error()
}
return ShouldEqual(actualString, expectedString)
}
func remarshal(value string) (string, error) {
var structured interface{}
err := json.Unmarshal([]byte(value), &structured)
if err != nil {
return "", err
}
canonical, _ := json.Marshal(structured)
return string(canonical), nil
}
// ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual) // ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual)
func ShouldResemble(actual interface{}, expected ...interface{}) string { func ShouldResemble(actual interface{}, expected ...interface{}) string {
if message := need(1, expected); message != success { if message := need(1, expected); message != success {
@ -150,8 +186,10 @@ func ShouldResemble(actual interface{}, expected ...interface{}) string {
} }
if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil { if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil {
return serializer.serializeDetailed(expected[0], actual, renderedExpected, renderedActual := render.Render(expected[0]), render.Render(actual)
fmt.Sprintf(shouldHaveResembled, render.Render(expected[0]), render.Render(actual))) message := fmt.Sprintf(shouldHaveResembled, renderedExpected, renderedActual) +
composePrettyDiff(renderedExpected, renderedActual)
return serializer.serializeDetailed(expected[0], actual, message)
} }
return success return success
@ -278,3 +316,16 @@ func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string {
} }
return success return success
} }
// ShouldBeZeroValue receives a single parameter and ensures that it is NOT
// the Go equivalent of the default value, or "zero" value.
func ShouldNotBeZeroValue(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(shouldNotHaveBeenZeroValue, actual))
}
return success
}

View File

@ -0,0 +1,37 @@
package assertions
import (
"fmt"
"github.com/smartystreets/assertions/internal/go-diff/diffmatchpatch"
)
func composePrettyDiff(expected, actual string) string {
diff := diffmatchpatch.New()
diffs := diff.DiffMain(expected, actual, false)
if prettyDiffIsLikelyToBeHelpful(diffs) {
return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs))
}
return ""
}
// prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains
// more 'equal' segments than 'deleted'/'inserted' segments.
func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool {
equal, deleted, inserted := measureDiffTypeLengths(diffs)
return equal > deleted && equal > inserted
}
func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) {
for _, segment := range diffs {
switch segment.Type {
case diffmatchpatch.DiffEqual:
equal += len(segment.Text)
case diffmatchpatch.DiffDelete:
deleted += len(segment.Text)
case diffmatchpatch.DiffInsert:
inserted += len(segment.Text)
}
}
return equal, deleted, inserted
}

View File

@ -6,6 +6,7 @@ const (
success = "" success = ""
needExactValues = "This assertion requires exactly %d comparison values (you provided %d)." needExactValues = "This assertion requires exactly %d comparison values (you provided %d)."
needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)." needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)."
needFewerValues = "This assertion allows %d or fewer comparison values (you provided %d)."
) )
func need(needed int, expected []interface{}) string { func need(needed int, expected []interface{}) string {
@ -16,8 +17,15 @@ func need(needed int, expected []interface{}) string {
} }
func atLeast(minimum int, expected []interface{}) string { func atLeast(minimum int, expected []interface{}) string {
if len(expected) < 1 { if len(expected) < minimum {
return needNonEmptyCollection return needNonEmptyCollection
} }
return success return success
} }
func atMost(max int, expected []interface{}) string {
if len(expected) > max {
return fmt.Sprintf(needFewerValues, max, len(expected))
}
return success
}

3
vendor/github.com/smartystreets/assertions/go.mod generated vendored Normal file
View File

@ -0,0 +1,3 @@
module github.com/smartystreets/assertions
go 1.12

View File

@ -12,32 +12,46 @@ import (
"strconv" "strconv"
) )
var implicitTypeMap = map[reflect.Kind]string{ var builtinTypeMap = map[reflect.Kind]string{
reflect.Bool: "bool", reflect.Bool: "bool",
reflect.String: "string", reflect.Complex128: "complex128",
reflect.Int: "int", reflect.Complex64: "complex64",
reflect.Int8: "int8", reflect.Float32: "float32",
reflect.Float64: "float64",
reflect.Int16: "int16", reflect.Int16: "int16",
reflect.Int32: "int32", reflect.Int32: "int32",
reflect.Int64: "int64", reflect.Int64: "int64",
reflect.Uint: "uint", reflect.Int8: "int8",
reflect.Uint8: "uint8", reflect.Int: "int",
reflect.String: "string",
reflect.Uint16: "uint16", reflect.Uint16: "uint16",
reflect.Uint32: "uint32", reflect.Uint32: "uint32",
reflect.Uint64: "uint64", reflect.Uint64: "uint64",
reflect.Float32: "float32", reflect.Uint8: "uint8",
reflect.Float64: "float64", reflect.Uint: "uint",
reflect.Complex64: "complex64", reflect.Uintptr: "uintptr",
reflect.Complex128: "complex128",
} }
var builtinTypeSet = map[string]struct{}{}
func init() {
for _, v := range builtinTypeMap {
builtinTypeSet[v] = struct{}{}
}
}
var typeOfString = reflect.TypeOf("")
var typeOfInt = reflect.TypeOf(int(1))
var typeOfUint = reflect.TypeOf(uint(1))
var typeOfFloat = reflect.TypeOf(10.1)
// Render converts a structure to a string representation. Unline the "%#v" // Render converts a structure to a string representation. Unline the "%#v"
// format string, this resolves pointer types' contents in structs, maps, and // format string, this resolves pointer types' contents in structs, maps, and
// slices/arrays and prints their field values. // slices/arrays and prints their field values.
func Render(v interface{}) string { func Render(v interface{}) string {
buf := bytes.Buffer{} buf := bytes.Buffer{}
s := (*traverseState)(nil) s := (*traverseState)(nil)
s.render(&buf, 0, reflect.ValueOf(v)) s.render(&buf, 0, reflect.ValueOf(v), false)
return buf.String() return buf.String()
} }
@ -72,7 +86,7 @@ func (s *traverseState) forkFor(ptr uintptr) *traverseState {
return fs return fs
} }
func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) { func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) {
if v.Kind() == reflect.Invalid { if v.Kind() == reflect.Invalid {
buf.WriteString("nil") buf.WriteString("nil")
return return
@ -107,49 +121,80 @@ func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) {
s = s.forkFor(pe) s = s.forkFor(pe)
if s == nil { if s == nil {
buf.WriteString("<REC(") buf.WriteString("<REC(")
writeType(buf, ptrs, vt) if !implicit {
writeType(buf, ptrs, vt)
}
buf.WriteString(")>") buf.WriteString(")>")
return return
} }
} }
isAnon := func(t reflect.Type) bool {
if t.Name() != "" {
if _, ok := builtinTypeSet[t.Name()]; !ok {
return false
}
}
return t.Kind() != reflect.Interface
}
switch vk { switch vk {
case reflect.Struct: case reflect.Struct:
writeType(buf, ptrs, vt) if !implicit {
writeType(buf, ptrs, vt)
}
buf.WriteRune('{') buf.WriteRune('{')
for i := 0; i < vt.NumField(); i++ { if rendered, ok := renderTime(v); ok {
if i > 0 { buf.WriteString(rendered)
buf.WriteString(", ") } else {
} structAnon := vt.Name() == ""
buf.WriteString(vt.Field(i).Name) for i := 0; i < vt.NumField(); i++ {
buf.WriteRune(':') if i > 0 {
buf.WriteString(", ")
}
anon := structAnon && isAnon(vt.Field(i).Type)
s.render(buf, 0, v.Field(i)) if !anon {
buf.WriteString(vt.Field(i).Name)
buf.WriteRune(':')
}
s.render(buf, 0, v.Field(i), anon)
}
} }
buf.WriteRune('}') buf.WriteRune('}')
case reflect.Slice: case reflect.Slice:
if v.IsNil() { if v.IsNil() {
writeType(buf, ptrs, vt) if !implicit {
buf.WriteString("(nil)") writeType(buf, ptrs, vt)
buf.WriteString("(nil)")
} else {
buf.WriteString("nil")
}
return return
} }
fallthrough fallthrough
case reflect.Array: case reflect.Array:
writeType(buf, ptrs, vt) if !implicit {
writeType(buf, ptrs, vt)
}
anon := vt.Name() == "" && isAnon(vt.Elem())
buf.WriteString("{") buf.WriteString("{")
for i := 0; i < v.Len(); i++ { for i := 0; i < v.Len(); i++ {
if i > 0 { if i > 0 {
buf.WriteString(", ") buf.WriteString(", ")
} }
s.render(buf, 0, v.Index(i)) s.render(buf, 0, v.Index(i), anon)
} }
buf.WriteRune('}') buf.WriteRune('}')
case reflect.Map: case reflect.Map:
writeType(buf, ptrs, vt) if !implicit {
writeType(buf, ptrs, vt)
}
if v.IsNil() { if v.IsNil() {
buf.WriteString("(nil)") buf.WriteString("(nil)")
} else { } else {
@ -158,14 +203,17 @@ func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) {
mkeys := v.MapKeys() mkeys := v.MapKeys()
tryAndSortMapKeys(vt, mkeys) tryAndSortMapKeys(vt, mkeys)
kt := vt.Key()
keyAnon := typeOfString.ConvertibleTo(kt) || typeOfInt.ConvertibleTo(kt) || typeOfUint.ConvertibleTo(kt) || typeOfFloat.ConvertibleTo(kt)
valAnon := vt.Name() == "" && isAnon(vt.Elem())
for i, mk := range mkeys { for i, mk := range mkeys {
if i > 0 { if i > 0 {
buf.WriteString(", ") buf.WriteString(", ")
} }
s.render(buf, 0, mk) s.render(buf, 0, mk, keyAnon)
buf.WriteString(":") buf.WriteString(":")
s.render(buf, 0, v.MapIndex(mk)) s.render(buf, 0, v.MapIndex(mk), valAnon)
} }
buf.WriteRune('}') buf.WriteRune('}')
} }
@ -176,11 +224,9 @@ func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) {
case reflect.Interface: case reflect.Interface:
if v.IsNil() { if v.IsNil() {
writeType(buf, ptrs, v.Type()) writeType(buf, ptrs, v.Type())
buf.WriteRune('(') buf.WriteString("(nil)")
fmt.Fprint(buf, "nil")
buf.WriteRune(')')
} else { } else {
s.render(buf, ptrs, v.Elem()) s.render(buf, ptrs, v.Elem(), false)
} }
case reflect.Chan, reflect.Func, reflect.UnsafePointer: case reflect.Chan, reflect.Func, reflect.UnsafePointer:
@ -191,7 +237,7 @@ func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) {
default: default:
tstr := vt.String() tstr := vt.String()
implicit := ptrs == 0 && implicitTypeMap[vk] == tstr implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr)
if !implicit { if !implicit {
writeType(buf, ptrs, vt) writeType(buf, ptrs, vt)
buf.WriteRune('(') buf.WriteRune('(')
@ -206,7 +252,7 @@ func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value) {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fmt.Fprintf(buf, "%d", v.Int()) fmt.Fprintf(buf, "%d", v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fmt.Fprintf(buf, "%d", v.Uint()) fmt.Fprintf(buf, "%d", v.Uint())
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
@ -288,40 +334,148 @@ func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) {
} }
} }
type cmpFn func(a, b reflect.Value) int
type sortableValueSlice struct { type sortableValueSlice struct {
kind reflect.Kind cmp cmpFn
elements []reflect.Value elements []reflect.Value
} }
func (s *sortableValueSlice) Len() int { func (s sortableValueSlice) Len() int {
return len(s.elements) return len(s.elements)
} }
func (s *sortableValueSlice) Less(i, j int) bool { func (s sortableValueSlice) Less(i, j int) bool {
switch s.kind { return s.cmp(s.elements[i], s.elements[j]) < 0
case reflect.String:
return s.elements[i].String() < s.elements[j].String()
case reflect.Int:
return s.elements[i].Int() < s.elements[j].Int()
default:
panic(fmt.Errorf("unsupported sort kind: %s", s.kind))
}
} }
func (s *sortableValueSlice) Swap(i, j int) { func (s sortableValueSlice) Swap(i, j int) {
s.elements[i], s.elements[j] = s.elements[j], s.elements[i] s.elements[i], s.elements[j] = s.elements[j], s.elements[i]
} }
func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) { // cmpForType returns a cmpFn which sorts the data for some type t in the same
// Try our stock sortable values. // order that a go-native map key is compared for equality.
switch mt.Key().Kind() { func cmpForType(t reflect.Type) cmpFn {
case reflect.String, reflect.Int: switch t.Kind() {
vs := &sortableValueSlice{ case reflect.String:
kind: mt.Key().Kind(), return func(av, bv reflect.Value) int {
elements: k, a, b := av.String(), bv.String()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
} }
sort.Sort(vs)
case reflect.Bool:
return func(av, bv reflect.Value) int {
a, b := av.Bool(), bv.Bool()
if !a && b {
return -1
} else if a && !b {
return 1
}
return 0
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return func(av, bv reflect.Value) int {
a, b := av.Int(), bv.Int()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32,
reflect.Uint64, reflect.Uintptr, reflect.UnsafePointer:
return func(av, bv reflect.Value) int {
a, b := av.Uint(), bv.Uint()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
}
case reflect.Float32, reflect.Float64:
return func(av, bv reflect.Value) int {
a, b := av.Float(), bv.Float()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
}
case reflect.Interface:
return func(av, bv reflect.Value) int {
a, b := av.InterfaceData(), bv.InterfaceData()
if a[0] < b[0] {
return -1
} else if a[0] > b[0] {
return 1
}
if a[1] < b[1] {
return -1
} else if a[1] > b[1] {
return 1
}
return 0
}
case reflect.Complex64, reflect.Complex128:
return func(av, bv reflect.Value) int {
a, b := av.Complex(), bv.Complex()
if real(a) < real(b) {
return -1
} else if real(a) > real(b) {
return 1
}
if imag(a) < imag(b) {
return -1
} else if imag(a) > imag(b) {
return 1
}
return 0
}
case reflect.Ptr, reflect.Chan:
return func(av, bv reflect.Value) int {
a, b := av.Pointer(), bv.Pointer()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
}
case reflect.Struct:
cmpLst := make([]cmpFn, t.NumField())
for i := range cmpLst {
cmpLst[i] = cmpForType(t.Field(i).Type)
}
return func(a, b reflect.Value) int {
for i, cmp := range cmpLst {
if rslt := cmp(a.Field(i), b.Field(i)); rslt != 0 {
return rslt
}
}
return 0
}
}
return nil
}
func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) {
if cmp := cmpForType(mt.Key()); cmp != nil {
sort.Sort(sortableValueSlice{cmp, k})
} }
} }

View File

@ -0,0 +1,26 @@
package render
import (
"reflect"
"time"
)
func renderTime(value reflect.Value) (string, bool) {
if instant, ok := convertTime(value); !ok {
return "", false
} else if instant.IsZero() {
return "0", true
} else {
return instant.String(), true
}
}
func convertTime(value reflect.Value) (t time.Time, ok bool) {
if value.Type() == timeType {
defer func() { recover() }()
t, ok = value.Interface().(time.Time)
}
return
}
var timeType = reflect.TypeOf(time.Time{})

View File

@ -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
}

View File

@ -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
}

View File

@ -28,7 +28,7 @@ func Contains(x interface{}) Matcher {
var ok bool var ok bool
if result.elementMatcher, ok = x.(Matcher); !ok { if result.elementMatcher, ok = x.(Matcher); !ok {
result.elementMatcher = Equals(x) result.elementMatcher = DeepEquals(x)
} }
return &result return &result

View File

@ -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
}

View File

@ -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())
}

View File

@ -1,37 +0,0 @@
// Copyright 2015 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"
)
// HasSameTypeAs returns a matcher that matches values with exactly the same
// type as the supplied prototype.
func HasSameTypeAs(p interface{}) Matcher {
expected := reflect.TypeOf(p)
pred := func(c interface{}) error {
actual := reflect.TypeOf(c)
if actual != expected {
return fmt.Errorf("which has type %v", actual)
}
return nil
}
return NewMatcher(pred, fmt.Sprintf("has type %v", expected))
}

View File

@ -1,46 +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 NewMatcher(
func(c interface{}) error { return hasSubstr(s, c) },
fmt.Sprintf("has substring \"%s\"", s))
}
func hasSubstr(needle string, 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, needle) {
return nil
}
return errors.New("")
}

View File

@ -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("")
}

View File

@ -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 supplied 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
}

View File

@ -1,43 +0,0 @@
// Copyright 2015 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
// Create a matcher with the given description and predicate function, which
// will be invoked to handle calls to Matchers.
//
// Using this constructor may be a convenience over defining your own type that
// implements Matcher if you do not need any logic in your Description method.
func NewMatcher(
predicate func(interface{}) error,
description string) Matcher {
return &predicateMatcher{
predicate: predicate,
description: description,
}
}
type predicateMatcher struct {
predicate func(interface{}) error
description string
}
func (pm *predicateMatcher) Matches(c interface{}) error {
return pm.predicate(c)
}
func (pm *predicateMatcher) Description() string {
return pm.description
}

View File

@ -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
}

View File

@ -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())
}

View File

@ -23,7 +23,7 @@ func transformDescription(m Matcher, newDesc string) Matcher {
} }
type transformDescriptionMatcher struct { type transformDescriptionMatcher struct {
desc string desc string
wrappedMatcher Matcher wrappedMatcher Matcher
} }

View File

@ -1,76 +1,85 @@
package assertions package assertions
const ( // equality const (
shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)" shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)"
shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!" shouldHaveBeenEqualNoResemblance = "Both the actual and expected values render equally ('%s') and their types are the same. Try using ShouldResemble instead."
shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)" shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!"
shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!" shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)"
shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!"
shouldHaveResembled = "Expected: '%#v'\nActual: '%#v'\n(Should resemble)!" shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!"
shouldHaveResembledTypeMismatch = "Expected: '%#v' (%T)\nActual: '%#v' (%T)\n(Should resemble, type mismatch)" shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!"
shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!"
shouldBePointers = "Both arguments should be pointers " shouldHaveResembled = "Expected: '%s'\nActual: '%s'\n(Should resemble)!"
shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!" shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!"
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')!" shouldBePointers = "Both arguments should be pointers "
shouldHaveBeenNil = "Expected: nil\nActual: '%v'" shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!"
shouldNotHaveBeenNil = "Expected '%+v' to NOT be nil (but it was)!" shouldHavePointedTo = "Expected '%+v' (address: '%v') and '%+v' (address: '%v') to be the same address (but their weren't)!"
shouldHaveBeenTrue = "Expected: true\nActual: %v" shouldNotHavePointedTo = "Expected '%+v' and '%+v' to be different references (but they matched: '%v')!"
shouldHaveBeenFalse = "Expected: false\nActual: %v"
shouldHaveBeenZeroValue = "'%+v' should have been the zero value" //"Expected: (zero value)\nActual: %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"
shouldNotHaveBeenZeroValue = "'%+v' should NOT have been the zero value"
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)!"
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)!" 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)!" 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')." 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 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)!"
shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!" shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!"
shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!" shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!"
shouldHaveContainedKey = "Expected the %v to contain the key: %v (but it didn't)!"
shouldNotHaveContainedKey = "Expected the %v NOT to contain the key: %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)!" shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!"
shouldHaveBeenAValidMap = "You must provide a valid map type (was %v)!"
shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!"
shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!"
shouldHaveBeenAValidInteger = "You must provide a valid integer (was %v)!"
shouldHaveBeenAValidLength = "You must provide a valid positive integer (was %v)!"
shouldHaveHadLength = "Expected %+v (length: %v) to have length equal to '%v', but it wasn't!"
)
const ( // strings shouldHaveContainedKey = "Expected the %v to contain the key: %v (but it didn't)!"
shouldHaveStartedWith = "Expected '%v'\nto start with '%v'\n(but it didn't)!" shouldNotHaveContainedKey = "Expected the %v NOT to contain the key: %v (but it did)!"
shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!" shouldHaveBeenAValidMap = "You must provide a valid map type (was %v)!"
shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!"
shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!" shouldHaveBeenIn = "Expected '%v' to be in the container (%v), but it wasn't!"
shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)." shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v), but it was!"
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)." shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!"
shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!"
shouldHaveBeenAValidInteger = "You must provide a valid integer (was %v)!"
shouldHaveBeenAValidLength = "You must provide a valid positive integer (was %v)!"
shouldHaveHadLength = "Expected collection to have length equal to [%v], but it's length was [%v] instead! contents: %+v"
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)!"
shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)."
shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)."
shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!" shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!"
shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it did)!" shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it did)!"
shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!"
shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!"
)
const ( // panics shouldBeString = "The argument to this assertion must be a string (you provided %v)."
shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!"
shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!"
shouldUseVoidNiladicFunction = "You must provide a void, niladic function as the first argument!" 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)!" shouldHavePanicked = "Expected func() to panic (but it didn't)!"
shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!" shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!"
shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!"
)
const ( // type checking shouldHavePanickedWith = "Expected func() to panic with '%v' (but it panicked with '%v')!"
shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!"
shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!" shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!"
shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!" shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!"
@ -78,17 +87,20 @@ const ( // type checking
shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!" 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)" 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!" shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!"
)
const ( // time comparisons shouldBeError = "Expected an error value (but was '%v' instead)!"
shouldUseTimes = "You must provide time instances as arguments to this assertion." shouldBeErrorInvalidComparisonValue = "The final argument to this assertion must be a string or an error value (you provided: '%v')."
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." 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)!" shouldHaveHappenedBefore = "Expected '%v' to happen before '%v' (it happened '%v' after)!"
shouldHaveHappenedAfter = "Expected '%v' to happen after '%v' (it happened '%v' before)!" 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)!" 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)!" 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 // 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!)" 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!)"
shouldNotHaveBeenchronological = "The provided times should NOT be chronological, but they were."
) )

View File

@ -43,7 +43,7 @@ func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) stri
if fail := need(1, expected); fail != success { if fail := need(1, expected); fail != success {
return fail return fail
} else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil { } else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil {
return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0]) return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0])
} }
return success return success
} }

View File

@ -3,6 +3,7 @@ package assertions
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings"
"github.com/smartystreets/assertions/internal/go-render/render" "github.com/smartystreets/assertions/internal/go-render/render"
) )
@ -15,28 +16,28 @@ type Serializer interface {
type failureSerializer struct{} type failureSerializer struct{}
func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string { func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string {
if index := strings.Index(message, " Diff:"); index > 0 {
message = message[:index]
}
view := FailureView{ view := FailureView{
Message: message, Message: message,
Expected: render.Render(expected), Expected: render.Render(expected),
Actual: render.Render(actual), Actual: render.Render(actual),
} }
serialized, err := json.Marshal(view) serialized, _ := json.Marshal(view)
if err != nil {
return message
}
return string(serialized) return string(serialized)
} }
func (self *failureSerializer) serialize(expected, actual interface{}, message string) string { func (self *failureSerializer) serialize(expected, actual interface{}, message string) string {
if index := strings.Index(message, " Diff:"); index > 0 {
message = message[:index]
}
view := FailureView{ view := FailureView{
Message: message, Message: message,
Expected: fmt.Sprintf("%+v", expected), Expected: fmt.Sprintf("%+v", expected),
Actual: fmt.Sprintf("%+v", actual), Actual: fmt.Sprintf("%+v", actual),
} }
serialized, err := json.Marshal(view) serialized, _ := json.Marshal(view)
if err != nil {
return message
}
return string(serialized) return string(serialized)
} }
@ -57,8 +58,8 @@ type FailureView struct {
/////////////////////////////////////////////////////// ///////////////////////////////////////////////////////
// noopSerializer just gives back the original message. This is useful when we are using // 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 // the assertions from a context other than the GoConvey Web UI, that requires the JSON
// provided by the failureSerializer. // structure provided by the failureSerializer.
type noopSerializer struct{} type noopSerializer struct{}
func (self *noopSerializer) serialize(expected, actual interface{}, message string) string { func (self *noopSerializer) serialize(expected, actual interface{}, message string) string {

View File

@ -178,7 +178,7 @@ func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string {
return ShouldNotHappenOnOrBetween(actualTime, min, max) return ShouldNotHappenOnOrBetween(actualTime, min, max)
} }
// ShouldBeChronological receives a []time.Time slice and asserts that the are // ShouldBeChronological receives a []time.Time slice and asserts that they are
// in chronological order starting with the first time.Time as the earliest. // in chronological order starting with the first time.Time as the earliest.
func ShouldBeChronological(actual interface{}, expected ...interface{}) string { func ShouldBeChronological(actual interface{}, expected ...interface{}) string {
if fail := need(0, expected); fail != success { if fail := need(0, expected); fail != success {
@ -200,3 +200,19 @@ func ShouldBeChronological(actual interface{}, expected ...interface{}) string {
} }
return "" return ""
} }
// ShouldNotBeChronological receives a []time.Time slice and asserts that they are
// NOT in chronological order.
func ShouldNotBeChronological(actual interface{}, expected ...interface{}) string {
if fail := need(0, expected); fail != success {
return fail
}
if _, ok := actual.([]time.Time); !ok {
return shouldUseTimeSlice
}
result := ShouldBeChronological(actual, expected...)
if result != "" {
return ""
}
return shouldNotHaveBeenchronological
}

View File

@ -14,9 +14,10 @@ func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
first := reflect.TypeOf(actual) first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0]) second := reflect.TypeOf(expected[0])
if equal := ShouldEqual(first, second); equal != success { if first != second {
return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first)) return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first))
} }
return success return success
} }
@ -29,7 +30,7 @@ func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string
first := reflect.TypeOf(actual) first := reflect.TypeOf(actual)
second := reflect.TypeOf(expected[0]) second := reflect.TypeOf(expected[0])
if equal := ShouldEqual(first, second); equal == success { if (actual == nil && expected[0] == nil) || first == second {
return fmt.Sprintf(shouldNotHaveBeenA, actual, second) return fmt.Sprintf(shouldNotHaveBeenA, actual, second)
} }
return success return success
@ -65,10 +66,6 @@ func ShouldImplement(actual interface{}, expectedList ...interface{}) string {
expectedInterface := expectedType.Elem() expectedInterface := expectedType.Elem()
if actualType == nil {
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual)
}
if !actualType.Implements(expectedInterface) { if !actualType.Implements(expectedInterface) {
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType) return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType)
} }
@ -110,3 +107,28 @@ func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string
} }
return success return success
} }
// ShouldBeError asserts that the first argument implements the error interface.
// It also compares the first argument against the second argument if provided
// (which must be an error message string or another error value).
func ShouldBeError(actual interface{}, expected ...interface{}) string {
if fail := atMost(1, expected); fail != success {
return fail
}
if !isError(actual) {
return fmt.Sprintf(shouldBeError, reflect.TypeOf(actual))
}
if len(expected) == 0 {
return success
}
if expected := expected[0]; !isString(expected) && !isError(expected) {
return fmt.Sprintf(shouldBeErrorInvalidComparisonValue, reflect.TypeOf(expected))
}
return ShouldEqual(fmt.Sprint(actual), fmt.Sprint(expected[0]))
}
func isString(value interface{}) bool { _, ok := value.(string); return ok }
func isError(value interface{}) bool { _, ok := value.(error); return ok }

View File

@ -16,6 +16,7 @@ var (
ShouldBeTrue = assertions.ShouldBeTrue ShouldBeTrue = assertions.ShouldBeTrue
ShouldBeFalse = assertions.ShouldBeFalse ShouldBeFalse = assertions.ShouldBeFalse
ShouldBeZeroValue = assertions.ShouldBeZeroValue ShouldBeZeroValue = assertions.ShouldBeZeroValue
ShouldNotBeZeroValue = assertions.ShouldNotBeZeroValue
ShouldBeGreaterThan = assertions.ShouldBeGreaterThan ShouldBeGreaterThan = assertions.ShouldBeGreaterThan
ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo
@ -65,4 +66,6 @@ var (
ShouldHappenWithin = assertions.ShouldHappenWithin ShouldHappenWithin = assertions.ShouldHappenWithin
ShouldNotHappenWithin = assertions.ShouldNotHappenWithin ShouldNotHappenWithin = assertions.ShouldNotHappenWithin
ShouldBeChronological = assertions.ShouldBeChronological ShouldBeChronological = assertions.ShouldBeChronological
ShouldBeError = assertions.ShouldBeError
) )

View File

@ -202,7 +202,7 @@ func SuppressConsoleStatistics() {
reporting.SuppressConsoleStatistics() reporting.SuppressConsoleStatistics()
} }
// ConsoleStatistics may be called at any time to print assertion statistics. // PrintConsoleStatistics may be called at any time to print assertion statistics.
// Generally, the best place to do this would be in a TestMain function, // Generally, the best place to do this would be in a TestMain function,
// after all tests have been run. Something like this: // after all tests have been run. Something like this:
// //

View File

@ -19,7 +19,7 @@ func ResolveExternalCaller() (file string, line int, name string) {
return return
} }
} }
file, line, name = "<unkown file>", -1, "<unknown name>" file, line, name = "<unknown file>", -1, "<unknown name>"
return // panic? return // panic?
} }

View File

@ -18,9 +18,9 @@ func init() {
} }
func declareFlags() { func declareFlags() {
flag.BoolVar(&json, "json", false, "When true, emits results in JSON blocks. Default: 'false'") flag.BoolVar(&json, "convey-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(&silent, "convey-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") flag.BoolVar(&story, "convey-story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirrors the value of the '-test.v' flag")
if noStoryFlagProvided() { if noStoryFlagProvided() {
story = verboseEnabled story = verboseEnabled

View File

@ -56,7 +56,7 @@ var (
dotError = "E" dotError = "E"
dotSkip = "S" dotSkip = "S"
errorTemplate = "* %s \nLine %d: - %v \n%s\n" errorTemplate = "* %s \nLine %d: - %v \n%s\n"
failureTemplate = "* %s \nLine %d:\n%s\n" failureTemplate = "* %s \nLine %d:\n%s\n%s\n"
) )
var ( var (
@ -71,7 +71,7 @@ var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole()))
func SuppressConsoleStatistics() { consoleStatistics.Suppress() } func SuppressConsoleStatistics() { consoleStatistics.Suppress() }
func PrintConsoleStatistics() { consoleStatistics.PrintSummary() } func PrintConsoleStatistics() { consoleStatistics.PrintSummary() }
// QuiteMode disables all console output symbols. This is only meant to be used // QuietMode 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 // for tests that are internal to goconvey where the output is distracting or
// otherwise not needed in the test output. // otherwise not needed in the test output.
func QuietMode() { func QuietMode() {

View File

@ -30,12 +30,15 @@ func (self *Printer) format(message string, values ...interface{}) string {
if len(values) == 0 { if len(values) == 0 {
formatted = self.prefix + message formatted = self.prefix + message
} else { } else {
formatted = self.prefix + fmt.Sprintf(message, values...) formatted = self.prefix + fmt_Sprintf(message, values...)
} }
indented := strings.Replace(formatted, newline, newline+self.prefix, -1) indented := strings.Replace(formatted, newline, newline+self.prefix, -1)
return strings.TrimRight(indented, space) return strings.TrimRight(indented, space)
} }
// Extracting fmt.Sprintf to a separate variable circumvents go vet, which, as of go 1.10 is run with go test.
var fmt_Sprintf = fmt.Sprintf
func (self *Printer) Indent() { func (self *Printer) Indent() {
self.prefix += pad self.prefix += pad
} }

View File

@ -53,7 +53,7 @@ func (self *problem) showFailures() {
self.out.Println("\nFailures:\n") self.out.Println("\nFailures:\n")
self.out.Indent() self.out.Indent()
} }
self.out.Println(failureTemplate, f.File, f.Line, f.Failure) self.out.Println(failureTemplate, f.File, f.Line, f.Failure, f.StackTrace)
} }
} }

View File

@ -1,12 +1,18 @@
package reporting package reporting
import "fmt" import (
"fmt"
"sync"
)
func (self *statistics) BeginStory(story *StoryReport) {} func (self *statistics) BeginStory(story *StoryReport) {}
func (self *statistics) Enter(scope *ScopeReport) {} func (self *statistics) Enter(scope *ScopeReport) {}
func (self *statistics) Report(report *AssertionResult) { func (self *statistics) Report(report *AssertionResult) {
self.Lock()
defer self.Unlock()
if !self.failing && report.Failure != "" { if !self.failing && report.Failure != "" {
self.failing = true self.failing = true
} }
@ -23,25 +29,36 @@ func (self *statistics) Report(report *AssertionResult) {
func (self *statistics) Exit() {} func (self *statistics) Exit() {}
func (self *statistics) EndStory() { func (self *statistics) EndStory() {
self.Lock()
defer self.Unlock()
if !self.suppressed { if !self.suppressed {
self.PrintSummary() self.printSummaryLocked()
} }
} }
func (self *statistics) Suppress() { func (self *statistics) Suppress() {
self.Lock()
defer self.Unlock()
self.suppressed = true self.suppressed = true
} }
func (self *statistics) PrintSummary() { func (self *statistics) PrintSummary() {
self.reportAssertions() self.Lock()
self.reportSkippedSections() defer self.Unlock()
self.completeReport() self.printSummaryLocked()
} }
func (self *statistics) reportAssertions() {
self.decideColor() func (self *statistics) printSummaryLocked() {
self.reportAssertionsLocked()
self.reportSkippedSectionsLocked()
self.completeReportLocked()
}
func (self *statistics) reportAssertionsLocked() {
self.decideColorLocked()
self.out.Print("\n%d total %s", self.total, plural("assertion", self.total)) self.out.Print("\n%d total %s", self.total, plural("assertion", self.total))
} }
func (self *statistics) decideColor() { func (self *statistics) decideColorLocked() {
if self.failing && !self.erroring { if self.failing && !self.erroring {
fmt.Print(yellowColor) fmt.Print(yellowColor)
} else if self.erroring { } else if self.erroring {
@ -50,13 +67,13 @@ func (self *statistics) decideColor() {
fmt.Print(greenColor) fmt.Print(greenColor)
} }
} }
func (self *statistics) reportSkippedSections() { func (self *statistics) reportSkippedSectionsLocked() {
if self.skipped > 0 { if self.skipped > 0 {
fmt.Print(yellowColor) fmt.Print(yellowColor)
self.out.Print(" (one or more sections skipped)") self.out.Print(" (one or more sections skipped)")
} }
} }
func (self *statistics) completeReport() { func (self *statistics) completeReportLocked() {
fmt.Print(resetColor) fmt.Print(resetColor)
self.out.Print("\n") self.out.Print("\n")
self.out.Print("\n") self.out.Print("\n")
@ -73,6 +90,8 @@ func NewStatisticsReporter(out *Printer) *statistics {
} }
type statistics struct { type statistics struct {
sync.Mutex
out *Printer out *Printer
total int total int
failing bool failing bool

View File

@ -0,0 +1,2 @@
#ignore
-timeout=1s

View File

@ -0,0 +1,164 @@
package api
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/smartystreets/goconvey/web/server/contract"
"github.com/smartystreets/goconvey/web/server/messaging"
)
type HTTPServer struct {
watcher chan messaging.WatcherCommand
executor contract.Executor
latest *contract.CompleteOutput
currentRoot string
longpoll chan chan string
paused bool
}
func (self *HTTPServer) ReceiveUpdate(root string, update *contract.CompleteOutput) {
self.currentRoot = root
self.latest = update
}
func (self *HTTPServer) Watch(response http.ResponseWriter, request *http.Request) {
if request.Method == "POST" {
self.adjustRoot(response, request)
} else if request.Method == "GET" {
response.Write([]byte(self.currentRoot))
}
}
func (self *HTTPServer) adjustRoot(response http.ResponseWriter, request *http.Request) {
newRoot := self.parseQueryString("root", response, request)
if newRoot == "" {
return
}
info, err := os.Stat(newRoot) // TODO: how to unit test?
if !info.IsDir() || err != nil {
http.Error(response, err.Error(), http.StatusNotFound)
return
}
self.watcher <- messaging.WatcherCommand{
Instruction: messaging.WatcherAdjustRoot,
Details: newRoot,
}
}
func (self *HTTPServer) Ignore(response http.ResponseWriter, request *http.Request) {
paths := self.parseQueryString("paths", response, request)
if paths != "" {
self.watcher <- messaging.WatcherCommand{
Instruction: messaging.WatcherIgnore,
Details: paths,
}
}
}
func (self *HTTPServer) Reinstate(response http.ResponseWriter, request *http.Request) {
paths := self.parseQueryString("paths", response, request)
if paths != "" {
self.watcher <- messaging.WatcherCommand{
Instruction: messaging.WatcherReinstate,
Details: paths,
}
}
}
func (self *HTTPServer) parseQueryString(key string, response http.ResponseWriter, request *http.Request) string {
value := request.URL.Query()[key]
if len(value) == 0 {
http.Error(response, fmt.Sprintf("No '%s' query string parameter included!", key), http.StatusBadRequest)
return ""
}
path := value[0]
if path == "" {
http.Error(response, "You must provide a non-blank path.", http.StatusBadRequest)
}
return path
}
func (self *HTTPServer) Status(response http.ResponseWriter, request *http.Request) {
status := self.executor.Status()
response.Write([]byte(status))
}
func (self *HTTPServer) LongPollStatus(response http.ResponseWriter, request *http.Request) {
if self.executor.ClearStatusFlag() {
response.Write([]byte(self.executor.Status()))
return
}
timeout, err := strconv.Atoi(request.URL.Query().Get("timeout"))
if err != nil || timeout > 180000 || timeout < 0 {
timeout = 60000 // default timeout is 60 seconds
}
myReqChan := make(chan string)
select {
case self.longpoll <- myReqChan: // this case means the executor's status is changing
case <-time.After(time.Duration(timeout) * time.Millisecond): // this case means the executor hasn't changed status
return
}
out := <-myReqChan
if out != "" { // TODO: Why is this check necessary? Sometimes it writes empty string...
response.Write([]byte(out))
}
}
func (self *HTTPServer) Results(response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
response.Header().Set("Pragma", "no-cache")
response.Header().Set("Expires", "0")
if self.latest != nil {
self.latest.Paused = self.paused
}
stuff, _ := json.Marshal(self.latest)
response.Write(stuff)
}
func (self *HTTPServer) Execute(response http.ResponseWriter, request *http.Request) {
go self.execute()
}
func (self *HTTPServer) execute() {
self.watcher <- messaging.WatcherCommand{Instruction: messaging.WatcherExecute}
}
func (self *HTTPServer) TogglePause(response http.ResponseWriter, request *http.Request) {
instruction := messaging.WatcherPause
if self.paused {
instruction = messaging.WatcherResume
}
self.watcher <- messaging.WatcherCommand{Instruction: instruction}
self.paused = !self.paused
fmt.Fprint(response, self.paused) // we could write out whatever helps keep the UI honest...
}
func NewHTTPServer(
root string,
watcher chan messaging.WatcherCommand,
executor contract.Executor,
status chan chan string) *HTTPServer {
self := new(HTTPServer)
self.currentRoot = root
self.watcher = watcher
self.executor = executor
self.longpoll = status
return self
}

View File

@ -0,0 +1,27 @@
package contract
import "net/http"
type (
Server interface {
ReceiveUpdate(root string, update *CompleteOutput)
Watch(writer http.ResponseWriter, request *http.Request)
Ignore(writer http.ResponseWriter, request *http.Request)
Reinstate(writer http.ResponseWriter, request *http.Request)
Status(writer http.ResponseWriter, request *http.Request)
LongPollStatus(writer http.ResponseWriter, request *http.Request)
Results(writer http.ResponseWriter, request *http.Request)
Execute(writer http.ResponseWriter, request *http.Request)
TogglePause(writer http.ResponseWriter, request *http.Request)
}
Executor interface {
ExecuteTests([]*Package) *CompleteOutput
Status() string
ClearStatusFlag() bool
}
Shell interface {
GoTest(directory, packageName string, tags, arguments []string) (output string, err error)
}
)

View File

@ -0,0 +1,100 @@
package contract
import (
"github.com/smartystreets/goconvey/convey/reporting"
"github.com/smartystreets/goconvey/web/server/messaging"
)
type Package struct {
Path string
Name string
Ignored bool
Disabled bool
BuildTags []string
TestArguments []string
Error error
Output string
Result *PackageResult
HasImportCycle bool
}
func NewPackage(folder *messaging.Folder, name string, hasImportCycle bool) *Package {
self := new(Package)
self.Path = folder.Path
self.Name = name
self.Result = NewPackageResult(self.Name)
self.Ignored = folder.Ignored
self.Disabled = folder.Disabled
self.BuildTags = folder.BuildTags
self.TestArguments = folder.TestArguments
self.HasImportCycle = hasImportCycle
return self
}
func (self *Package) Active() bool {
return !self.Disabled && !self.Ignored
}
func (self *Package) HasUsableResult() bool {
return self.Active() && (self.Error == nil || (self.Output != ""))
}
type CompleteOutput struct {
Packages []*PackageResult
Revision string
Paused bool
}
var ( // PackageResult.Outcome values:
Ignored = "ignored"
Disabled = "disabled"
Passed = "passed"
Failed = "failed"
Panicked = "panicked"
BuildFailure = "build failure"
NoTestFiles = "no test files"
NoTestFunctions = "no test functions"
NoGoFiles = "no go code"
TestRunAbortedUnexpectedly = "test run aborted unexpectedly"
)
type PackageResult struct {
PackageName string
Elapsed float64
Coverage float64
Outcome string
BuildOutput string
TestResults []TestResult
}
func NewPackageResult(packageName string) *PackageResult {
self := new(PackageResult)
self.PackageName = packageName
self.TestResults = []TestResult{}
self.Coverage = -1
return self
}
type TestResult struct {
TestName string
Elapsed float64
Passed bool
Skipped bool
File string
Line int
Message string
Error string
Stories []reporting.ScopeResult
RawLines []string `json:",omitempty"`
}
func NewTestResult(testName string) *TestResult {
self := new(TestResult)
self.Stories = []reporting.ScopeResult{}
self.RawLines = []string{}
self.TestName = testName
return self
}

View File

@ -0,0 +1,12 @@
package executor
import "github.com/smartystreets/goconvey/web/server/contract"
type Parser interface {
Parse([]*contract.Package)
}
type Tester interface {
SetBatchSize(batchSize int)
TestAll(folders []*contract.Package)
}

View File

@ -0,0 +1,71 @@
package executor
import (
"errors"
"fmt"
"log"
"strings"
"sync"
"github.com/smartystreets/goconvey/web/server/contract"
)
type concurrentCoordinator struct {
batchSize int
queue chan *contract.Package
folders []*contract.Package
shell contract.Shell
waiter sync.WaitGroup
}
func (self *concurrentCoordinator) ExecuteConcurrently() {
self.enlistWorkers()
self.scheduleTasks()
self.awaitCompletion()
}
func (self *concurrentCoordinator) enlistWorkers() {
for i := 0; i < self.batchSize; i++ {
self.waiter.Add(1)
go self.worker(i)
}
}
func (self *concurrentCoordinator) worker(id int) {
for folder := range self.queue {
packageName := strings.Replace(folder.Name, "\\", "/", -1)
if !folder.Active() {
log.Printf("Skipping concurrent execution: %s\n", packageName)
continue
}
if folder.HasImportCycle {
message := fmt.Sprintf("can't load package: import cycle not allowed\npackage %s\n\timports %s", packageName, packageName)
log.Println(message)
folder.Output, folder.Error = message, errors.New(message)
} else {
log.Printf("Executing concurrent tests: %s\n", packageName)
folder.Output, folder.Error = self.shell.GoTest(folder.Path, packageName, folder.BuildTags, folder.TestArguments)
}
}
self.waiter.Done()
}
func (self *concurrentCoordinator) scheduleTasks() {
for _, folder := range self.folders {
self.queue <- folder
}
}
func (self *concurrentCoordinator) awaitCompletion() {
close(self.queue)
self.waiter.Wait()
}
func newConcurrentCoordinator(folders []*contract.Package, batchSize int, shell contract.Shell) *concurrentCoordinator {
self := new(concurrentCoordinator)
self.queue = make(chan *contract.Package)
self.folders = folders
self.batchSize = batchSize
self.shell = shell
return self
}

View File

@ -0,0 +1,84 @@
package executor
import (
"log"
"time"
"github.com/smartystreets/goconvey/web/server/contract"
)
const (
Idle = "idle"
Executing = "executing"
)
type Executor struct {
tester Tester
parser Parser
status string
statusChan chan chan string
statusFlag bool
}
func (self *Executor) Status() string {
return self.status
}
func (self *Executor) ClearStatusFlag() bool {
hasNewStatus := self.statusFlag
self.statusFlag = false
return hasNewStatus
}
func (self *Executor) ExecuteTests(folders []*contract.Package) *contract.CompleteOutput {
defer func() { self.setStatus(Idle) }()
self.execute(folders)
result := self.parse(folders)
return result
}
func (self *Executor) execute(folders []*contract.Package) {
self.setStatus(Executing)
self.tester.TestAll(folders)
}
func (self *Executor) parse(folders []*contract.Package) *contract.CompleteOutput {
result := &contract.CompleteOutput{Revision: now().String()}
self.parser.Parse(folders)
for _, folder := range folders {
result.Packages = append(result.Packages, folder.Result)
}
return result
}
func (self *Executor) setStatus(status string) {
self.status = status
self.statusFlag = true
Loop:
for {
select {
case c := <-self.statusChan:
self.statusFlag = false
c <- status
default:
break Loop
}
}
log.Printf("Executor status: '%s'\n", self.status)
}
func NewExecutor(tester Tester, parser Parser, ch chan chan string) *Executor {
return &Executor{
tester: tester,
parser: parser,
status: Idle,
statusChan: ch,
statusFlag: false,
}
}
var now = func() time.Time {
return time.Now()
}

View File

@ -0,0 +1,2 @@
#ignore
-timeout=1s

View File

@ -0,0 +1,56 @@
package executor
import (
"errors"
"fmt"
"log"
"strings"
"github.com/smartystreets/goconvey/web/server/contract"
)
type ConcurrentTester struct {
shell contract.Shell
batchSize int
}
func (self *ConcurrentTester) SetBatchSize(batchSize int) {
self.batchSize = batchSize
log.Printf("Now configured to test %d packages concurrently.\n", self.batchSize)
}
func (self *ConcurrentTester) TestAll(folders []*contract.Package) {
if self.batchSize == 1 {
self.executeSynchronously(folders)
} else {
newConcurrentCoordinator(folders, self.batchSize, self.shell).ExecuteConcurrently()
}
return
}
func (self *ConcurrentTester) executeSynchronously(folders []*contract.Package) {
for _, folder := range folders {
packageName := strings.Replace(folder.Name, "\\", "/", -1)
if !folder.Active() {
log.Printf("Skipping execution: %s\n", packageName)
continue
}
if folder.HasImportCycle {
message := fmt.Sprintf("can't load package: import cycle not allowed\npackage %s\n\timports %s", packageName, packageName)
log.Println(message)
folder.Output, folder.Error = message, errors.New(message)
} else {
log.Printf("Executing tests: %s\n", packageName)
folder.Output, folder.Error = self.shell.GoTest(folder.Path, packageName, folder.BuildTags, folder.TestArguments)
}
}
}
func NewConcurrentTester(shell contract.Shell) *ConcurrentTester {
self := new(ConcurrentTester)
self.shell = shell
self.batchSize = defaultBatchSize
return self
}
const defaultBatchSize = 10

View File

@ -0,0 +1,56 @@
package messaging
///////////////////////////////////////////////////////////////////////////////
type WatcherCommand struct {
Instruction WatcherInstruction
Details string
}
type WatcherInstruction int
func (this WatcherInstruction) String() string {
switch this {
case WatcherPause:
return "Pause"
case WatcherResume:
return "Resume"
case WatcherIgnore:
return "Ignore"
case WatcherReinstate:
return "Reinstate"
case WatcherAdjustRoot:
return "AdjustRoot"
case WatcherExecute:
return "Execute"
case WatcherStop:
return "Stop"
default:
return "UNKNOWN INSTRUCTION"
}
}
const (
WatcherPause WatcherInstruction = iota
WatcherResume
WatcherIgnore
WatcherReinstate
WatcherAdjustRoot
WatcherExecute
WatcherStop
)
///////////////////////////////////////////////////////////////////////////////
type Folders map[string]*Folder
type Folder struct {
Path string // key
Root string
Ignored bool
Disabled bool
BuildTags []string
TestArguments []string
}
///////////////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,178 @@
package parser
import (
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"github.com/smartystreets/goconvey/web/server/contract"
)
var (
testNamePattern = regexp.MustCompile("^=== RUN:? +(.+)$")
)
func ParsePackageResults(result *contract.PackageResult, rawOutput string) {
newOutputParser(result, rawOutput).parse()
}
type outputParser struct {
raw string
lines []string
result *contract.PackageResult
tests []*contract.TestResult
// place holders for loops
line string
test *contract.TestResult
testMap map[string]*contract.TestResult
}
func newOutputParser(result *contract.PackageResult, rawOutput string) *outputParser {
self := new(outputParser)
self.raw = strings.TrimSpace(rawOutput)
self.lines = strings.Split(self.raw, "\n")
self.result = result
self.tests = []*contract.TestResult{}
self.testMap = make(map[string]*contract.TestResult)
return self
}
func (self *outputParser) parse() {
self.separateTestFunctionsAndMetadata()
self.parseEachTestFunction()
}
func (self *outputParser) separateTestFunctionsAndMetadata() {
for _, self.line = range self.lines {
if self.processNonTestOutput() {
break
}
self.processTestOutput()
}
}
func (self *outputParser) processNonTestOutput() bool {
if noGoFiles(self.line) {
self.recordFinalOutcome(contract.NoGoFiles)
} else if buildFailed(self.line) {
self.recordFinalOutcome(contract.BuildFailure)
} else if noTestFiles(self.line) {
self.recordFinalOutcome(contract.NoTestFiles)
} else if noTestFunctions(self.line) {
self.recordFinalOutcome(contract.NoTestFunctions)
} else {
return false
}
return true
}
func (self *outputParser) recordFinalOutcome(outcome string) {
self.result.Outcome = outcome
self.result.BuildOutput = strings.Join(self.lines, "\n")
}
func (self *outputParser) processTestOutput() {
self.line = strings.TrimSpace(self.line)
if isNewTest(self.line) {
self.registerTestFunction()
} else if isTestResult(self.line) {
self.recordTestMetadata()
} else if isPackageReport(self.line) {
self.recordPackageMetadata()
} else {
self.saveLineForParsingLater()
}
}
func (self *outputParser) registerTestFunction() {
testNameReg := testNamePattern.FindStringSubmatch(self.line)
if len(testNameReg) < 2 { // Test-related lines that aren't about a new test
return
}
self.test = contract.NewTestResult(testNameReg[1])
self.tests = append(self.tests, self.test)
self.testMap[self.test.TestName] = self.test
}
func (self *outputParser) recordTestMetadata() {
testName := strings.Split(self.line, " ")[2]
if test, ok := self.testMap[testName]; ok {
self.test = test
self.test.Passed = !strings.HasPrefix(self.line, "--- FAIL: ")
self.test.Skipped = strings.HasPrefix(self.line, "--- SKIP: ")
self.test.Elapsed = parseTestFunctionDuration(self.line)
}
}
func (self *outputParser) recordPackageMetadata() {
if packageFailed(self.line) {
self.recordTestingOutcome(contract.Failed)
} else if packagePassed(self.line) {
self.recordTestingOutcome(contract.Passed)
} else if isCoverageSummary(self.line) {
self.recordCoverageSummary(self.line)
}
}
func (self *outputParser) recordTestingOutcome(outcome string) {
self.result.Outcome = outcome
fields := strings.Split(self.line, "\t")
self.result.PackageName = strings.TrimSpace(fields[1])
self.result.Elapsed = parseDurationInSeconds(fields[2], 3)
}
func (self *outputParser) recordCoverageSummary(summary string) {
start := len("coverage: ")
end := strings.Index(summary, "%")
value := summary[start:end]
parsed, err := strconv.ParseFloat(value, 64)
if err != nil {
self.result.Coverage = -1
} else {
self.result.Coverage = parsed
}
}
func (self *outputParser) saveLineForParsingLater() {
self.line = strings.TrimLeft(self.line, "\t")
if self.test == nil {
fmt.Println("Potential error parsing output of", self.result.PackageName, "; couldn't handle this stray line:", self.line)
return
}
self.test.RawLines = append(self.test.RawLines, self.line)
}
// TestResults is a collection of TestResults that implements sort.Interface.
type TestResults []contract.TestResult
func (r TestResults) Len() int {
return len(r)
}
// Less compares TestResults on TestName
func (r TestResults) Less(i, j int) bool {
return r[i].TestName < r[j].TestName
}
func (r TestResults) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
func (self *outputParser) parseEachTestFunction() {
for _, self.test = range self.tests {
self.test = parseTestOutput(self.test)
if self.test.Error != "" {
self.result.Outcome = contract.Panicked
}
self.test.RawLines = []string{}
self.result.TestResults = append(self.result.TestResults, *self.test)
}
sort.Sort(TestResults(self.result.TestResults))
}

View File

@ -0,0 +1,32 @@
package parser
import (
"log"
"github.com/smartystreets/goconvey/web/server/contract"
)
type Parser struct {
parser func(*contract.PackageResult, string)
}
func (self *Parser) Parse(packages []*contract.Package) {
for _, p := range packages {
if p.Active() && p.HasUsableResult() {
self.parser(p.Result, p.Output)
} else if p.Ignored {
p.Result.Outcome = contract.Ignored
} else if p.Disabled {
p.Result.Outcome = contract.Disabled
} else {
p.Result.Outcome = contract.TestRunAbortedUnexpectedly
}
log.Printf("[%s]: %s\n", p.Result.Outcome, p.Name)
}
}
func NewParser(helper func(*contract.PackageResult, string)) *Parser {
self := new(Parser)
self.parser = helper
return self
}

View File

@ -0,0 +1,2 @@
#ignore
-timeout=1s

View File

@ -0,0 +1,45 @@
package parser
import "strings"
func noGoFiles(line string) bool {
return strings.HasPrefix(line, "can't load package: ") &&
(strings.Contains(line, ": no buildable Go source files in ") ||
strings.Contains(line, ": no Go ") ||
strings.Contains(line, "cannot find module providing package"))
}
func buildFailed(line string) bool {
return strings.HasPrefix(line, "# ") ||
strings.Contains(line, "cannot find package") ||
(strings.HasPrefix(line, "can't load package: ") && !strings.Contains(line, ": no Go ")) ||
(strings.Contains(line, ": found packages ") && strings.Contains(line, ".go) and ") && strings.Contains(line, ".go) in "))
}
func noTestFunctions(line string) bool {
return line == "testing: warning: no tests to run"
}
func noTestFiles(line string) bool {
return strings.HasPrefix(line, "?") && strings.Contains(line, "[no test files]")
}
func isNewTest(line string) bool {
return strings.HasPrefix(line, "=== ")
}
func isTestResult(line string) bool {
return strings.HasPrefix(line, "--- FAIL:") || strings.HasPrefix(line, "--- PASS:") || strings.HasPrefix(line, "--- SKIP:")
}
func isPackageReport(line string) bool {
return (strings.HasPrefix(line, "FAIL") ||
strings.HasPrefix(line, "exit status") ||
strings.HasPrefix(line, "PASS") ||
isCoverageSummary(line) ||
packagePassed(line))
}
func packageFailed(line string) bool {
return strings.HasPrefix(line, "FAIL\t")
}
func packagePassed(line string) bool {
return strings.HasPrefix(line, "ok \t")
}
func isCoverageSummary(line string) bool {
return strings.HasPrefix(line, "coverage: ") && strings.Contains(line, "% of statements")
}

View File

@ -0,0 +1,177 @@
package parser
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/smartystreets/goconvey/convey/reporting"
"github.com/smartystreets/goconvey/web/server/contract"
)
type testParser struct {
test *contract.TestResult
line string
index int
inJson bool
jsonLines []string
otherLines []string
}
func parseTestOutput(test *contract.TestResult) *contract.TestResult {
parser := newTestParser(test)
parser.parseTestFunctionOutput()
return test
}
func newTestParser(test *contract.TestResult) *testParser {
self := new(testParser)
self.test = test
return self
}
func (self *testParser) parseTestFunctionOutput() {
if len(self.test.RawLines) > 0 {
self.processLines()
self.deserializeJson()
self.composeCapturedOutput()
}
}
func (self *testParser) processLines() {
for self.index, self.line = range self.test.RawLines {
if !self.processLine() {
break
}
}
}
func (self *testParser) processLine() bool {
if strings.HasSuffix(self.line, reporting.OpenJson) {
self.inJson = true
self.accountForOutputWithoutNewline()
} else if self.line == reporting.CloseJson {
self.inJson = false
} else if self.inJson {
self.jsonLines = append(self.jsonLines, self.line)
} else if isPanic(self.line) {
self.parsePanicOutput()
return false
} else if isGoTestLogOutput(self.line) {
self.parseLogLocation()
} else {
self.otherLines = append(self.otherLines, self.line)
}
return true
}
// If fmt.Print(f) produces output with no \n and that output
// is that last output before the framework spits out json
// (which starts with ''>>>>>'') then without this code
// all of the json is counted as output, not as json to be
// parsed and displayed by the web UI.
func (self *testParser) accountForOutputWithoutNewline() {
prefix := strings.Split(self.line, reporting.OpenJson)[0]
if prefix != "" {
self.otherLines = append(self.otherLines, prefix)
}
}
func (self *testParser) deserializeJson() {
formatted := createArrayForJsonItems(self.jsonLines)
var scopes []reporting.ScopeResult
err := json.Unmarshal(formatted, &scopes)
if err != nil {
panic(fmt.Sprintf(bugReportRequest, err, formatted))
}
self.test.Stories = scopes
}
func (self *testParser) parsePanicOutput() {
for index, line := range self.test.RawLines[self.index:] {
self.parsePanicLocation(index, line)
self.preserveStackTraceIndentation(index, line)
}
self.test.Error = strings.Join(self.test.RawLines, "\n")
}
func (self *testParser) parsePanicLocation(index int, line string) {
if !panicLineHasMetadata(line) {
return
}
metaLine := self.test.RawLines[index+4]
fields := strings.Split(metaLine, " ")
fileAndLine := strings.Split(fields[0], ":")
self.test.File = fileAndLine[0]
if len(fileAndLine) >= 2 {
self.test.Line, _ = strconv.Atoi(fileAndLine[1])
}
}
func (self *testParser) preserveStackTraceIndentation(index int, line string) {
if panicLineShouldBeIndented(index, line) {
self.test.RawLines[index] = "\t" + line
}
}
func (self *testParser) parseLogLocation() {
self.otherLines = append(self.otherLines, self.line)
lineFields := strings.TrimSpace(self.line)
if strings.HasPrefix(lineFields, "Error Trace:") {
lineFields = strings.TrimPrefix(lineFields, "Error Trace:")
}
fields := strings.Split(lineFields, ":")
self.test.File = strings.TrimSpace(fields[0])
self.test.Line, _ = strconv.Atoi(fields[1])
}
func (self *testParser) composeCapturedOutput() {
self.test.Message = strings.Join(self.otherLines, "\n")
}
func createArrayForJsonItems(lines []string) []byte {
jsonArrayItems := strings.Join(lines, "")
jsonArrayItems = removeTrailingComma(jsonArrayItems)
return []byte(fmt.Sprintf("[%s]\n", jsonArrayItems))
}
func removeTrailingComma(rawJson string) string {
if trailingComma(rawJson) {
return rawJson[:len(rawJson)-1]
}
return rawJson
}
func trailingComma(value string) bool {
return strings.HasSuffix(value, ",")
}
func isGoTestLogOutput(line string) bool {
return strings.Count(line, ":") == 2
}
func isPanic(line string) bool {
return strings.HasPrefix(line, "panic: ")
}
func panicLineHasMetadata(line string) bool {
return strings.HasPrefix(line, "goroutine") && strings.Contains(line, "[running]")
}
func panicLineShouldBeIndented(index int, line string) bool {
return strings.Contains(line, "+") || (index > 0 && strings.Contains(line, "panic: "))
}
const bugReportRequest = `
Uh-oh! Looks like something went wrong. Please copy the following text and file a bug report at:
https://github.com/smartystreets/goconvey/issues?state=open
======= BEGIN BUG REPORT =======
ERROR: %v
OUTPUT: %s
======= END BUG REPORT =======
`

View File

@ -0,0 +1,49 @@
package parser
import (
"math"
"strings"
"time"
)
// parseTestFunctionDuration parses the duration in seconds as a float64
// from a line of go test output that looks something like this:
// --- PASS: TestOldSchool_PassesWithMessage (0.03 seconds)
func parseTestFunctionDuration(line string) float64 {
line = strings.Replace(line, "(", "", 1)
line = strings.Replace(line, ")", "", 1)
fields := strings.Split(line, " ")
return parseDurationInSeconds(fields[3], 2)
}
func parseDurationInSeconds(raw string, precision int) float64 {
elapsed, err := time.ParseDuration(raw)
if err != nil {
elapsed, _ = time.ParseDuration(raw + "s")
}
return round(elapsed.Seconds(), precision)
}
// round returns the rounded version of x with precision.
//
// Special cases are:
// round(±0) = ±0
// round(±Inf) = ±Inf
// round(NaN) = NaN
//
// Why, oh why doesn't the math package come with a round function?
// Inspiration: http://play.golang.org/p/ZmFfr07oHp
func round(x float64, precision int) float64 {
var rounder float64
pow := math.Pow(10, float64(precision))
intermediate := x * pow
if intermediate < 0.0 {
intermediate -= 0.5
} else {
intermediate += 0.5
}
rounder = float64(int64(intermediate))
return rounder / float64(pow)
}

View File

@ -0,0 +1,174 @@
package system
import (
"log"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
///////////////////////////////////////////////////////////////////////////////
// Integration: ///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
type Shell struct {
coverage bool
gobin string
reportsPath string
defaultTimeout string
}
func NewShell(gobin, reportsPath string, coverage bool, defaultTimeout string) *Shell {
return &Shell{
coverage: coverage,
gobin: gobin,
reportsPath: reportsPath,
defaultTimeout: defaultTimeout,
}
}
func (self *Shell) GoTest(directory, packageName string, tags, arguments []string) (output string, err error) {
reportFilename := strings.Replace(packageName, "/", "-", -1)
reportPath := filepath.Join(self.reportsPath, reportFilename)
reportData := reportPath + ".txt"
reportHTML := reportPath + ".html"
tagsArg := "-tags=" + strings.Join(tags, ",")
goconvey := findGoConvey(directory, self.gobin, packageName, tagsArg).Execute()
compilation := compile(directory, self.gobin, tagsArg).Execute()
withCoverage := runWithCoverage(compilation, goconvey, self.coverage, reportData, directory, self.gobin, self.defaultTimeout, tagsArg, arguments).Execute()
final := runWithoutCoverage(compilation, withCoverage, goconvey, directory, self.gobin, self.defaultTimeout, tagsArg, arguments).Execute()
go generateReports(final, self.coverage, directory, self.gobin, reportData, reportHTML).Execute()
return final.Output, final.Error
}
///////////////////////////////////////////////////////////////////////////////
// Functional Core:////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
func findGoConvey(directory, gobin, packageName, tagsArg string) Command {
return NewCommand(directory, gobin, "list", "-f", "'{{.TestImports}}{{.XTestImports}}'", tagsArg, packageName)
}
func compile(directory, gobin, tagsArg string) Command {
return NewCommand(directory, gobin, "test", "-i", tagsArg)
}
func runWithCoverage(compile, goconvey Command, coverage bool, reportPath, directory, gobin, defaultTimeout, tagsArg string, customArguments []string) Command {
if compile.Error != nil || goconvey.Error != nil {
return compile
}
if !coverage {
return compile
}
arguments := []string{"test", "-v", "-coverprofile=" + reportPath, tagsArg}
customArgsText := strings.Join(customArguments, "\t")
if !strings.Contains(customArgsText, "-covermode=") {
arguments = append(arguments, "-covermode=set")
}
if !strings.Contains(customArgsText, "-timeout=") {
arguments = append(arguments, "-timeout="+defaultTimeout)
}
if strings.Contains(goconvey.Output, goconveyDSLImport) {
arguments = append(arguments, "-convey-json")
}
arguments = append(arguments, customArguments...)
return NewCommand(directory, gobin, arguments...)
}
func runWithoutCoverage(compile, withCoverage, goconvey Command, directory, gobin, defaultTimeout, tagsArg string, customArguments []string) Command {
if compile.Error != nil {
return compile
}
if goconvey.Error != nil {
log.Println(gopathProblem, goconvey.Output, goconvey.Error)
return goconvey
}
if coverageStatementRE.MatchString(withCoverage.Output) {
return withCoverage
}
log.Printf("Coverage output: %v", withCoverage.Output)
log.Print("Run without coverage")
arguments := []string{"test", "-v", tagsArg}
customArgsText := strings.Join(customArguments, "\t")
if !strings.Contains(customArgsText, "-timeout=") {
arguments = append(arguments, "-timeout="+defaultTimeout)
}
if strings.Contains(goconvey.Output, goconveyDSLImport) {
arguments = append(arguments, "-convey-json")
}
arguments = append(arguments, customArguments...)
return NewCommand(directory, gobin, arguments...)
}
func generateReports(previous Command, coverage bool, directory, gobin, reportData, reportHTML string) Command {
if previous.Error != nil {
return previous
}
if !coverage {
return previous
}
return NewCommand(directory, gobin, "tool", "cover", "-html="+reportData, "-o", reportHTML)
}
///////////////////////////////////////////////////////////////////////////////
// Imperative Shell: //////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
type Command struct {
directory string
executable string
arguments []string
Output string
Error error
}
func NewCommand(directory, executable string, arguments ...string) Command {
return Command{
directory: directory,
executable: executable,
arguments: arguments,
}
}
func (this Command) Execute() Command {
if len(this.executable) == 0 {
return this
}
if len(this.Output) > 0 || this.Error != nil {
return this
}
command := exec.Command(this.executable, this.arguments...)
command.Dir = this.directory
var rawOutput []byte
rawOutput, this.Error = command.CombinedOutput()
this.Output = string(rawOutput)
return this
}
///////////////////////////////////////////////////////////////////////////////
const goconveyDSLImport = "github.com/smartystreets/goconvey/convey " // note the trailing space: we don't want to target packages nested in the /convey package.
const gopathProblem = "Please run goconvey from within $GOPATH/src (also, symlinks might be problematic). Output and Error: "
var coverageStatementRE = regexp.MustCompile(`(?m)^coverage: \d+\.\d% of statements(.*)$|^panic: test timed out after `)

View File

@ -0,0 +1,3 @@
#ignore
-timeout=1s
-short

View File

@ -0,0 +1,171 @@
package watch
import (
"os"
"path/filepath"
"strings"
"github.com/smartystreets/goconvey/web/server/messaging"
)
///////////////////////////////////////////////////////////////////////////////
func Categorize(items chan *FileSystemItem, root string, watchSuffixes []string) (folders, profiles, goFiles []*FileSystemItem) {
for item := range items {
if item.IsFolder && !isHidden(item.Name) && !foundInHiddenDirectory(item, root) {
folders = append(folders, item)
} else if strings.HasSuffix(item.Name, ".goconvey") && len(item.Name) > len(".goconvey") {
profiles = append(profiles, item)
} else {
for _, suffix := range watchSuffixes {
if strings.HasSuffix(item.Name, suffix) && !isHidden(item.Name) && !foundInHiddenDirectory(item, root) {
goFiles = append(goFiles, item)
}
}
}
}
return folders, profiles, goFiles
}
func foundInHiddenDirectory(item *FileSystemItem, root string) bool {
path := item.Path
if len(path) > len(root) {
path = path[len(root):]
}
for _, folder := range strings.Split(filepath.Dir(path), slash) {
if isHidden(folder) {
return true
}
}
return false
}
func isHidden(path string) bool {
return strings.HasPrefix(path, ".") || strings.HasPrefix(path, "_") || strings.HasPrefix(path, "flymake_")
}
///////////////////////////////////////////////////////////////////////////////
func ParseProfile(profile string) (isDisabled bool, tags, arguments []string) {
lines := strings.Split(profile, "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if len(arguments) == 0 && strings.ToLower(line) == "ignore" {
return true, nil, nil
} else if strings.HasPrefix(line, "-tags=") {
tags = append(tags, strings.Split(strings.SplitN(line, "=", 2)[1], ",")...)
continue
} else if len(line) == 0 {
continue
} else if strings.HasPrefix(line, "#") {
continue
} else if strings.HasPrefix(line, "//") {
continue
} else if line == "-cover" || strings.HasPrefix(line, "-coverprofile") {
continue
} else if line == "-v" {
continue // Verbose mode is always enabled so there is no need to record it here.
}
arguments = append(arguments, line)
}
return false, tags, arguments
}
///////////////////////////////////////////////////////////////////////////////
func CreateFolders(items []*FileSystemItem) messaging.Folders {
folders := map[string]*messaging.Folder{}
for _, item := range items {
folders[item.Path] = &messaging.Folder{Path: item.Path, Root: item.Root}
}
return folders
}
///////////////////////////////////////////////////////////////////////////////
func LimitDepth(folders messaging.Folders, depth int) {
if depth < 0 {
return
}
for path, folder := range folders {
if strings.Count(path[len(folder.Root):], slash) > depth {
delete(folders, path)
}
}
}
///////////////////////////////////////////////////////////////////////////////
func AttachProfiles(folders messaging.Folders, items []*FileSystemItem) {
for _, profile := range items {
if folder, exists := folders[filepath.Dir(profile.Path)]; exists {
folder.Disabled, folder.BuildTags, folder.TestArguments = profile.ProfileDisabled, profile.ProfileTags, profile.ProfileArguments
}
}
}
///////////////////////////////////////////////////////////////////////////////
func MarkIgnored(folders messaging.Folders, ignored map[string]struct{}) {
if len(ignored) == 0 {
return
}
for _, folder := range folders {
for ignored := range ignored {
if !folder.Ignored && strings.HasSuffix(folder.Path, ignored) {
folder.Ignored = true
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
func ActiveFolders(folders messaging.Folders) messaging.Folders {
var active messaging.Folders = map[string]*messaging.Folder{}
for path, folder := range folders {
if folder.Ignored || folder.Disabled {
continue
}
active[path] = folder
}
return active
}
///////////////////////////////////////////////////////////////////////////////
func Sum(folders messaging.Folders, items []*FileSystemItem) int64 {
var sum int64
for _, item := range items {
if _, exists := folders[filepath.Dir(item.Path)]; exists {
sum += item.Size + item.Modified
}
}
return sum
}
///////////////////////////////////////////////////////////////////////////////
const slash = string(os.PathSeparator)
///////////////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,82 @@
package watch
import (
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
///////////////////////////////////////////////////////////////////////////////
type FileSystemItem struct {
Root string
Path string
Name string
Size int64
Modified int64
IsFolder bool
ProfileDisabled bool
ProfileTags []string
ProfileArguments []string
}
///////////////////////////////////////////////////////////////////////////////
func YieldFileSystemItems(root string, excludedDirs []string) chan *FileSystemItem {
items := make(chan *FileSystemItem)
go func() {
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return filepath.SkipDir
}
if info.IsDir() && strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
basePath := filepath.Base(path)
for _, item := range excludedDirs {
if item == basePath && info.IsDir() && item != "" && basePath != "" {
return filepath.SkipDir
}
}
items <- &FileSystemItem{
Root: root,
Path: path,
Name: info.Name(),
Size: info.Size(),
Modified: info.ModTime().Unix(),
IsFolder: info.IsDir(),
}
return nil
})
close(items)
}()
return items
}
///////////////////////////////////////////////////////////////////////////////
// ReadContents reads files wholesale. This function is only called on files
// that end in '.goconvey'. These files should be very small, probably not
// ever more than a few hundred bytes. The ignored errors are ok because in
// the event of an IO error all that need be returned is an empty string.
func ReadContents(path string) string {
file, err := os.Open(path)
if err != nil {
return ""
}
defer file.Close()
reader := io.LimitReader(file, 1024*4)
content, _ := ioutil.ReadAll(reader)
return string(content)
}
///////////////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,183 @@
package watch
import (
"log"
"os"
"strings"
"sync"
"time"
"github.com/smartystreets/goconvey/web/server/messaging"
)
type Watcher struct {
nap time.Duration
rootFolder string
folderDepth int
ignoredFolders map[string]struct{}
fileSystemState int64
paused bool
stopped bool
watchSuffixes []string
excludedDirs []string
input chan messaging.WatcherCommand
output chan messaging.Folders
lock sync.RWMutex
}
func NewWatcher(rootFolder string, folderDepth int, nap time.Duration,
input chan messaging.WatcherCommand, output chan messaging.Folders, watchSuffixes string, excludedDirs []string) *Watcher {
return &Watcher{
nap: nap,
rootFolder: rootFolder,
folderDepth: folderDepth,
input: input,
output: output,
watchSuffixes: strings.Split(watchSuffixes, ","),
excludedDirs: excludedDirs,
ignoredFolders: make(map[string]struct{}),
}
}
func (this *Watcher) Listen() {
for {
if this.stopped {
return
}
select {
case command := <-this.input:
this.respond(command)
default:
if !this.paused {
this.scan()
}
time.Sleep(this.nap)
}
}
}
func (this *Watcher) respond(command messaging.WatcherCommand) {
switch command.Instruction {
case messaging.WatcherAdjustRoot:
log.Println("Adjusting root...")
this.rootFolder = command.Details
this.execute()
case messaging.WatcherIgnore:
log.Println("Ignoring specified folders")
this.ignore(command.Details)
// Prevent a filesystem change due to the number of active folders changing
_, checksum := this.gather()
this.set(checksum)
case messaging.WatcherReinstate:
log.Println("Reinstating specified folders")
this.reinstate(command.Details)
// Prevent a filesystem change due to the number of active folders changing
_, checksum := this.gather()
this.set(checksum)
case messaging.WatcherPause:
log.Println("Pausing watcher...")
this.paused = true
case messaging.WatcherResume:
log.Println("Resuming watcher...")
this.paused = false
case messaging.WatcherExecute:
log.Println("Gathering folders for immediate execution...")
this.execute()
case messaging.WatcherStop:
log.Println("Stopping the watcher...")
close(this.output)
this.stopped = true
default:
log.Println("Unrecognized command from server:", command.Instruction)
}
}
func (this *Watcher) execute() {
folders, _ := this.gather()
this.sendToExecutor(folders)
}
func (this *Watcher) scan() {
folders, checksum := this.gather()
if checksum == this.fileSystemState {
return
}
log.Println("File system state modified, publishing current folders...", this.fileSystemState, checksum)
defer this.set(checksum)
this.sendToExecutor(folders)
}
func (this *Watcher) gather() (folders messaging.Folders, checksum int64) {
items := YieldFileSystemItems(this.rootFolder, this.excludedDirs)
folderItems, profileItems, goFileItems := Categorize(items, this.rootFolder, this.watchSuffixes)
for _, item := range profileItems {
// TODO: don't even bother if the item's size is over a few hundred bytes...
contents := ReadContents(item.Path)
item.ProfileDisabled, item.ProfileTags, item.ProfileArguments = ParseProfile(contents)
}
folders = CreateFolders(folderItems)
LimitDepth(folders, this.folderDepth)
AttachProfiles(folders, profileItems)
this.protectedRead(func() { MarkIgnored(folders, this.ignoredFolders) })
active := ActiveFolders(folders)
checksum = int64(len(active))
checksum += Sum(active, profileItems)
checksum += Sum(active, goFileItems)
return folders, checksum
}
func (this *Watcher) set(state int64) {
this.fileSystemState = state
}
func (this *Watcher) sendToExecutor(folders messaging.Folders) {
this.output <- folders
}
func (this *Watcher) ignore(paths string) {
this.protectedWrite(func() {
for _, folder := range strings.Split(paths, string(os.PathListSeparator)) {
this.ignoredFolders[folder] = struct{}{}
log.Println("Currently ignored folders:", this.ignoredFolders)
}
})
}
func (this *Watcher) reinstate(paths string) {
this.protectedWrite(func() {
for _, folder := range strings.Split(paths, string(os.PathListSeparator)) {
delete(this.ignoredFolders, folder)
}
})
}
func (this *Watcher) protectedWrite(protected func()) {
this.lock.Lock()
defer this.lock.Unlock()
protected()
}
func (this *Watcher) protectedRead(protected func()) {
this.lock.RLock()
defer this.lock.RUnlock()
protected()
}

View File

@ -0,0 +1,3 @@
#ignore
-timeout=1s
-short

78
vendor/vendor.json vendored
View File

@ -471,22 +471,22 @@
"revisionTime": "2016-09-18T04:11:01Z" "revisionTime": "2016-09-18T04:11:01Z"
}, },
{ {
"checksumSHA1": "OieGcyWgc9NzZb4TWXcufX560pc=", "checksumSHA1": "dqFYWn+mMsT6NP+k3Z3l5XMPbGw=",
"path": "github.com/smartystreets/assertions", "path": "github.com/smartystreets/assertions",
"revision": "287b4346dc4e71a038c346375a9d572453bc469b", "revision": "b2515dfb413c5270515e0dc2e18bbbda06ff0bf8",
"revisionTime": "2016-02-05T03:39:31Z" "revisionTime": "2019-07-19T19:21:57Z"
}, },
{ {
"checksumSHA1": "9iA8MD7dsY0eid8vy+1ixJHkR+M=", "checksumSHA1": "v6W3GIQMzr3QSXB2NtBa9X7SwiI=",
"path": "github.com/smartystreets/assertions/internal/go-render/render", "path": "github.com/smartystreets/assertions/internal/go-render/render",
"revision": "287b4346dc4e71a038c346375a9d572453bc469b", "revision": "b2515dfb413c5270515e0dc2e18bbbda06ff0bf8",
"revisionTime": "2016-02-05T03:39:31Z" "revisionTime": "2019-07-19T19:21:57Z"
}, },
{ {
"checksumSHA1": "QCsUvPHx/Ifqm+sJmocjSvePAIc=", "checksumSHA1": "r6FauVdOTFnwYQgrKGFuWUbIAJE=",
"path": "github.com/smartystreets/assertions/internal/oglematchers", "path": "github.com/smartystreets/assertions/internal/oglematchers",
"revision": "287b4346dc4e71a038c346375a9d572453bc469b", "revision": "b2515dfb413c5270515e0dc2e18bbbda06ff0bf8",
"revisionTime": "2016-02-05T03:39:31Z" "revisionTime": "2019-07-19T19:21:57Z"
}, },
{ {
"checksumSHA1": "7E7jpXiYAxa4vxc+2ftP4aBrDy8=", "checksumSHA1": "7E7jpXiYAxa4vxc+2ftP4aBrDy8=",
@ -495,22 +495,64 @@
"revisionTime": "2019-07-10T18:59:42Z" "revisionTime": "2019-07-10T18:59:42Z"
}, },
{ {
"checksumSHA1": "fQeXVv5U9dlo3ufH2vjk1GNf4Lo=", "checksumSHA1": "clSz8OLgNZgATQ7mKB80ZRDdxDs=",
"path": "github.com/smartystreets/goconvey/convey", "path": "github.com/smartystreets/goconvey/convey",
"revision": "bf58a9a1291224109919756b4dcc469c670cc7e4", "revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2016-02-05T03:35:52Z" "revisionTime": "2019-07-10T18:59:42Z"
}, },
{ {
"checksumSHA1": "9LakndErFi5uCXtY1KWl0iRnT4c=", "checksumSHA1": "6Mgn4H/4vpqYGlaIKZ0UwOmJN0E=",
"path": "github.com/smartystreets/goconvey/convey/gotest", "path": "github.com/smartystreets/goconvey/convey/gotest",
"revision": "bf58a9a1291224109919756b4dcc469c670cc7e4", "revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2016-02-05T03:35:52Z" "revisionTime": "2019-07-10T18:59:42Z"
}, },
{ {
"checksumSHA1": "4NSMMeBraoAH+oebwoNzR9z25MM=", "checksumSHA1": "zUFddnpn7/A+gjwhShq642PM40I=",
"path": "github.com/smartystreets/goconvey/convey/reporting", "path": "github.com/smartystreets/goconvey/convey/reporting",
"revision": "bf58a9a1291224109919756b4dcc469c670cc7e4", "revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2016-02-05T03:35:52Z" "revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "DjCJPoeFDfYI7LsteLMhxwDEnoE=",
"path": "github.com/smartystreets/goconvey/web/server/api",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "Z+Mne86XlzUBRu8yCIoZVvRbieQ=",
"path": "github.com/smartystreets/goconvey/web/server/contract",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "pWkPFCaZP+x5SZVw/QG/FKl94SA=",
"path": "github.com/smartystreets/goconvey/web/server/executor",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "yaYihYltKDF/h2vuiUx8KbnsWMU=",
"path": "github.com/smartystreets/goconvey/web/server/messaging",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "eq6QaILIjLAbT+PsxeI9YzIhZeY=",
"path": "github.com/smartystreets/goconvey/web/server/parser",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "msXwJmK2tEpVWDyOETUCs3cHaho=",
"path": "github.com/smartystreets/goconvey/web/server/system",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
},
{
"checksumSHA1": "3GcDERpXpjAF3Y/tRRGnfZ0suOk=",
"path": "github.com/smartystreets/goconvey/web/server/watch",
"revision": "9d28bd7c0945047857c9740bd2eb3d62f98d3d35",
"revisionTime": "2019-07-10T18:59:42Z"
}, },
{ {
"checksumSHA1": "j+CXOooI5VyVEhKPTJkuL/GHPE0=", "checksumSHA1": "j+CXOooI5VyVEhKPTJkuL/GHPE0=",