updated dependencies

This commit is contained in:
Torkel Ödegaard 2016-08-01 14:15:41 +02:00
parent 357358898d
commit e6c4e47849
143 changed files with 2370 additions and 17306 deletions

33
Godeps/Godeps.json generated
View File

@ -276,6 +276,14 @@
"Comment": "go.weekly.2011-12-22-27-ge6ac2fc",
"Rev": "e6ac2fc51e89a3249e82157fa0bb7a18ef9dd5bb"
},
{
"ImportPath": "github.com/kr/s3",
"Rev": "c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d"
},
{
"ImportPath": "github.com/kr/s3/s3util",
"Rev": "c070c8f9a8f0032d48f0d2a77d4e382788bd8a1d"
},
{
"ImportPath": "github.com/kr/text",
"Rev": "bb797dc4fb8320488f47bf11de07a733d7233e1f"
@ -307,21 +315,26 @@
"ImportPath": "github.com/rainycape/unidecode",
"Rev": "836ef0a715aedf08a12d595ed73ec8ed5b288cac"
},
{
"ImportPath": "github.com/smartystreets/assertions",
"Comment": "1.6.0-6-g40711f7",
"Rev": "40711f7748186bbf9c99977cd89f21ce1a229447"
},
{
"ImportPath": "github.com/smartystreets/assertions/internal/go-render/render",
"Comment": "1.6.0-6-g40711f7",
"Rev": "40711f7748186bbf9c99977cd89f21ce1a229447"
},
{
"ImportPath": "github.com/smartystreets/assertions/internal/oglematchers",
"Comment": "1.6.0-6-g40711f7",
"Rev": "40711f7748186bbf9c99977cd89f21ce1a229447"
},
{
"ImportPath": "github.com/smartystreets/goconvey/convey",
"Comment": "1.5.0-356-gfbc0a1c",
"Rev": "fbc0a1c888f9f96263f9a559d1769905245f1123"
},
{
"ImportPath": "github.com/smartystreets/goconvey/convey/assertions",
"Comment": "1.5.0-356-gfbc0a1c",
"Rev": "fbc0a1c888f9f96263f9a559d1769905245f1123"
},
{
"ImportPath": "github.com/smartystreets/goconvey/convey/assertions/oglematchers",
"Comment": "1.5.0-356-gfbc0a1c",
"Rev": "fbc0a1c888f9f96263f9a559d1769905245f1123"
},
{
"ImportPath": "github.com/smartystreets/goconvey/convey/gotest",
"Comment": "1.5.0-356-gfbc0a1c",

19
Godeps/_workspace/src/github.com/kr/s3/License generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2012 Keith Rarick.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

4
Godeps/_workspace/src/github.com/kr/s3/Readme generated vendored Normal file
View File

@ -0,0 +1,4 @@
Package s3 signs HTTP requests for use with Amazons S3 API.
Documentation:
http://godoc.org/github.com/kr/s3

4
Godeps/_workspace/src/github.com/kr/s3/s3util/Readme generated vendored Normal file
View File

@ -0,0 +1,4 @@
Package s3util provides streaming transfers to and from Amazon S3.
Full documentation:
http://godoc.org/github.com/kr/s3/s3util

View File

@ -0,0 +1,27 @@
// Package s3util provides streaming transfers to and from Amazon S3.
//
// To use it, open or create an S3 object, read or write data,
// and close the object.
//
// You must assign valid credentials to DefaultConfig.Keys before using
// DefaultConfig. Be sure to close an io.WriteCloser returned by this package,
// to flush buffers and complete the multipart upload process.
package s3util
// TODO(kr): parse error responses; return structured data
import (
"github.com/kr/s3"
"net/http"
)
var DefaultConfig = &Config{
Service: s3.DefaultService,
Keys: new(s3.Keys),
}
type Config struct {
*s3.Service
*s3.Keys
*http.Client // if nil, uses http.DefaultClient
}

29
Godeps/_workspace/src/github.com/kr/s3/s3util/error.go generated vendored Normal file
View File

@ -0,0 +1,29 @@
package s3util
import (
"bytes"
"fmt"
"io"
"net/http"
)
type respError struct {
r *http.Response
b bytes.Buffer
}
func newRespError(r *http.Response) *respError {
e := new(respError)
e.r = r
io.Copy(&e.b, r.Body)
r.Body.Close()
return e
}
func (e *respError) Error() string {
return fmt.Sprintf(
"unwanted http status %d: %q",
e.r.StatusCode,
e.b.String(),
)
}

33
Godeps/_workspace/src/github.com/kr/s3/s3util/open.go generated vendored Normal file
View File

@ -0,0 +1,33 @@
package s3util
import (
"io"
"net/http"
"time"
)
// Open requests the S3 object at url. An HTTP status other than 200 is
// considered an error.
//
// If c is nil, Open uses DefaultConfig.
func Open(url string, c *Config) (io.ReadCloser, error) {
if c == nil {
c = DefaultConfig
}
// TODO(kr): maybe parallel range fetching
r, _ := http.NewRequest("GET", url, nil)
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
c.Sign(r, *c.Keys)
client := c.Client
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
return resp.Body, nil
}

View File

@ -0,0 +1,208 @@
package s3util
import (
"bytes"
"encoding/xml"
"errors"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// File represents an S3 object or directory.
type File struct {
url string
prefix string
config *Config
result *listObjectsResult
}
type fileInfo struct {
name string
size int64
dir bool
modTime time.Time
sys *Stat
}
// Stat contains information about an S3 object or directory.
// It is the "underlying data source" returned by method Sys
// for each FileInfo produced by this package.
// fi.Sys().(*s3util.Stat)
// For the meaning of these fields, see
// http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html.
type Stat struct {
Key string
LastModified string
ETag string // ETag value, without double quotes.
Size string
StorageClass string
OwnerID string `xml:"Owner>ID"`
OwnerName string `xml:"Owner>DisplayName"`
}
type listObjectsResult struct {
IsTruncated bool
Contents []Stat
Directories []string `xml:"CommonPrefixes>Prefix"` // Suffix "/" trimmed
}
func (f *fileInfo) Name() string { return f.name }
func (f *fileInfo) Size() int64 { return f.size }
func (f *fileInfo) Mode() os.FileMode {
if f.dir {
return 0755 | os.ModeDir
}
return 0644
}
func (f *fileInfo) ModTime() time.Time {
if f.modTime.IsZero() && f.sys != nil {
// we return the zero value if a parse error ever happens.
f.modTime, _ = time.Parse(time.RFC3339Nano, f.sys.LastModified)
}
return f.modTime
}
func (f *fileInfo) IsDir() bool { return f.dir }
func (f *fileInfo) Sys() interface{} { return f.sys }
// NewFile returns a new File with the given URL and config.
//
// Set rawurl to a directory on S3, such as
// https://mybucket.s3.amazonaws.com/myfolder.
// The URL cannot have query parameters or a fragment.
// If c is nil, DefaultConfig will be used.
func NewFile(rawurl string, c *Config) (*File, error) {
u, err := url.Parse(rawurl)
if err != nil {
return nil, err
}
if u.RawQuery != "" {
return nil, errors.New("url cannot have raw query parameters.")
}
if u.Fragment != "" {
return nil, errors.New("url cannot have a fragment.")
}
prefix := strings.TrimLeft(u.Path, "/")
if prefix != "" && !strings.HasSuffix(prefix, "/") {
prefix += "/"
}
u.Path = ""
return &File{u.String(), prefix, c, nil}, nil
}
// Readdir requests a list of entries in the S3 directory
// represented by f and returns a slice of up to n FileInfo
// values, in alphabetical order. Subsequent calls
// on the same File will yield further FileInfos.
// Only direct children are returned, not deeper descendants.
func (f *File) Readdir(n int) ([]os.FileInfo, error) {
if f.result != nil && !f.result.IsTruncated {
return make([]os.FileInfo, 0), io.EOF
}
reader, err := f.sendRequest(n)
if err != nil {
return nil, err
}
defer reader.Close()
return f.parseResponse(reader)
}
func (f *File) sendRequest(count int) (io.ReadCloser, error) {
c := f.config
if c == nil {
c = DefaultConfig
}
var buf bytes.Buffer
buf.WriteString(f.url)
buf.WriteString("?delimiter=%2F")
if f.prefix != "" {
buf.WriteString("&prefix=")
buf.WriteString(url.QueryEscape(f.prefix))
}
if count > 0 {
buf.WriteString("&max-keys=")
buf.WriteString(strconv.Itoa(count))
}
if f.result != nil && f.result.IsTruncated {
var lastDir, lastKey, marker string
if len(f.result.Directories) > 0 {
lastDir = f.result.Directories[len(f.result.Directories)-1]
}
if len(f.result.Contents) > 0 {
lastKey = f.result.Contents[len(f.result.Contents)-1].Key
}
if lastKey > lastDir {
marker = lastKey
} else {
marker = lastDir
}
if marker != "" {
buf.WriteString("&marker=")
buf.WriteString(url.QueryEscape(marker))
}
}
u := buf.String()
r, _ := http.NewRequest("GET", u, nil)
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
c.Sign(r, *c.Keys)
resp, err := http.DefaultClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
return resp.Body, nil
}
func (f *File) parseResponse(reader io.Reader) ([]os.FileInfo, error) {
decoder := xml.NewDecoder(reader)
result := listObjectsResult{}
var err error
err = decoder.Decode(&result)
if err != nil {
return nil, err
}
infos := make([]os.FileInfo, len(result.Contents)+len(result.Directories))
var size int64
var name string
var is_dir bool
for i, content := range result.Contents {
c := content
c.ETag = strings.Trim(c.ETag, `"`)
size, _ = strconv.ParseInt(c.Size, 10, 0)
if size == 0 && strings.HasSuffix(c.Key, "/") {
name = strings.TrimRight(c.Key, "/")
is_dir = true
} else {
name = c.Key
is_dir = false
}
infos[i] = &fileInfo{
name: name,
size: size,
dir: is_dir,
sys: &c,
}
}
for i, dir := range result.Directories {
infos[len(result.Contents)+i] = &fileInfo{
name: strings.TrimRight(dir, "/"),
size: 0,
dir: true,
}
}
f.result = &result
return infos, nil
}

View File

@ -0,0 +1,267 @@
package s3util
import (
"bytes"
"encoding/xml"
"github.com/kr/s3"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"sync"
"syscall"
"time"
)
// defined by amazon
const (
minPartSize = 5 * 1024 * 1024
maxPartSize = 1<<31 - 1 // for 32-bit use; amz max is 5GiB
maxObjSize = 5 * 1024 * 1024 * 1024 * 1024
maxNPart = 10000
)
const (
concurrency = 5
nTry = 2
)
type part struct {
r io.ReadSeeker
len int64
// read by xml encoder
PartNumber int
ETag string
}
type uploader struct {
s3 s3.Service
keys s3.Keys
url string
client *http.Client
UploadId string // written by xml decoder
bufsz int64
buf []byte
off int
ch chan *part
part int
closed bool
err error
wg sync.WaitGroup
xml struct {
XMLName string `xml:"CompleteMultipartUpload"`
Part []*part
}
}
// Create creates an S3 object at url and sends multipart upload requests as
// data is written.
//
// If h is not nil, each of its entries is added to the HTTP request header.
// If c is nil, Create uses DefaultConfig.
func Create(url string, h http.Header, c *Config) (io.WriteCloser, error) {
if c == nil {
c = DefaultConfig
}
return newUploader(url, h, c)
}
// Sends an S3 multipart upload initiation request.
// See http://docs.amazonwebservices.com/AmazonS3/latest/dev/mpuoverview.html.
// This initial request returns an UploadId that we use to identify
// subsequent PUT requests.
func newUploader(url string, h http.Header, c *Config) (u *uploader, err error) {
u = new(uploader)
u.s3 = *c.Service
u.url = url
u.keys = *c.Keys
u.client = c.Client
if u.client == nil {
u.client = http.DefaultClient
}
u.bufsz = minPartSize
r, err := http.NewRequest("POST", url+"?uploads", nil)
if err != nil {
return nil, err
}
r.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
for k := range h {
for _, v := range h[k] {
r.Header.Add(k, v)
}
}
u.s3.Sign(r, u.keys)
resp, err := u.client.Do(r)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, newRespError(resp)
}
err = xml.NewDecoder(resp.Body).Decode(u)
if err != nil {
return nil, err
}
u.ch = make(chan *part)
for i := 0; i < concurrency; i++ {
go u.worker()
}
return u, nil
}
func (u *uploader) Write(p []byte) (n int, err error) {
if u.closed {
return 0, syscall.EINVAL
}
if u.err != nil {
return 0, u.err
}
for n < len(p) {
if cap(u.buf) == 0 {
u.buf = make([]byte, int(u.bufsz))
// Increase part size (1.001x).
// This lets us reach the max object size (5TiB) while
// still doing minimal buffering for small objects.
u.bufsz = min(u.bufsz+u.bufsz/1000, maxPartSize)
}
r := copy(u.buf[u.off:], p[n:])
u.off += r
n += r
if u.off == len(u.buf) {
u.flush()
}
}
return n, nil
}
func (u *uploader) flush() {
u.wg.Add(1)
u.part++
p := &part{bytes.NewReader(u.buf[:u.off]), int64(u.off), u.part, ""}
u.xml.Part = append(u.xml.Part, p)
u.ch <- p
u.buf, u.off = nil, 0
}
func (u *uploader) worker() {
for p := range u.ch {
u.retryUploadPart(p)
}
}
// Calls putPart up to nTry times to recover from transient errors.
func (u *uploader) retryUploadPart(p *part) {
defer u.wg.Done()
defer func() { p.r = nil }() // free the large buffer
var err error
for i := 0; i < nTry; i++ {
p.r.Seek(0, 0)
err = u.putPart(p)
if err == nil {
return
}
}
u.err = err
}
// Uploads part p, reading its contents from p.r.
// Stores the ETag in p.ETag.
func (u *uploader) putPart(p *part) error {
v := url.Values{}
v.Set("partNumber", strconv.Itoa(p.PartNumber))
v.Set("uploadId", u.UploadId)
req, err := http.NewRequest("PUT", u.url+"?"+v.Encode(), p.r)
if err != nil {
return err
}
req.ContentLength = p.len
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
u.s3.Sign(req, u.keys)
resp, err := u.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return newRespError(resp)
}
s := resp.Header.Get("etag") // includes quote chars for some reason
if len(s) < 2 {
return fmt.Errorf("received invalid etag %q", s)
}
p.ETag = s[1 : len(s)-1]
return nil
}
func (u *uploader) Close() error {
if u.closed {
return syscall.EINVAL
}
if cap(u.buf) > 0 {
u.flush()
}
u.wg.Wait()
close(u.ch)
u.closed = true
if u.err != nil {
u.abort()
return u.err
}
body, err := xml.Marshal(u.xml)
if err != nil {
return err
}
b := bytes.NewBuffer(body)
v := url.Values{}
v.Set("uploadId", u.UploadId)
req, err := http.NewRequest("POST", u.url+"?"+v.Encode(), b)
if err != nil {
return err
}
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
u.s3.Sign(req, u.keys)
resp, err := u.client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return newRespError(resp)
}
resp.Body.Close()
return nil
}
func (u *uploader) abort() {
// TODO(kr): devise a reasonable way to report an error here in addition
// to the error that caused the abort.
v := url.Values{}
v.Set("uploadId", u.UploadId)
s := u.url + "?" + v.Encode()
req, err := http.NewRequest("DELETE", s, nil)
if err != nil {
return
}
req.Header.Set("Date", time.Now().UTC().Format(http.TimeFormat))
u.s3.Sign(req, u.keys)
resp, err := u.client.Do(req)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return
}
}
func min(a, b int64) int64 {
if a < b {
return a
}
return b
}

200
Godeps/_workspace/src/github.com/kr/s3/sign.go generated vendored Normal file
View File

@ -0,0 +1,200 @@
// Package s3 signs HTTP requests for Amazon S3 and compatible services.
package s3
// See
// http://docs.amazonwebservices.com/AmazonS3/2006-03-01/dev/RESTAuthentication.html.
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"io"
"net/http"
"sort"
"strings"
)
var signParams = map[string]bool{
"acl": true,
"delete": true,
"lifecycle": true,
"location": true,
"logging": true,
"notification": true,
"partNumber": true,
"policy": true,
"requestPayment": true,
"response-cache-control": true,
"response-content-disposition": true,
"response-content-encoding": true,
"response-content-language": true,
"response-content-type": true,
"response-expires": true,
"restore": true,
"torrent": true,
"uploadId": true,
"uploads": true,
"versionId": true,
"versioning": true,
"versions": true,
"website": true,
}
// Keys holds a set of Amazon Security Credentials.
type Keys struct {
AccessKey string
SecretKey string
// SecurityToken is used for temporary security credentials.
// If set, it will be added to header field X-Amz-Security-Token
// before signing a request.
SecurityToken string
// See http://docs.aws.amazon.com/AmazonS3/latest/dev/MakingRequests.html#TypesofSecurityCredentials
}
// IdentityBucket returns subdomain.
// It is designed to be used with S3-compatible services that
// treat the entire subdomain as the bucket name, for example
// storage.io.
func IdentityBucket(subdomain string) string {
return subdomain
}
// AmazonBucket returns everything up to the last '.' in subdomain.
// It is designed to be used with the Amazon service.
// "johnsmith.s3" becomes "johnsmith"
// "johnsmith.s3-eu-west-1" becomes "johnsmith"
// "www.example.com.s3" becomes "www.example.com"
func AmazonBucket(subdomain string) string {
if i := strings.LastIndex(subdomain, "."); i != -1 {
return subdomain[:i]
}
return ""
}
// DefaultService is the default Service used by Sign.
var DefaultService = &Service{Domain: "amazonaws.com"}
// Sign signs an HTTP request with the given S3 keys.
//
// This function is a wrapper around DefaultService.Sign.
func Sign(r *http.Request, k Keys) {
DefaultService.Sign(r, k)
}
// Service represents an S3-compatible service.
type Service struct {
// Domain is the service's root domain. It is used to extract
// the subdomain from an http.Request before passing the
// subdomain to Bucket.
Domain string
// Bucket derives the bucket name from a subdomain.
// If nil, AmazonBucket is used.
Bucket func(subdomain string) string
}
// Sign signs an HTTP request with the given S3 keys for use on service s.
func (s *Service) Sign(r *http.Request, k Keys) {
if k.SecurityToken != "" {
r.Header.Set("X-Amz-Security-Token", k.SecurityToken)
}
h := hmac.New(sha1.New, []byte(k.SecretKey))
s.writeSigData(h, r)
sig := make([]byte, base64.StdEncoding.EncodedLen(h.Size()))
base64.StdEncoding.Encode(sig, h.Sum(nil))
r.Header.Set("Authorization", "AWS "+k.AccessKey+":"+string(sig))
}
func (s *Service) writeSigData(w io.Writer, r *http.Request) {
w.Write([]byte(r.Method))
w.Write([]byte{'\n'})
w.Write([]byte(r.Header.Get("content-md5")))
w.Write([]byte{'\n'})
w.Write([]byte(r.Header.Get("content-type")))
w.Write([]byte{'\n'})
if _, ok := r.Header["X-Amz-Date"]; !ok {
w.Write([]byte(r.Header.Get("date")))
}
w.Write([]byte{'\n'})
writeAmzHeaders(w, r)
s.writeResource(w, r)
}
func (s *Service) writeResource(w io.Writer, r *http.Request) {
s.writeVhostBucket(w, strings.ToLower(r.Host))
path := r.URL.RequestURI()
if r.URL.RawQuery != "" {
path = path[:len(path)-len(r.URL.RawQuery)-1]
}
w.Write([]byte(path))
s.writeSubResource(w, r)
}
func (s *Service) writeVhostBucket(w io.Writer, host string) {
if i := strings.Index(host, ":"); i != -1 {
host = host[:i]
}
if host == s.Domain {
// no vhost - do nothing
} else if strings.HasSuffix(host, "."+s.Domain) {
// vhost - bucket may be in prefix
b := s.Bucket
if b == nil {
b = AmazonBucket
}
bucket := b(host[:len(host)-len(s.Domain)-1])
if bucket != "" {
w.Write([]byte{'/'})
w.Write([]byte(bucket))
}
} else {
// cname - bucket is host
w.Write([]byte{'/'})
w.Write([]byte(host))
}
}
func (s *Service) writeSubResource(w io.Writer, r *http.Request) {
var a []string
for k, vs := range r.URL.Query() {
if signParams[k] {
for _, v := range vs {
if v == "" {
a = append(a, k)
} else {
a = append(a, k+"="+v)
}
}
}
}
sort.Strings(a)
var p byte = '?'
for _, s := range a {
w.Write([]byte{p})
w.Write([]byte(s))
p = '&'
}
}
func writeAmzHeaders(w io.Writer, r *http.Request) {
var keys []string
for k, _ := range r.Header {
if strings.HasPrefix(strings.ToLower(k), "x-amz-") {
keys = append(keys, k)
}
}
sort.Strings(keys)
var a []string
for _, k := range keys {
v := r.Header[k]
a = append(a, strings.ToLower(k)+":"+strings.Join(v, ","))
}
for _, h := range a {
w.Write([]byte(h))
w.Write([]byte{'\n'})
}
}

View File

@ -0,0 +1,3 @@
.DS_Store
Thumbs.db
/.idea

View File

@ -0,0 +1,14 @@
language: go
go:
- 1.2
- 1.3
- 1.4
- 1.5
install:
- go get -t ./...
script: go test -v
sudo: false

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

@ -0,0 +1,23 @@
Copyright (c) 2016 SmartyStreets, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
NOTE: Various optional and subordinate components carry their own licensing
requirements and restrictions. Use of those components is subject to the terms
and conditions outlined the respective license of each component.

View File

@ -0,0 +1,575 @@
# assertions
--
import "github.com/smartystreets/assertions"
Package assertions contains the implementations for all assertions which are
referenced in goconvey's `convey` package
(github.com/smartystreets/goconvey/convey) and gunit
(github.com/smartystreets/gunit) for use with the So(...) method. They can also
be used in traditional Go test functions and even in applications.
Many of the assertions lean heavily on work done by Aaron Jacobs in his
excellent oglematchers library. (https://github.com/jacobsa/oglematchers) The
ShouldResemble assertion leans heavily on work done by Daniel Jacques in his
very helpful go-render library. (https://github.com/luci/go-render)
## Usage
#### func GoConveyMode
```go
func GoConveyMode(yes bool)
```
GoConveyMode provides control over JSON serialization of failures. When using
the assertions in this package from the convey package JSON results are very
helpful and can be rendered in a DIFF view. In that case, this function will be
called with a true value to enable the JSON serialization. By default, the
assertions in this package will not serializer a JSON result, making standalone
ussage more convenient.
#### func ShouldAlmostEqual
```go
func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string
```
ShouldAlmostEqual makes sure that two parameters are close enough to being
equal. The acceptable delta may be specified with a third argument, or a very
small default delta will be used.
#### func ShouldBeBetween
```go
func ShouldBeBetween(actual interface{}, expected ...interface{}) string
```
ShouldBeBetween receives exactly three parameters: an actual value, a lower
bound, and an upper bound. It ensures that the actual value is between both
bounds (but not equal to either of them).
#### func ShouldBeBetweenOrEqual
```go
func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string
```
ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a
lower bound, and an upper bound. It ensures that the actual value is between
both bounds or equal to one of them.
#### func ShouldBeBlank
```go
func ShouldBeBlank(actual interface{}, expected ...interface{}) string
```
ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal
to "".
#### func ShouldBeChronological
```go
func ShouldBeChronological(actual interface{}, expected ...interface{}) string
```
ShouldBeChronological receives a []time.Time slice and asserts that the are in
chronological order starting with the first time.Time as the earliest.
#### func ShouldBeEmpty
```go
func ShouldBeEmpty(actual interface{}, expected ...interface{}) string
```
ShouldBeEmpty receives a single parameter (actual) and determines whether or not
calling len(actual) would return `0`. It obeys the rules specified by the len
function for determining length: http://golang.org/pkg/builtin/#len
#### func ShouldBeFalse
```go
func ShouldBeFalse(actual interface{}, expected ...interface{}) string
```
ShouldBeFalse receives a single parameter and ensures that it is false.
#### func ShouldBeGreaterThan
```go
func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string
```
ShouldBeGreaterThan receives exactly two parameters and ensures that the first
is greater than the second.
#### func ShouldBeGreaterThanOrEqualTo
```go
func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string
```
ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that
the first is greater than or equal to the second.
#### func ShouldBeIn
```go
func ShouldBeIn(actual interface{}, expected ...interface{}) string
```
ShouldBeIn receives at least 2 parameters. The first is a proposed member of the
collection that is passed in either as the second parameter, or of the
collection that is comprised of all the remaining parameters. This assertion
ensures that the proposed member is in the collection (using ShouldEqual).
#### func ShouldBeLessThan
```go
func ShouldBeLessThan(actual interface{}, expected ...interface{}) string
```
ShouldBeLessThan receives exactly two parameters and ensures that the first is
less than the second.
#### func ShouldBeLessThanOrEqualTo
```go
func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string
```
ShouldBeLessThan receives exactly two parameters and ensures that the first is
less than or equal to the second.
#### func ShouldBeNil
```go
func ShouldBeNil(actual interface{}, expected ...interface{}) string
```
ShouldBeNil receives a single parameter and ensures that it is nil.
#### func ShouldBeTrue
```go
func ShouldBeTrue(actual interface{}, expected ...interface{}) string
```
ShouldBeTrue receives a single parameter and ensures that it is true.
#### func ShouldBeZeroValue
```go
func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string
```
ShouldBeZeroValue receives a single parameter and ensures that it is the Go
equivalent of the default value, or "zero" value.
#### func ShouldContain
```go
func ShouldContain(actual interface{}, expected ...interface{}) string
```
ShouldContain receives exactly two parameters. The first is a slice and the
second is a proposed member. Membership is determined using ShouldEqual.
#### func ShouldContainKey
```go
func ShouldContainKey(actual interface{}, expected ...interface{}) string
```
ShouldContainKey receives exactly two parameters. The first is a map and the
second is a proposed key. Keys are compared with a simple '=='.
#### func ShouldContainSubstring
```go
func ShouldContainSubstring(actual interface{}, expected ...interface{}) string
```
ShouldContainSubstring receives exactly 2 string parameters and ensures that the
first contains the second as a substring.
#### func ShouldEndWith
```go
func ShouldEndWith(actual interface{}, expected ...interface{}) string
```
ShouldEndWith receives exactly 2 string parameters and ensures that the first
ends with the second.
#### func ShouldEqual
```go
func ShouldEqual(actual interface{}, expected ...interface{}) string
```
ShouldEqual receives exactly two parameters and does an equality check.
#### func ShouldEqualTrimSpace
```go
func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string
```
ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the
first is equal to the second after removing all leading and trailing whitespace
using strings.TrimSpace(first).
#### func ShouldEqualWithout
```go
func ShouldEqualWithout(actual interface{}, expected ...interface{}) string
```
ShouldEqualWithout receives exactly 3 string parameters and ensures that the
first is equal to the second after removing all instances of the third from the
first using strings.Replace(first, third, "", -1).
#### func ShouldHappenAfter
```go
func ShouldHappenAfter(actual interface{}, expected ...interface{}) string
```
ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the
first happens after the second.
#### func ShouldHappenBefore
```go
func ShouldHappenBefore(actual interface{}, expected ...interface{}) string
```
ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the
first happens before the second.
#### func ShouldHappenBetween
```go
func ShouldHappenBetween(actual interface{}, expected ...interface{}) string
```
ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the
first happens between (not on) the second and third.
#### func ShouldHappenOnOrAfter
```go
func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string
```
ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that
the first happens on or after the second.
#### func ShouldHappenOnOrBefore
```go
func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string
```
ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that
the first happens on or before the second.
#### func ShouldHappenOnOrBetween
```go
func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string
```
ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that
the first happens between or on the second and third.
#### func ShouldHappenWithin
```go
func ShouldHappenWithin(actual interface{}, expected ...interface{}) string
```
ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3
arguments) and asserts that the first time.Time happens within or on the
duration specified relative to the other time.Time.
#### func ShouldHaveLength
```go
func ShouldHaveLength(actual interface{}, expected ...interface{}) string
```
ShouldHaveLength receives 2 parameters. The first is a collection to check the
length of, the second being the expected length. It obeys the rules specified by
the len function for determining length: http://golang.org/pkg/builtin/#len
#### func ShouldHaveSameTypeAs
```go
func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string
```
ShouldHaveSameTypeAs receives exactly two parameters and compares their
underlying types for equality.
#### func ShouldImplement
```go
func ShouldImplement(actual interface{}, expectedList ...interface{}) string
```
ShouldImplement receives exactly two parameters and ensures that the first
implements the interface type of the second.
#### func ShouldNotAlmostEqual
```go
func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string
```
ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual
#### func ShouldNotBeBetween
```go
func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string
```
ShouldNotBeBetween receives exactly three parameters: an actual value, a lower
bound, and an upper bound. It ensures that the actual value is NOT between both
bounds.
#### func ShouldNotBeBetweenOrEqual
```go
func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string
```
ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a
lower bound, and an upper bound. It ensures that the actual value is nopt
between the bounds nor equal to either of them.
#### func ShouldNotBeBlank
```go
func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string
```
ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is
equal to "".
#### func ShouldNotBeEmpty
```go
func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string
```
ShouldNotBeEmpty receives a single parameter (actual) and determines whether or
not calling len(actual) would return a value greater than zero. It obeys the
rules specified by the `len` function for determining length:
http://golang.org/pkg/builtin/#len
#### func ShouldNotBeIn
```go
func ShouldNotBeIn(actual interface{}, expected ...interface{}) string
```
ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of
the collection that is passed in either as the second parameter, or of the
collection that is comprised of all the remaining parameters. This assertion
ensures that the proposed member is NOT in the collection (using ShouldEqual).
#### func ShouldNotBeNil
```go
func ShouldNotBeNil(actual interface{}, expected ...interface{}) string
```
ShouldNotBeNil receives a single parameter and ensures that it is not nil.
#### func ShouldNotContain
```go
func ShouldNotContain(actual interface{}, expected ...interface{}) string
```
ShouldNotContain receives exactly two parameters. The first is a slice and the
second is a proposed member. Membership is determinied using ShouldEqual.
#### func ShouldNotContainKey
```go
func ShouldNotContainKey(actual interface{}, expected ...interface{}) string
```
ShouldNotContainKey receives exactly two parameters. The first is a map and the
second is a proposed absent key. Keys are compared with a simple '=='.
#### func ShouldNotContainSubstring
```go
func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string
```
ShouldNotContainSubstring receives exactly 2 string parameters and ensures that
the first does NOT contain the second as a substring.
#### func ShouldNotEndWith
```go
func ShouldNotEndWith(actual interface{}, expected ...interface{}) string
```
ShouldEndWith receives exactly 2 string parameters and ensures that the first
does not end with the second.
#### func ShouldNotEqual
```go
func ShouldNotEqual(actual interface{}, expected ...interface{}) string
```
ShouldNotEqual receives exactly two parameters and does an inequality check.
#### func ShouldNotHappenOnOrBetween
```go
func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string
```
ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts
that the first does NOT happen between or on the second or third.
#### func ShouldNotHappenWithin
```go
func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string
```
ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3
arguments) and asserts that the first time.Time does NOT happen within or on the
duration specified relative to the other time.Time.
#### func ShouldNotHaveSameTypeAs
```go
func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string
```
ShouldNotHaveSameTypeAs receives exactly two parameters and compares their
underlying types for inequality.
#### func ShouldNotImplement
```go
func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string
```
ShouldNotImplement receives exactly two parameters and ensures that the first
does NOT implement the interface type of the second.
#### func ShouldNotPanic
```go
func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string)
```
ShouldNotPanic receives a void, niladic function and expects to execute the
function without any panic.
#### func ShouldNotPanicWith
```go
func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string)
```
ShouldNotPanicWith receives a void, niladic function and expects to recover a
panic whose content differs from the second argument.
#### func ShouldNotPointTo
```go
func ShouldNotPointTo(actual interface{}, expected ...interface{}) string
```
ShouldNotPointTo receives exactly two parameters and checks to see that they
point to different addresess.
#### func ShouldNotResemble
```go
func ShouldNotResemble(actual interface{}, expected ...interface{}) string
```
ShouldNotResemble receives exactly two parameters and does an inverse deep equal
check (see reflect.DeepEqual)
#### func ShouldNotStartWith
```go
func ShouldNotStartWith(actual interface{}, expected ...interface{}) string
```
ShouldNotStartWith receives exactly 2 string parameters and ensures that the
first does not start with the second.
#### func ShouldPanic
```go
func ShouldPanic(actual interface{}, expected ...interface{}) (message string)
```
ShouldPanic receives a void, niladic function and expects to recover a panic.
#### func ShouldPanicWith
```go
func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string)
```
ShouldPanicWith receives a void, niladic function and expects to recover a panic
with the second argument as the content.
#### func ShouldPointTo
```go
func ShouldPointTo(actual interface{}, expected ...interface{}) string
```
ShouldPointTo receives exactly two parameters and checks to see that they point
to the same address.
#### func ShouldResemble
```go
func ShouldResemble(actual interface{}, expected ...interface{}) string
```
ShouldResemble receives exactly two parameters and does a deep equal check (see
reflect.DeepEqual)
#### func ShouldStartWith
```go
func ShouldStartWith(actual interface{}, expected ...interface{}) string
```
ShouldStartWith receives exactly 2 string parameters and ensures that the first
starts with the second.
#### func So
```go
func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string)
```
So is a convenience function (as opposed to an inconvenience function?) for
running assertions on arbitrary arguments in any context, be it for testing or
even application logging. It allows you to perform assertion-like behavior (and
get nicely formatted messages detailing discrepancies) but without the program
blowing up or panicking. All that is required is to import this package and call
`So` with one of the assertions exported by this package as the second
parameter. The first return parameter is a boolean indicating if the assertion
was true. The second return parameter is the well-formatted message showing why
an assertion was incorrect, or blank if the assertion was correct.
Example:
if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
log.Println(message)
}
#### type Assertion
```go
type Assertion struct {
}
```
#### func New
```go
func New(t testingT) *Assertion
```
New swallows the *testing.T struct and prints failed assertions using t.Error.
Example: assertions.New(t).So(1, should.Equal, 1)
#### func (*Assertion) Failed
```go
func (this *Assertion) Failed() bool
```
Failed reports whether any calls to So (on this Assertion instance) have failed.
#### func (*Assertion) So
```go
func (this *Assertion) So(actual interface{}, assert assertion, expected ...interface{}) bool
```
So calls the standalone So function and additionally, calls t.Error in failure
scenarios.
#### type FailureView
```go
type FailureView struct {
Message string `json:"Message"`
Expected string `json:"Expected"`
Actual string `json:"Actual"`
}
```
This struct is also declared in
github.com/smartystreets/goconvey/convey/reporting. The json struct tags should
be equal in both declarations.
#### type Serializer
```go
type Serializer interface {
// contains filtered or unexported methods
}
```

View File

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

View File

@ -4,7 +4,7 @@ import (
"fmt"
"reflect"
"github.com/smartystreets/goconvey/convey/assertions/oglematchers"
"github.com/smartystreets/assertions/internal/oglematchers"
)
// ShouldContain receives exactly two parameters. The first is a slice and the
@ -42,6 +42,61 @@ func ShouldNotContain(actual interface{}, expected ...interface{}) string {
return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0])
}
// ShouldContainKey receives exactly two parameters. The first is a map and the
// second is a proposed key. Keys are compared with a simple '=='.
func ShouldContainKey(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
keys, isMap := mapKeys(actual)
if !isMap {
return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual))
}
if !keyFound(keys, expected[0]) {
return fmt.Sprintf(shouldHaveContainedKey, reflect.TypeOf(actual), expected)
}
return ""
}
// ShouldNotContainKey receives exactly two parameters. The first is a map and the
// second is a proposed absent key. Keys are compared with a simple '=='.
func ShouldNotContainKey(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
keys, isMap := mapKeys(actual)
if !isMap {
return fmt.Sprintf(shouldHaveBeenAValidMap, reflect.TypeOf(actual))
}
if keyFound(keys, expected[0]) {
return fmt.Sprintf(shouldNotHaveContainedKey, reflect.TypeOf(actual), expected)
}
return ""
}
func mapKeys(m interface{}) ([]reflect.Value, bool) {
value := reflect.ValueOf(m)
if value.Kind() != reflect.Map {
return nil, false
}
return value.MapKeys(), true
}
func keyFound(keys []reflect.Value, expectedKey interface{}) bool {
found := false
for _, key := range keys {
if key.Interface() == expectedKey {
found = true
}
}
return found
}
// ShouldBeIn receives at least 2 parameters. The first is a proposed member of the collection
// that is passed in either as the second parameter, or of the collection that is comprised
// of all the remaining parameters. This assertion ensures that the proposed member is in
@ -138,3 +193,52 @@ func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string {
}
return fmt.Sprintf(shouldNotHaveBeenEmpty, actual)
}
// ShouldHaveLength receives 2 parameters. The first is a collection to check
// the length of, the second being the expected length. It obeys the rules
// specified by the len function for determining length:
// http://golang.org/pkg/builtin/#len
func ShouldHaveLength(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
var expectedLen int64
lenValue := reflect.ValueOf(expected[0])
switch lenValue.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
expectedLen = lenValue.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
expectedLen = int64(lenValue.Uint())
default:
return fmt.Sprintf(shouldHaveBeenAValidInteger, reflect.TypeOf(expected[0]))
}
if expectedLen < 0 {
return fmt.Sprintf(shouldHaveBeenAValidLength, expected[0])
}
value := reflect.ValueOf(actual)
switch value.Kind() {
case reflect.Slice,
reflect.Chan,
reflect.Map,
reflect.String:
if int64(value.Len()) == expectedLen {
return success
} else {
return fmt.Sprintf(shouldHaveHadLength, actual, value.Len(), expectedLen)
}
case reflect.Ptr:
elem := value.Elem()
kind := elem.Kind()
if kind == reflect.Slice || kind == reflect.Array {
if int64(elem.Len()) == expectedLen {
return success
} else {
return fmt.Sprintf(shouldHaveHadLength, actual, elem.Len(), expectedLen)
}
}
}
return fmt.Sprintf(shouldHaveBeenAValidCollection, reflect.TypeOf(actual))
}

View File

@ -0,0 +1,105 @@
// Package assertions contains the implementations for all assertions which
// are referenced in goconvey's `convey` package
// (github.com/smartystreets/goconvey/convey) and gunit (github.com/smartystreets/gunit)
// for use with the So(...) method.
// They can also be used in traditional Go test functions and even in
// applications.
//
// Many of the assertions lean heavily on work done by Aaron Jacobs in his excellent oglematchers library.
// (https://github.com/jacobsa/oglematchers)
// The ShouldResemble assertion leans heavily on work done by Daniel Jacques in his very helpful go-render library.
// (https://github.com/luci/go-render)
package assertions
import (
"fmt"
"runtime"
)
// By default we use a no-op serializer. The actual Serializer provides a JSON
// representation of failure results on selected assertions so the goconvey
// web UI can display a convenient diff.
var serializer Serializer = new(noopSerializer)
// GoConveyMode provides control over JSON serialization of failures. When
// using the assertions in this package from the convey package JSON results
// are very helpful and can be rendered in a DIFF view. In that case, this function
// will be called with a true value to enable the JSON serialization. By default,
// the assertions in this package will not serializer a JSON result, making
// standalone ussage more convenient.
func GoConveyMode(yes bool) {
if yes {
serializer = newSerializer()
} else {
serializer = new(noopSerializer)
}
}
type testingT interface {
Error(args ...interface{})
}
type Assertion struct {
t testingT
failed bool
}
// New swallows the *testing.T struct and prints failed assertions using t.Error.
// Example: assertions.New(t).So(1, should.Equal, 1)
func New(t testingT) *Assertion {
return &Assertion{t: t}
}
// Failed reports whether any calls to So (on this Assertion instance) have failed.
func (this *Assertion) Failed() bool {
return this.failed
}
// So calls the standalone So function and additionally, calls t.Error in failure scenarios.
func (this *Assertion) So(actual interface{}, assert assertion, expected ...interface{}) bool {
ok, result := So(actual, assert, expected...)
if !ok {
this.failed = true
_, file, line, _ := runtime.Caller(1)
this.t.Error(fmt.Sprintf("\n%s:%d\n%s", file, line, result))
}
return ok
}
// So is a convenience function (as opposed to an inconvenience function?)
// for running assertions on arbitrary arguments in any context, be it for testing or even
// application logging. It allows you to perform assertion-like behavior (and get nicely
// formatted messages detailing discrepancies) but without the program blowing up or panicking.
// All that is required is to import this package and call `So` with one of the assertions
// exported by this package as the second parameter.
// The first return parameter is a boolean indicating if the assertion was true. The second
// return parameter is the well-formatted message showing why an assertion was incorrect, or
// blank if the assertion was correct.
//
// Example:
//
// if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
// log.Println(message)
// }
//
func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) {
if result := so(actual, assert, expected...); len(result) == 0 {
return true, result
} else {
return false, result
}
}
// so is like So, except that it only returns the string message, which is blank if the
// assertion passed. Used to facilitate testing.
func so(actual interface{}, assert func(interface{}, ...interface{}) string, expected ...interface{}) string {
return assert(actual, expected...)
}
// assertion is an alias for a function with a signature that the So()
// function can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string
////////////////////////////////////////////////////////////////////////////

View File

@ -7,7 +7,8 @@ import (
"reflect"
"strings"
"github.com/smartystreets/goconvey/convey/assertions/oglematchers"
"github.com/smartystreets/assertions/internal/oglematchers"
"github.com/smartystreets/assertions/internal/go-render/render"
)
// default acceptable delta for ShouldAlmostEqual
@ -29,7 +30,14 @@ func shouldEqual(actual, expected interface{}) (message string) {
}()
if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil {
message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual))
expectedSyntax := fmt.Sprintf("%v", expected)
actualSyntax := fmt.Sprintf("%v", actual)
if expectedSyntax == actualSyntax && reflect.TypeOf(expected) != reflect.TypeOf(actual) {
message = fmt.Sprintf(shouldHaveBeenEqualTypeMismatch, expected, expected, actual, actual)
} else {
message = fmt.Sprintf(shouldHaveBeenEqual, expected, actual)
}
message = serializer.serialize(expected, actual, message)
return
}
@ -142,15 +150,8 @@ func ShouldResemble(actual interface{}, expected ...interface{}) string {
}
if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil {
expectedSyntax := fmt.Sprintf("%#v", expected[0])
actualSyntax := fmt.Sprintf("%#v", actual)
var message string
if expectedSyntax == actualSyntax {
message = fmt.Sprintf(shouldHaveResembledTypeMismatch, expected[0], actual, expected[0], actual)
} else {
message = fmt.Sprintf(shouldHaveResembled, expected[0], actual)
}
return serializer.serializeDetailed(expected[0], actual, message)
return serializer.serializeDetailed(expected[0], actual,
fmt.Sprintf(shouldHaveResembled, render.Render(expected[0]), render.Render(actual)))
}
return success
@ -161,7 +162,7 @@ func ShouldNotResemble(actual interface{}, expected ...interface{}) string {
if message := need(1, expected); message != success {
return message
} else if ShouldResemble(actual, expected[0]) == success {
return fmt.Sprintf(shouldNotHaveResembled, actual, expected[0])
return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0]))
}
return success
}

View File

@ -3,8 +3,9 @@ package assertions
import "fmt"
const (
success = ""
needExactValues = "This assertion requires exactly %d comparison values (you provided %d)."
success = ""
needExactValues = "This assertion requires exactly %d comparison values (you provided %d)."
needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)."
)
func need(needed int, expected []interface{}) string {
@ -16,7 +17,7 @@ func need(needed int, expected []interface{}) string {
func atLeast(minimum int, expected []interface{}) string {
if len(expected) < 1 {
return shouldHaveProvidedCollectionMembers
return needNonEmptyCollection
}
return success
}

View File

@ -0,0 +1,477 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package render
import (
"bytes"
"fmt"
"reflect"
"sort"
"strconv"
)
var builtinTypeMap = map[reflect.Kind]string{
reflect.Bool: "bool",
reflect.Complex128: "complex128",
reflect.Complex64: "complex64",
reflect.Float32: "float32",
reflect.Float64: "float64",
reflect.Int16: "int16",
reflect.Int32: "int32",
reflect.Int64: "int64",
reflect.Int8: "int8",
reflect.Int: "int",
reflect.String: "string",
reflect.Uint16: "uint16",
reflect.Uint32: "uint32",
reflect.Uint64: "uint64",
reflect.Uint8: "uint8",
reflect.Uint: "uint",
reflect.Uintptr: "uintptr",
}
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"
// format string, this resolves pointer types' contents in structs, maps, and
// slices/arrays and prints their field values.
func Render(v interface{}) string {
buf := bytes.Buffer{}
s := (*traverseState)(nil)
s.render(&buf, 0, reflect.ValueOf(v), false)
return buf.String()
}
// renderPointer is called to render a pointer value.
//
// This is overridable so that the test suite can have deterministic pointer
// values in its expectations.
var renderPointer = func(buf *bytes.Buffer, p uintptr) {
fmt.Fprintf(buf, "0x%016x", p)
}
// traverseState is used to note and avoid recursion as struct members are being
// traversed.
//
// traverseState is allowed to be nil. Specifically, the root state is nil.
type traverseState struct {
parent *traverseState
ptr uintptr
}
func (s *traverseState) forkFor(ptr uintptr) *traverseState {
for cur := s; cur != nil; cur = cur.parent {
if ptr == cur.ptr {
return nil
}
}
fs := &traverseState{
parent: s,
ptr: ptr,
}
return fs
}
func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) {
if v.Kind() == reflect.Invalid {
buf.WriteString("nil")
return
}
vt := v.Type()
// If the type being rendered is a potentially recursive type (a type that
// can contain itself as a member), we need to avoid recursion.
//
// If we've already seen this type before, mark that this is the case and
// write a recursion placeholder instead of actually rendering it.
//
// If we haven't seen it before, fork our `seen` tracking so any higher-up
// renderers will also render it at least once, then mark that we've seen it
// to avoid recursing on lower layers.
pe := uintptr(0)
vk := vt.Kind()
switch vk {
case reflect.Ptr:
// Since structs and arrays aren't pointers, they can't directly be
// recursed, but they can contain pointers to themselves. Record their
// pointer to avoid this.
switch v.Elem().Kind() {
case reflect.Struct, reflect.Array:
pe = v.Pointer()
}
case reflect.Slice, reflect.Map:
pe = v.Pointer()
}
if pe != 0 {
s = s.forkFor(pe)
if s == nil {
buf.WriteString("<REC(")
if !implicit {
writeType(buf, ptrs, vt)
}
buf.WriteString(")>")
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 {
case reflect.Struct:
if !implicit {
writeType(buf, ptrs, vt)
}
structAnon := vt.Name() == ""
buf.WriteRune('{')
for i := 0; i < vt.NumField(); i++ {
if i > 0 {
buf.WriteString(", ")
}
anon := structAnon && isAnon(vt.Field(i).Type)
if !anon {
buf.WriteString(vt.Field(i).Name)
buf.WriteRune(':')
}
s.render(buf, 0, v.Field(i), anon)
}
buf.WriteRune('}')
case reflect.Slice:
if v.IsNil() {
if !implicit {
writeType(buf, ptrs, vt)
buf.WriteString("(nil)")
} else {
buf.WriteString("nil")
}
return
}
fallthrough
case reflect.Array:
if !implicit {
writeType(buf, ptrs, vt)
}
anon := vt.Name() == "" && isAnon(vt.Elem())
buf.WriteString("{")
for i := 0; i < v.Len(); i++ {
if i > 0 {
buf.WriteString(", ")
}
s.render(buf, 0, v.Index(i), anon)
}
buf.WriteRune('}')
case reflect.Map:
if !implicit {
writeType(buf, ptrs, vt)
}
if v.IsNil() {
buf.WriteString("(nil)")
} else {
buf.WriteString("{")
mkeys := v.MapKeys()
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 {
if i > 0 {
buf.WriteString(", ")
}
s.render(buf, 0, mk, keyAnon)
buf.WriteString(":")
s.render(buf, 0, v.MapIndex(mk), valAnon)
}
buf.WriteRune('}')
}
case reflect.Ptr:
ptrs++
fallthrough
case reflect.Interface:
if v.IsNil() {
writeType(buf, ptrs, v.Type())
buf.WriteString("(nil)")
} else {
s.render(buf, ptrs, v.Elem(), false)
}
case reflect.Chan, reflect.Func, reflect.UnsafePointer:
writeType(buf, ptrs, vt)
buf.WriteRune('(')
renderPointer(buf, v.Pointer())
buf.WriteRune(')')
default:
tstr := vt.String()
implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr)
if !implicit {
writeType(buf, ptrs, vt)
buf.WriteRune('(')
}
switch vk {
case reflect.String:
fmt.Fprintf(buf, "%q", v.String())
case reflect.Bool:
fmt.Fprintf(buf, "%v", v.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fmt.Fprintf(buf, "%d", v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fmt.Fprintf(buf, "%d", v.Uint())
case reflect.Float32, reflect.Float64:
fmt.Fprintf(buf, "%g", v.Float())
case reflect.Complex64, reflect.Complex128:
fmt.Fprintf(buf, "%g", v.Complex())
}
if !implicit {
buf.WriteRune(')')
}
}
}
func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) {
parens := ptrs > 0
switch t.Kind() {
case reflect.Chan, reflect.Func, reflect.UnsafePointer:
parens = true
}
if parens {
buf.WriteRune('(')
for i := 0; i < ptrs; i++ {
buf.WriteRune('*')
}
}
switch t.Kind() {
case reflect.Ptr:
if ptrs == 0 {
// This pointer was referenced from within writeType (e.g., as part of
// rendering a list), and so hasn't had its pointer asterisk accounted
// for.
buf.WriteRune('*')
}
writeType(buf, 0, t.Elem())
case reflect.Interface:
if n := t.Name(); n != "" {
buf.WriteString(t.String())
} else {
buf.WriteString("interface{}")
}
case reflect.Array:
buf.WriteRune('[')
buf.WriteString(strconv.FormatInt(int64(t.Len()), 10))
buf.WriteRune(']')
writeType(buf, 0, t.Elem())
case reflect.Slice:
if t == reflect.SliceOf(t.Elem()) {
buf.WriteString("[]")
writeType(buf, 0, t.Elem())
} else {
// Custom slice type, use type name.
buf.WriteString(t.String())
}
case reflect.Map:
if t == reflect.MapOf(t.Key(), t.Elem()) {
buf.WriteString("map[")
writeType(buf, 0, t.Key())
buf.WriteRune(']')
writeType(buf, 0, t.Elem())
} else {
// Custom map type, use type name.
buf.WriteString(t.String())
}
default:
buf.WriteString(t.String())
}
if parens {
buf.WriteRune(')')
}
}
type cmpFn func(a, b reflect.Value) int
type sortableValueSlice struct {
cmp cmpFn
elements []reflect.Value
}
func (s sortableValueSlice) Len() int {
return len(s.elements)
}
func (s sortableValueSlice) Less(i, j int) bool {
return s.cmp(s.elements[i], s.elements[j]) < 0
}
func (s sortableValueSlice) Swap(i, j int) {
s.elements[i], s.elements[j] = s.elements[j], s.elements[i]
}
// cmpForType returns a cmpFn which sorts the data for some type t in the same
// order that a go-native map key is compared for equality.
func cmpForType(t reflect.Type) cmpFn {
switch t.Kind() {
case reflect.String:
return func(av, bv reflect.Value) int {
a, b := av.String(), bv.String()
if a < b {
return -1
} else if a > b {
return 1
}
return 0
}
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,4 @@
# Cf. http://docs.travis-ci.com/user/getting-started/
# Cf. http://docs.travis-ci.com/user/languages/go/
language: go

View File

@ -1,3 +1,5 @@
[![GoDoc](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers?status.svg)](https://godoc.org/github.com/smartystreets/assertions/internal/oglematchers)
`oglematchers` is a package for the Go programming language containing a set of
matchers, useful in a testing or mocking framework, inspired by and mostly
compatible with [Google Test][googletest] for C++ and
@ -36,21 +38,21 @@ First, make sure you have installed Go 1.0.2 or newer. See
Use the following command to install `oglematchers` and keep it up to date:
go get -u github.com/smartystreets/goconvey/convey/assertions/oglematchers
go get -u github.com/smartystreets/assertions/internal/oglematchers
Documentation
-------------
See [here][reference] for documentation hosted on GoPkgDoc. Alternatively, you
can install the package and then use `go doc`:
See [here][reference] for documentation. Alternatively, you can install the
package and then use `godoc`:
go doc github.com/smartystreets/goconvey/convey/assertions/oglematchers
godoc github.com/smartystreets/assertions/internal/oglematchers
[reference]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/goconvey/convey/assertions/oglematchers
[reference]: http://godoc.org/github.com/smartystreets/assertions/internal/oglematchers
[golang-install]: http://golang.org/doc/install.html
[googletest]: http://code.google.com/p/googletest/
[google-js-test]: http://code.google.com/p/google-js-test/
[ogletest]: http://github.com/smartystreets/goconvey/convey/assertions/ogletest
[oglemock]: http://github.com/smartystreets/goconvey/convey/assertions/oglemock
[ogletest]: http://github.com/smartystreets/assertions/internal/ogletest
[oglemock]: http://github.com/smartystreets/assertions/internal/oglemock

View File

@ -47,7 +47,8 @@ func AnyOf(vals ...interface{}) Matcher {
// matcher.
wrapped := make([]Matcher, len(vals))
for i, v := range vals {
if reflect.TypeOf(v).Implements(matcherType) {
t := reflect.TypeOf(v)
if t != nil && t.Implements(matcherType) {
wrapped[i] = v.(Matcher)
} else {
wrapped[i] = Equals(v)

View File

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

View File

@ -24,8 +24,9 @@ import (
// Equals(x) returns a matcher that matches values v such that v and x are
// equivalent. This includes the case when the comparison v == x using Go's
// built-in comparison operator is legal, but for convenience the following
// rules also apply:
// built-in comparison operator is legal (except for structs, which this
// matcher does not support), but for convenience the following rules also
// apply:
//
// * Type checking is done based on underlying types rather than actual
// types, so that e.g. two aliases for string can be compared:
@ -49,11 +50,16 @@ import (
//
// If you want a stricter matcher that contains no such cleverness, see
// IdenticalTo instead.
//
// Arrays are supported by this matcher, but do not participate in the
// exceptions above. Two arrays compared with this matcher must have identical
// types, and their element type must itself be comparable according to Go's ==
// operator.
func Equals(x interface{}) Matcher {
v := reflect.ValueOf(x)
// The == operator is not defined for array or struct types.
if v.Kind() == reflect.Array || v.Kind() == reflect.Struct {
// This matcher doesn't support structs.
if v.Kind() == reflect.Struct {
panic(fmt.Sprintf("oglematchers.Equals: unsupported kind %v", v.Kind()))
}
@ -80,7 +86,7 @@ func isSignedInteger(v reflect.Value) bool {
func isUnsignedInteger(v reflect.Value) bool {
k := v.Kind()
return k >= reflect.Uint && k <= reflect.Uint64
return k >= reflect.Uint && k <= reflect.Uintptr
}
func isInteger(v reflect.Value) bool {
@ -307,19 +313,6 @@ func checkAgainstBool(e bool, c reflect.Value) (err error) {
return
}
func checkAgainstUintptr(e uintptr, c reflect.Value) (err error) {
if c.Kind() != reflect.Uintptr {
err = NewFatalError("which is not a uintptr")
return
}
err = errors.New("")
if uintptr(c.Uint()) == e {
err = nil
}
return
}
func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) {
// Create a description of e's type, e.g. "chan int".
typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem())
@ -417,6 +410,25 @@ func checkAgainstString(e reflect.Value, c reflect.Value) (err error) {
return
}
func checkAgainstArray(e reflect.Value, c reflect.Value) (err error) {
// Create a description of e's type, e.g. "[2]int".
typeStr := fmt.Sprintf("%v", e.Type())
// Make sure c is the correct type.
if c.Type() != e.Type() {
err = NewFatalError(fmt.Sprintf("which is not %s", typeStr))
return
}
// Check for equality.
if e.Interface() != c.Interface() {
err = errors.New("")
return
}
return
}
func checkAgainstUnsafePointer(e reflect.Value, c reflect.Value) (err error) {
// Make sure c is a pointer.
if c.Kind() != reflect.UnsafePointer {
@ -476,9 +488,6 @@ func (m *equalsMatcher) Matches(candidate interface{}) error {
case isUnsignedInteger(e):
return checkAgainstUint64(e.Uint(), c)
case ek == reflect.Uintptr:
return checkAgainstUintptr(uintptr(e.Uint()), c)
case ek == reflect.Float32:
return checkAgainstFloat32(float32(e.Float()), c)
@ -509,6 +518,9 @@ func (m *equalsMatcher) Matches(candidate interface{}) error {
case ek == reflect.String:
return checkAgainstString(e, c)
case ek == reflect.Array:
return checkAgainstArray(e, c)
case ek == reflect.UnsafePointer:
return checkAgainstUnsafePointer(e, c)

View File

@ -1,4 +1,4 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Copyright 2015 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
@ -13,12 +13,25 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// A package that calls itself something different than its package path would
// have you believe.
package tony
package oglematchers
type SomeUint8Alias uint8
import (
"fmt"
"reflect"
)
type SomeInterface interface {
DoFoo(a int) int
// 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

@ -25,18 +25,12 @@ import (
// HasSubstr returns a matcher that matches strings containing s as a
// substring.
func HasSubstr(s string) Matcher {
return &hasSubstrMatcher{s}
return NewMatcher(
func(c interface{}) error { return hasSubstr(s, c) },
fmt.Sprintf("has substring \"%s\"", s))
}
type hasSubstrMatcher struct {
needle string
}
func (m *hasSubstrMatcher) Description() string {
return fmt.Sprintf("has substring \"%s\"", m.needle)
}
func (m *hasSubstrMatcher) Matches(c interface{}) error {
func hasSubstr(needle string, c interface{}) error {
v := reflect.ValueOf(c)
if v.Kind() != reflect.String {
return NewFatalError("which is not a string")
@ -44,7 +38,7 @@ func (m *hasSubstrMatcher) Matches(c interface{}) error {
// Perform the substring search.
haystack := v.String()
if strings.Contains(haystack, m.needle) {
if strings.Contains(haystack, needle) {
return nil
}

View File

@ -17,8 +17,8 @@
// mocking framework. These matchers are inspired by and mostly compatible with
// Google Test for C++ and Google JS Test.
//
// This package is used by github.com/smartystreets/goconvey/convey/assertions/ogletest and
// github.com/smartystreets/goconvey/convey/assertions/oglemock, which may be more directly useful if you're not
// This package is used by github.com/smartystreets/assertions/internal/ogletest and
// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not
// writing your own testing package or defining your own matchers.
package oglematchers
@ -26,6 +26,10 @@ package oglematchers
// matches. For example, GreaterThan(17) matches all numeric values greater
// than 17, and HasSubstr("taco") matches all strings with the substring
// "taco".
//
// Matchers are typically exposed to tests via constructor functions like
// HasSubstr. In order to implement such a function you can either define your
// own matcher type or use NewMatcher.
type Matcher interface {
// Check whether the supplied value belongs to the the set defined by the
// matcher. Return a non-nil error if and only if it does not.

View File

@ -23,7 +23,7 @@ import (
)
// MatchesRegexp returns a matcher that matches strings and byte slices whose
// contents match the supplide regular expression. The semantics are those of
// 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 {

View File

@ -0,0 +1,43 @@
// 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

@ -3,10 +3,10 @@ package assertions
const ( // equality
shouldHaveBeenEqual = "Expected: '%v'\nActual: '%v'\n(Should be equal)"
shouldNotHaveBeenEqual = "Expected '%v'\nto NOT equal '%v'\n(but it did)!"
shouldHaveBeenEqualTypeMismatch = "Expected: '%v' (%T)\nActual: '%v' (%T)\n(Should be equal, type mismatch)"
shouldHaveBeenAlmostEqual = "Expected '%v' to almost equal '%v' (but it didn't)!"
shouldHaveNotBeenAlmostEqual = "Expected '%v' to NOT almost equal '%v' (but it did)!"
shouldHaveResembled = "Expected: '%#v'\nActual: '%#v'\n(Should resemble)!"
shouldHaveResembledTypeMismatch = "Expected: '%#v'\nActual: '%#v'\n(Type mismatch: '%T' vs '%T')!"
shouldHaveResembled = "Expected: '%s'\nActual: '%s'\n(Should resemble)!"
shouldNotHaveResembled = "Expected '%#v'\nto NOT resemble '%#v'\n(but it did)!"
shouldBePointers = "Both arguments should be pointers "
shouldHaveBeenNonNilPointer = shouldBePointers + "(the %s was %s)!"
@ -32,14 +32,19 @@ const ( // quantity comparisons
)
const ( // collections
shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!"
shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!"
shouldHaveBeenIn = "Expected '%v' to be in the container (%v, but it wasn't)!"
shouldNotHaveBeenIn = "Expected '%v' NOT to be in the container (%v, but it was)!"
shouldHaveBeenAValidCollection = "You must provide a valid container (was %v)!"
shouldHaveProvidedCollectionMembers = "This assertion requires at least 1 comparison value (you provided 0)."
shouldHaveBeenEmpty = "Expected %+v to be empty (but it wasn't)!"
shouldNotHaveBeenEmpty = "Expected %+v to NOT be empty (but it was)!"
shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!"
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)!"
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
@ -47,10 +52,11 @@ const ( // strings
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)."
shouldBeString = "The argument to this assertion must be a string (you provided %v)."
shouldHaveContainedSubstring = "Expected '%s' to contain substring '%s' (but it didn't)!"
shouldNotHaveContainedSubstring = "Expected '%s' NOT to contain substring '%s' (but it didn't)!"
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)!"
)

View File

@ -3,7 +3,7 @@ package assertions
import (
"fmt"
"github.com/smartystreets/goconvey/convey/assertions/oglematchers"
"github.com/smartystreets/assertions/internal/oglematchers"
)
// ShouldBeGreaterThan receives exactly two parameters and ensures that the first is greater than the second.
@ -43,7 +43,7 @@ func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) stri
if fail := need(1, expected); fail != success {
return fail
} else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil {
return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0])
return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0])
}
return success
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"
"github.com/smartystreets/goconvey/convey/reporting"
"github.com/smartystreets/assertions/internal/go-render/render"
)
type Serializer interface {
@ -15,7 +15,11 @@ type Serializer interface {
type failureSerializer struct{}
func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string {
view := self.format(expected, actual, message, "%#v")
view := FailureView{
Message: message,
Expected: render.Render(expected),
Actual: render.Render(actual),
}
serialized, err := json.Marshal(view)
if err != nil {
return message
@ -24,7 +28,11 @@ func (self *failureSerializer) serializeDetailed(expected, actual interface{}, m
}
func (self *failureSerializer) serialize(expected, actual interface{}, message string) string {
view := self.format(expected, actual, message, "%+v")
view := FailureView{
Message: message,
Expected: fmt.Sprintf("%+v", expected),
Actual: fmt.Sprintf("%+v", actual),
}
serialized, err := json.Marshal(view)
if err != nil {
return message
@ -32,18 +40,20 @@ func (self *failureSerializer) serialize(expected, actual interface{}, message s
return string(serialized)
}
func (self *failureSerializer) format(expected, actual interface{}, message string, format string) reporting.FailureView {
return reporting.FailureView{
Message: message,
Expected: fmt.Sprintf(format, expected),
Actual: fmt.Sprintf(format, actual),
}
}
func newSerializer() *failureSerializer {
return &failureSerializer{}
}
///////////////////////////////////////////////////////////////////////////////
// This struct is also declared in github.com/smartystreets/goconvey/convey/reporting.
// The json struct tags should be equal in both declarations.
type FailureView struct {
Message string `json:"Message"`
Expected string `json:"Expected"`
Actual string `json:"Actual"`
}
///////////////////////////////////////////////////////
// noopSerializer just gives back the original message. This is useful when we are using

View File

@ -181,3 +181,47 @@ func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string {
}
return success
}
// ShouldEqualWithout receives exactly 3 string parameters and ensures that the first is equal to the second
// after removing all instances of the third from the first using strings.Replace(first, third, "", -1).
func ShouldEqualWithout(actual interface{}, expected ...interface{}) string {
if fail := need(2, expected); fail != success {
return fail
}
actualString, ok1 := actual.(string)
expectedString, ok2 := expected[0].(string)
replace, ok3 := expected[1].(string)
if !ok1 || !ok2 || !ok3 {
return fmt.Sprintf(shouldAllBeStrings, []reflect.Type{
reflect.TypeOf(actual),
reflect.TypeOf(expected[0]),
reflect.TypeOf(expected[1]),
})
}
replaced := strings.Replace(actualString, replace, "", -1)
if replaced == expectedString {
return ""
}
return fmt.Sprintf("Expected '%s' to equal '%s' but without any '%s' (but it didn't).", actualString, expectedString, replace)
}
// ShouldEqualTrimSpace receives exactly 2 string parameters and ensures that the first is equal to the second
// after removing all leading and trailing whitespace using strings.TrimSpace(first).
func ShouldEqualTrimSpace(actual interface{}, expected ...interface{}) string {
if fail := need(1, expected); fail != success {
return fail
}
actualString, valueIsString := actual.(string)
_, value2IsString := expected[0].(string)
if !valueIsString || !value2IsString {
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
}
actualString = strings.TrimSpace(actualString)
return ShouldEqual(actualString, expected[0])
}

View File

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

View File

@ -1,103 +0,0 @@
package assertions
import (
"fmt"
"testing"
"time"
)
func TestShouldContain(t *testing.T) {
fail(t, so([]int{}, ShouldContain), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so([]int{}, ShouldContain, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")
fail(t, so(Thing1{}, ShouldContain, 1), "You must provide a valid container (was assertions.Thing1)!")
fail(t, so(nil, ShouldContain, 1), "You must provide a valid container (was <nil>)!")
fail(t, so([]int{1}, ShouldContain, 2), "Expected the container ([]int) to contain: '2' (but it didn't)!")
pass(t, so([]int{1}, ShouldContain, 1))
pass(t, so([]int{1, 2, 3}, ShouldContain, 2))
}
func TestShouldNotContain(t *testing.T) {
fail(t, so([]int{}, ShouldNotContain), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so([]int{}, ShouldNotContain, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")
fail(t, so(Thing1{}, ShouldNotContain, 1), "You must provide a valid container (was assertions.Thing1)!")
fail(t, so(nil, ShouldNotContain, 1), "You must provide a valid container (was <nil>)!")
fail(t, so([]int{1}, ShouldNotContain, 1), "Expected the container ([]int) NOT to contain: '1' (but it did)!")
fail(t, so([]int{1, 2, 3}, ShouldNotContain, 2), "Expected the container ([]int) NOT to contain: '2' (but it did)!")
pass(t, so([]int{1}, ShouldNotContain, 2))
}
func TestShouldBeIn(t *testing.T) {
fail(t, so(4, ShouldBeIn), shouldHaveProvidedCollectionMembers)
container := []int{1, 2, 3, 4}
pass(t, so(4, ShouldBeIn, container))
pass(t, so(4, ShouldBeIn, 1, 2, 3, 4))
fail(t, so(4, ShouldBeIn, 1, 2, 3), "Expected '4' to be in the container ([]interface {}, but it wasn't)!")
fail(t, so(4, ShouldBeIn, []int{1, 2, 3}), "Expected '4' to be in the container ([]int, but it wasn't)!")
}
func TestShouldNotBeIn(t *testing.T) {
fail(t, so(4, ShouldNotBeIn), shouldHaveProvidedCollectionMembers)
container := []int{1, 2, 3, 4}
pass(t, so(42, ShouldNotBeIn, container))
pass(t, so(42, ShouldNotBeIn, 1, 2, 3, 4))
fail(t, so(2, ShouldNotBeIn, 1, 2, 3), "Expected '2' NOT to be in the container ([]interface {}, but it was)!")
fail(t, so(2, ShouldNotBeIn, []int{1, 2, 3}), "Expected '2' NOT to be in the container ([]int, but it was)!")
}
func TestShouldBeEmpty(t *testing.T) {
fail(t, so(1, ShouldBeEmpty, 2, 3), "This assertion requires exactly 0 comparison values (you provided 2).")
pass(t, so([]int{}, ShouldBeEmpty)) // empty slice
pass(t, so([]interface{}{}, ShouldBeEmpty)) // empty slice
pass(t, so(map[string]int{}, ShouldBeEmpty)) // empty map
pass(t, so("", ShouldBeEmpty)) // empty string
pass(t, so(&[]int{}, ShouldBeEmpty)) // pointer to empty slice
pass(t, so(&[0]int{}, ShouldBeEmpty)) // pointer to empty array
pass(t, so(nil, ShouldBeEmpty)) // nil
pass(t, so(make(chan string), ShouldBeEmpty)) // empty channel
fail(t, so([]int{1}, ShouldBeEmpty), "Expected [1] to be empty (but it wasn't)!") // non-empty slice
fail(t, so([]interface{}{1}, ShouldBeEmpty), "Expected [1] to be empty (but it wasn't)!") // non-empty slice
fail(t, so(map[string]int{"hi": 0}, ShouldBeEmpty), "Expected map[hi:0] to be empty (but it wasn't)!") // non-empty map
fail(t, so("hi", ShouldBeEmpty), "Expected hi to be empty (but it wasn't)!") // non-empty string
fail(t, so(&[]int{1}, ShouldBeEmpty), "Expected &[1] to be empty (but it wasn't)!") // pointer to non-empty slice
fail(t, so(&[1]int{1}, ShouldBeEmpty), "Expected &[1] to be empty (but it wasn't)!") // pointer to non-empty array
c := make(chan int, 1) // non-empty channel
go func() { c <- 1 }()
time.Sleep(time.Millisecond)
fail(t, so(c, ShouldBeEmpty), fmt.Sprintf("Expected %+v to be empty (but it wasn't)!", c))
}
func TestShouldNotBeEmpty(t *testing.T) {
fail(t, so(1, ShouldNotBeEmpty, 2, 3), "This assertion requires exactly 0 comparison values (you provided 2).")
fail(t, so([]int{}, ShouldNotBeEmpty), "Expected [] to NOT be empty (but it was)!") // empty slice
fail(t, so([]interface{}{}, ShouldNotBeEmpty), "Expected [] to NOT be empty (but it was)!") // empty slice
fail(t, so(map[string]int{}, ShouldNotBeEmpty), "Expected map[] to NOT be empty (but it was)!") // empty map
fail(t, so("", ShouldNotBeEmpty), "Expected to NOT be empty (but it was)!") // empty string
fail(t, so(&[]int{}, ShouldNotBeEmpty), "Expected &[] to NOT be empty (but it was)!") // pointer to empty slice
fail(t, so(&[0]int{}, ShouldNotBeEmpty), "Expected &[] to NOT be empty (but it was)!") // pointer to empty array
fail(t, so(nil, ShouldNotBeEmpty), "Expected <nil> to NOT be empty (but it was)!") // nil
c := make(chan int, 0) // non-empty channel
fail(t, so(c, ShouldNotBeEmpty), fmt.Sprintf("Expected %+v to NOT be empty (but it was)!", c)) // empty channel
pass(t, so([]int{1}, ShouldNotBeEmpty)) // non-empty slice
pass(t, so([]interface{}{1}, ShouldNotBeEmpty)) // non-empty slice
pass(t, so(map[string]int{"hi": 0}, ShouldNotBeEmpty)) // non-empty map
pass(t, so("hi", ShouldNotBeEmpty)) // non-empty string
pass(t, so(&[]int{1}, ShouldNotBeEmpty)) // pointer to non-empty slice
pass(t, so(&[1]int{1}, ShouldNotBeEmpty)) // pointer to non-empty array
c = make(chan int, 1)
go func() { c <- 1 }()
time.Sleep(time.Millisecond)
pass(t, so(c, ShouldNotBeEmpty))
}

View File

@ -1,43 +0,0 @@
// Package assertions contains the implementations for all assertions which
// are referenced in the convey package for use with the So(...) method.
package assertions
// This function is not used by the goconvey library. It's actually a convenience method
// for running assertions on arbitrary arguments outside of any testing context, like for
// application logging. It allows you to perform assertion-like behavior (and get nicely
// formatted messages detailing discrepancies) but without the probram blowing up or panicking.
// All that is required is to import this package and call `So` with one of the assertions
// exported by this package as the second parameter.
// The first return parameter is a boolean indicating if the assertion was true. The second
// return parameter is the well-formatted message showing why an assertion was incorrect, or
// blank if the assertion was correct.
//
// Example:
//
// if ok, message := So(x, ShouldBeGreaterThan, y); !ok {
// log.Println(message)
// }
//
func So(actual interface{}, assert assertion, expected ...interface{}) (bool, string) {
serializer = noop
if result := so(actual, assert, expected...); len(result) == 0 {
return true, result
} else {
return false, result
}
}
// so is like So, except that it only returns the string message, which is blank if the
// assertion passed. Used to facilitate testing.
func so(actual interface{}, assert func(interface{}, ...interface{}) string, expected ...interface{}) string {
return assert(actual, expected...)
}
// assertion is an alias for a function with a signature that the So()
// function can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string
////////////////////////////////////////////////////////////////////////////

View File

@ -1,267 +0,0 @@
package assertions
import (
"fmt"
"reflect"
"testing"
)
func TestShouldEqual(t *testing.T) {
serializer = newFakeSerializer()
fail(t, so(1, ShouldEqual), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(1, ShouldEqual, 1, 2), "This assertion requires exactly 1 comparison values (you provided 2).")
fail(t, so(1, ShouldEqual, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")
pass(t, so(1, ShouldEqual, 1))
fail(t, so(1, ShouldEqual, 2), "2|1|Expected: '2' Actual: '1' (Should be equal)")
pass(t, so(true, ShouldEqual, true))
fail(t, so(true, ShouldEqual, false), "false|true|Expected: 'false' Actual: 'true' (Should be equal)")
pass(t, so("hi", ShouldEqual, "hi"))
fail(t, so("hi", ShouldEqual, "bye"), "bye|hi|Expected: 'bye' Actual: 'hi' (Should be equal)")
pass(t, so(42, ShouldEqual, uint(42)))
fail(t, so(Thing1{"hi"}, ShouldEqual, Thing1{}), "{}|{hi}|Expected: '{}' Actual: '{hi}' (Should be equal)")
fail(t, so(Thing1{"hi"}, ShouldEqual, Thing1{"hi"}), "{hi}|{hi}|Expected: '{hi}' Actual: '{hi}' (Should be equal)")
fail(t, so(&Thing1{"hi"}, ShouldEqual, &Thing1{"hi"}), "&{hi}|&{hi}|Expected: '&{hi}' Actual: '&{hi}' (Should be equal)")
fail(t, so(Thing1{}, ShouldEqual, Thing2{}), "{}|{}|Expected: '{}' Actual: '{}' (Should be equal)")
}
func TestShouldNotEqual(t *testing.T) {
fail(t, so(1, ShouldNotEqual), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(1, ShouldNotEqual, 1, 2), "This assertion requires exactly 1 comparison values (you provided 2).")
fail(t, so(1, ShouldNotEqual, 1, 2, 3), "This assertion requires exactly 1 comparison values (you provided 3).")
pass(t, so(1, ShouldNotEqual, 2))
fail(t, so(1, ShouldNotEqual, 1), "Expected '1' to NOT equal '1' (but it did)!")
pass(t, so(true, ShouldNotEqual, false))
fail(t, so(true, ShouldNotEqual, true), "Expected 'true' to NOT equal 'true' (but it did)!")
pass(t, so("hi", ShouldNotEqual, "bye"))
fail(t, so("hi", ShouldNotEqual, "hi"), "Expected 'hi' to NOT equal 'hi' (but it did)!")
pass(t, so(&Thing1{"hi"}, ShouldNotEqual, &Thing1{"hi"}))
pass(t, so(Thing1{"hi"}, ShouldNotEqual, Thing1{"hi"}))
pass(t, so(Thing1{}, ShouldNotEqual, Thing1{}))
pass(t, so(Thing1{}, ShouldNotEqual, Thing2{}))
}
func TestShouldAlmostEqual(t *testing.T) {
fail(t, so(1, ShouldAlmostEqual), "This assertion requires exactly one comparison value and an optional delta (you provided neither)")
fail(t, so(1, ShouldAlmostEqual, 1, 2, 3), "This assertion requires exactly one comparison value and an optional delta (you provided more values)")
// with the default delta
pass(t, so(1, ShouldAlmostEqual, .99999999999999))
pass(t, so(1.3612499999999996, ShouldAlmostEqual, 1.36125))
pass(t, so(0.7285312499999999, ShouldAlmostEqual, 0.72853125))
fail(t, so(1, ShouldAlmostEqual, .99), "Expected '1' to almost equal '0.99' (but it didn't)!")
// with a different delta
pass(t, so(100.0, ShouldAlmostEqual, 110.0, 10.0))
fail(t, so(100.0, ShouldAlmostEqual, 111.0, 10.5), "Expected '100' to almost equal '111' (but it didn't)!")
// ints should work
pass(t, so(100, ShouldAlmostEqual, 100.0))
fail(t, so(100, ShouldAlmostEqual, 99.0), "Expected '100' to almost equal '99' (but it didn't)!")
// float32 should work
pass(t, so(float64(100.0), ShouldAlmostEqual, float32(100.0)))
fail(t, so(float32(100.0), ShouldAlmostEqual, 99.0, float32(0.1)), "Expected '100' to almost equal '99' (but it didn't)!")
}
func TestShouldNotAlmostEqual(t *testing.T) {
fail(t, so(1, ShouldNotAlmostEqual), "This assertion requires exactly one comparison value and an optional delta (you provided neither)")
fail(t, so(1, ShouldNotAlmostEqual, 1, 2, 3), "This assertion requires exactly one comparison value and an optional delta (you provided more values)")
// with the default delta
fail(t, so(1, ShouldNotAlmostEqual, .99999999999999), "Expected '1' to NOT almost equal '0.99999999999999' (but it did)!")
fail(t, so(1.3612499999999996, ShouldNotAlmostEqual, 1.36125), "Expected '1.3612499999999996' to NOT almost equal '1.36125' (but it did)!")
pass(t, so(1, ShouldNotAlmostEqual, .99))
// with a different delta
fail(t, so(100.0, ShouldNotAlmostEqual, 110.0, 10.0), "Expected '100' to NOT almost equal '110' (but it did)!")
pass(t, so(100.0, ShouldNotAlmostEqual, 111.0, 10.5))
// ints should work
fail(t, so(100, ShouldNotAlmostEqual, 100.0), "Expected '100' to NOT almost equal '100' (but it did)!")
pass(t, so(100, ShouldNotAlmostEqual, 99.0))
// float32 should work
fail(t, so(float64(100.0), ShouldNotAlmostEqual, float32(100.0)), "Expected '100' to NOT almost equal '100' (but it did)!")
pass(t, so(float32(100.0), ShouldNotAlmostEqual, 99.0, float32(0.1)))
}
func TestShouldResemble(t *testing.T) {
serializer = newFakeSerializer()
fail(t, so(Thing1{"hi"}, ShouldResemble), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"hi"}, Thing1{"hi"}), "This assertion requires exactly 1 comparison values (you provided 2).")
pass(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"hi"}))
fail(t, so(Thing1{"hi"}, ShouldResemble, Thing1{"bye"}), "{bye}|{hi}|Expected: 'assertions.Thing1{a:\"bye\"}' Actual: 'assertions.Thing1{a:\"hi\"}' (Should resemble)!")
var (
a []int
b []int = []int{}
)
fail(t, so(a, ShouldResemble, b), "[]|[]|Expected: '[]int{}' Actual: '[]int(nil)' (Should resemble)!")
fail(t, so(2, ShouldResemble, 1), "1|2|Expected: '1' Actual: '2' (Should resemble)!")
fail(t, so(StringStringMapAlias{"hi": "bye"}, ShouldResemble, map[string]string{"hi": "bye"}),
"map[hi:bye]|map[hi:bye]|Expected: 'map[string]string{\"hi\":\"bye\"}' Actual: 'assertions.StringStringMapAlias{\"hi\":\"bye\"}' (Should resemble)!")
fail(t, so(StringSliceAlias{"hi", "bye"}, ShouldResemble, []string{"hi", "bye"}),
"[hi bye]|[hi bye]|Expected: '[]string{\"hi\", \"bye\"}' Actual: 'assertions.StringSliceAlias{\"hi\", \"bye\"}' (Should resemble)!")
// some types come out looking the same when represented with "%#v" so we show type mismatch info:
fail(t, so(StringAlias("hi"), ShouldResemble, "hi"), "hi|hi|Expected: '\"hi\"' Actual: '\"hi\"' (Type mismatch: 'string' vs 'assertions.StringAlias')!")
fail(t, so(IntAlias(42), ShouldResemble, 42), "42|42|Expected: '42' Actual: '42' (Type mismatch: 'int' vs 'assertions.IntAlias')!")
}
func TestShouldNotResemble(t *testing.T) {
fail(t, so(Thing1{"hi"}, ShouldNotResemble), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"hi"}, Thing1{"hi"}), "This assertion requires exactly 1 comparison values (you provided 2).")
pass(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"bye"}))
fail(t, so(Thing1{"hi"}, ShouldNotResemble, Thing1{"hi"}),
"Expected 'assertions.Thing1{a:\"hi\"}' to NOT resemble 'assertions.Thing1{a:\"hi\"}' (but it did)!")
pass(t, so(map[string]string{"hi": "bye"}, ShouldResemble, map[string]string{"hi": "bye"}))
pass(t, so(IntAlias(42), ShouldNotResemble, 42))
pass(t, so(StringSliceAlias{"hi", "bye"}, ShouldNotResemble, []string{"hi", "bye"}))
}
func TestShouldPointTo(t *testing.T) {
serializer = newFakeSerializer()
t1 := &Thing1{}
t2 := t1
t3 := &Thing1{}
pointer1 := reflect.ValueOf(t1).Pointer()
pointer3 := reflect.ValueOf(t3).Pointer()
fail(t, so(t1, ShouldPointTo), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(t1, ShouldPointTo, t2, t3), "This assertion requires exactly 1 comparison values (you provided 2).")
pass(t, so(t1, ShouldPointTo, t2))
fail(t, so(t1, ShouldPointTo, t3), fmt.Sprintf(
"%v|%v|Expected '&{a:}' (address: '%v') and '&{a:}' (address: '%v') to be the same address (but their weren't)!",
pointer3, pointer1, pointer1, pointer3))
t4 := Thing1{}
t5 := t4
fail(t, so(t4, ShouldPointTo, t5), "Both arguments should be pointers (the first was not)!")
fail(t, so(&t4, ShouldPointTo, t5), "Both arguments should be pointers (the second was not)!")
fail(t, so(nil, ShouldPointTo, nil), "Both arguments should be pointers (the first was nil)!")
fail(t, so(&t4, ShouldPointTo, nil), "Both arguments should be pointers (the second was nil)!")
}
func TestShouldNotPointTo(t *testing.T) {
t1 := &Thing1{}
t2 := t1
t3 := &Thing1{}
pointer1 := reflect.ValueOf(t1).Pointer()
fail(t, so(t1, ShouldNotPointTo), "This assertion requires exactly 1 comparison values (you provided 0).")
fail(t, so(t1, ShouldNotPointTo, t2, t3), "This assertion requires exactly 1 comparison values (you provided 2).")
pass(t, so(t1, ShouldNotPointTo, t3))
fail(t, so(t1, ShouldNotPointTo, t2), fmt.Sprintf("Expected '&{a:}' and '&{a:}' to be different references (but they matched: '%v')!", pointer1))
t4 := Thing1{}
t5 := t4
fail(t, so(t4, ShouldNotPointTo, t5), "Both arguments should be pointers (the first was not)!")
fail(t, so(&t4, ShouldNotPointTo, t5), "Both arguments should be pointers (the second was not)!")
fail(t, so(nil, ShouldNotPointTo, nil), "Both arguments should be pointers (the first was nil)!")
fail(t, so(&t4, ShouldNotPointTo, nil), "Both arguments should be pointers (the second was nil)!")
}
func TestShouldBeNil(t *testing.T) {
fail(t, so(nil, ShouldBeNil, nil, nil, nil), "This assertion requires exactly 0 comparison values (you provided 3).")
fail(t, so(nil, ShouldBeNil, nil), "This assertion requires exactly 0 comparison values (you provided 1).")
pass(t, so(nil, ShouldBeNil))
fail(t, so(1, ShouldBeNil), "Expected: nil Actual: '1'")
var thing Thinger
pass(t, so(thing, ShouldBeNil))
thing = &Thing{}
fail(t, so(thing, ShouldBeNil), "Expected: nil Actual: '&{}'")
var thingOne *Thing1
pass(t, so(thingOne, ShouldBeNil))
var nilSlice []int = nil
pass(t, so(nilSlice, ShouldBeNil))
var nilMap map[string]string = nil
pass(t, so(nilMap, ShouldBeNil))
var nilChannel chan int = nil
pass(t, so(nilChannel, ShouldBeNil))
var nilFunc func() = nil
pass(t, so(nilFunc, ShouldBeNil))
var nilInterface interface{} = nil
pass(t, so(nilInterface, ShouldBeNil))
}
func TestShouldNotBeNil(t *testing.T) {
fail(t, so(nil, ShouldNotBeNil, nil, nil, nil), "This assertion requires exactly 0 comparison values (you provided 3).")
fail(t, so(nil, ShouldNotBeNil, nil), "This assertion requires exactly 0 comparison values (you provided 1).")
fail(t, so(nil, ShouldNotBeNil), "Expected '<nil>' to NOT be nil (but it was)!")
pass(t, so(1, ShouldNotBeNil))
var thing Thinger
fail(t, so(thing, ShouldNotBeNil), "Expected '<nil>' to NOT be nil (but it was)!")
thing = &Thing{}
pass(t, so(thing, ShouldNotBeNil))
}
func TestShouldBeTrue(t *testing.T) {
fail(t, so(true, ShouldBeTrue, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).")
fail(t, so(true, ShouldBeTrue, 1), "This assertion requires exactly 0 comparison values (you provided 1).")
fail(t, so(false, ShouldBeTrue), "Expected: true Actual: false")
fail(t, so(1, ShouldBeTrue), "Expected: true Actual: 1")
pass(t, so(true, ShouldBeTrue))
}
func TestShouldBeFalse(t *testing.T) {
fail(t, so(false, ShouldBeFalse, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).")
fail(t, so(false, ShouldBeFalse, 1), "This assertion requires exactly 0 comparison values (you provided 1).")
fail(t, so(true, ShouldBeFalse), "Expected: false Actual: true")
fail(t, so(1, ShouldBeFalse), "Expected: false Actual: 1")
pass(t, so(false, ShouldBeFalse))
}
func TestShouldBeZeroValue(t *testing.T) {
serializer = newFakeSerializer()
fail(t, so(0, ShouldBeZeroValue, 1, 2, 3), "This assertion requires exactly 0 comparison values (you provided 3).")
fail(t, so(false, ShouldBeZeroValue, true), "This assertion requires exactly 0 comparison values (you provided 1).")
fail(t, so(1, ShouldBeZeroValue), "0|1|'1' should have been the zero value") //"Expected: (zero value) Actual: 1")
fail(t, so(true, ShouldBeZeroValue), "false|true|'true' should have been the zero value") //"Expected: (zero value) Actual: true")
fail(t, so("123", ShouldBeZeroValue), "|123|'123' should have been the zero value") //"Expected: (zero value) Actual: 123")
fail(t, so(" ", ShouldBeZeroValue), "| |' ' should have been the zero value") //"Expected: (zero value) Actual: ")
fail(t, so([]string{"Nonempty"}, ShouldBeZeroValue), "[]|[Nonempty]|'[Nonempty]' should have been the zero value") //"Expected: (zero value) Actual: [Nonempty]")
fail(t, so(struct{ a string }{a: "asdf"}, ShouldBeZeroValue), "{}|{asdf}|'{a:asdf}' should have been the zero value")
pass(t, so(0, ShouldBeZeroValue))
pass(t, so(false, ShouldBeZeroValue))
pass(t, so("", ShouldBeZeroValue))
pass(t, so(struct{}{}, ShouldBeZeroValue))
}

View File

@ -1,6 +0,0 @@
package assertions
var (
serializer Serializer = newSerializer()
noop Serializer = new(noopSerializer)
)

View File

@ -1,110 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type allOfFakeMatcher struct {
desc string
err error
}
func (m *allOfFakeMatcher) Matches(c interface{}) error {
return m.err
}
func (m *allOfFakeMatcher) Description() string {
return m.desc
}
type AllOfTest struct {
}
func init() { RegisterTestSuite(&AllOfTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *AllOfTest) DescriptionWithEmptySet() {
m := AllOf()
ExpectEq("is anything", m.Description())
}
func (t *AllOfTest) DescriptionWithOneMatcher() {
m := AllOf(&allOfFakeMatcher{"taco", errors.New("")})
ExpectEq("taco", m.Description())
}
func (t *AllOfTest) DescriptionWithMultipleMatchers() {
m := AllOf(
&allOfFakeMatcher{"taco", errors.New("")},
&allOfFakeMatcher{"burrito", errors.New("")},
&allOfFakeMatcher{"enchilada", errors.New("")})
ExpectEq("taco, and burrito, and enchilada", m.Description())
}
func (t *AllOfTest) EmptySet() {
m := AllOf()
err := m.Matches(17)
ExpectEq(nil, err)
}
func (t *AllOfTest) OneMatcherReturnsFatalErrorAndSomeOthersFail() {
m := AllOf(
&allOfFakeMatcher{"", errors.New("")},
&allOfFakeMatcher{"", NewFatalError("taco")},
&allOfFakeMatcher{"", errors.New("")},
&allOfFakeMatcher{"", nil})
err := m.Matches(17)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("taco")))
}
func (t *AllOfTest) OneMatcherReturnsNonFatalAndOthersSayTrue() {
m := AllOf(
&allOfFakeMatcher{"", nil},
&allOfFakeMatcher{"", errors.New("taco")},
&allOfFakeMatcher{"", nil})
err := m.Matches(17)
ExpectFalse(isFatal(err))
ExpectThat(err, Error(Equals("taco")))
}
func (t *AllOfTest) AllMatchersSayTrue() {
m := AllOf(
&allOfFakeMatcher{"", nil},
&allOfFakeMatcher{"", nil},
&allOfFakeMatcher{"", nil})
err := m.Matches(17)
ExpectEq(nil, err)
}

View File

@ -1,121 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type fakeAnyOfMatcher struct {
desc string
err error
}
func (m *fakeAnyOfMatcher) Matches(c interface{}) error {
return m.err
}
func (m *fakeAnyOfMatcher) Description() string {
return m.desc
}
type AnyOfTest struct {
}
func init() { RegisterTestSuite(&AnyOfTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *AnyOfTest) EmptySet() {
matcher := AnyOf()
err := matcher.Matches(0)
ExpectThat(err, Error(Equals("")))
}
func (t *AnyOfTest) OneTrue() {
matcher := AnyOf(
&fakeAnyOfMatcher{"", NewFatalError("foo")},
17,
&fakeAnyOfMatcher{"", errors.New("foo")},
&fakeAnyOfMatcher{"", nil},
&fakeAnyOfMatcher{"", errors.New("foo")},
)
err := matcher.Matches(0)
ExpectEq(nil, err)
}
func (t *AnyOfTest) OneEqual() {
matcher := AnyOf(
&fakeAnyOfMatcher{"", NewFatalError("foo")},
&fakeAnyOfMatcher{"", errors.New("foo")},
13,
"taco",
19,
&fakeAnyOfMatcher{"", errors.New("foo")},
)
err := matcher.Matches("taco")
ExpectEq(nil, err)
}
func (t *AnyOfTest) OneFatal() {
matcher := AnyOf(
&fakeAnyOfMatcher{"", errors.New("foo")},
17,
&fakeAnyOfMatcher{"", NewFatalError("taco")},
&fakeAnyOfMatcher{"", errors.New("foo")},
)
err := matcher.Matches(0)
ExpectThat(err, Error(Equals("taco")))
}
func (t *AnyOfTest) AllFalseAndNotEqual() {
matcher := AnyOf(
&fakeAnyOfMatcher{"", errors.New("foo")},
17,
&fakeAnyOfMatcher{"", errors.New("foo")},
19,
)
err := matcher.Matches(0)
ExpectThat(err, Error(Equals("")))
}
func (t *AnyOfTest) DescriptionForEmptySet() {
matcher := AnyOf()
ExpectEq("or()", matcher.Description())
}
func (t *AnyOfTest) DescriptionForNonEmptySet() {
matcher := AnyOf(
&fakeAnyOfMatcher{"taco", nil},
"burrito",
&fakeAnyOfMatcher{"enchilada", nil},
)
ExpectEq("or(taco, burrito, enchilada)", matcher.Description())
}

View File

@ -1,53 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type AnyTest struct {
}
func init() { RegisterTestSuite(&AnyTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *AnyTest) Description() {
m := Any()
ExpectEq("is anything", m.Description())
}
func (t *AnyTest) Matches() {
var err error
m := Any()
err = m.Matches(nil)
ExpectEq(nil, err)
err = m.Matches(17)
ExpectEq(nil, err)
err = m.Matches("taco")
ExpectEq(nil, err)
}

View File

@ -1,234 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type ContainsTest struct{}
func init() { RegisterTestSuite(&ContainsTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *ContainsTest) WrongTypeCandidates() {
m := Contains("")
ExpectEq("contains: ", m.Description())
var err error
// Nil candidate
err = m.Matches(nil)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
// String candidate
err = m.Matches("")
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
// Map candidate
err = m.Matches(make(map[string]string))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
}
func (t *ContainsTest) NilArgument() {
m := Contains(nil)
ExpectEq("contains: is nil", m.Description())
var c interface{}
var err error
// Empty array of pointers
c = [...]*int{}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Empty slice of pointers
c = []*int{}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-empty array of integers
c = [...]int{17, 0, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-empty slice of integers
c = []int{17, 0, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching array of pointers
c = [...]*int{new(int), new(int)}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching slice of pointers
c = []*int{new(int), new(int)}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Matching array of pointers
c = [...]*int{new(int), nil, new(int)}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching slice of pointers
c = []*int{new(int), nil, new(int)}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching slice of pointers from matching array
someArray := [...]*int{new(int), nil, new(int)}
c = someArray[0:1]
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *ContainsTest) StringArgument() {
m := Contains("taco")
ExpectEq("contains: taco", m.Description())
var c interface{}
var err error
// Non-matching array of strings
c = [...]string{"burrito", "enchilada"}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching slice of strings
c = []string{"burrito", "enchilada"}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Matching array of strings
c = [...]string{"burrito", "taco", "enchilada"}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching slice of strings
c = []string{"burrito", "taco", "enchilada"}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching slice of strings from matching array
someArray := [...]string{"burrito", "taco", "enchilada"}
c = someArray[0:1]
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *ContainsTest) IntegerArgument() {
m := Contains(int(17))
ExpectEq("contains: 17", m.Description())
var c interface{}
var err error
// Non-matching array of integers
c = [...]int{13, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching slice of integers
c = []int{13, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Matching array of integers
c = [...]int{13, 17, 19}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching slice of integers
c = []int{13, 17, 19}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching slice of integers from matching array
someArray := [...]int{13, 17, 19}
c = someArray[0:1]
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching array of floats
c = [...]float32{13, 17.5, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching slice of floats
c = []float32{13, 17.5, 19}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Matching array of floats
c = [...]float32{13, 17, 19}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching slice of floats
c = []float32{13, 17, 19}
err = m.Matches(c)
ExpectEq(nil, err)
}
func (t *ContainsTest) MatcherArgument() {
m := Contains(HasSubstr("ac"))
ExpectEq("contains: has substring \"ac\"", m.Description())
var c interface{}
var err error
// Non-matching array of strings
c = [...]string{"burrito", "enchilada"}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Non-matching slice of strings
c = []string{"burrito", "enchilada"}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Matching array of strings
c = [...]string{"burrito", "taco", "enchilada"}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching slice of strings
c = []string{"burrito", "taco", "enchilada"}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching slice of strings from matching array
someArray := [...]string{"burrito", "taco", "enchilada"}
c = someArray[0:1]
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}

View File

@ -1,344 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"bytes"
"testing"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type DeepEqualsTest struct{}
func init() { RegisterTestSuite(&DeepEqualsTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *DeepEqualsTest) WrongTypeCandidateWithScalarValue() {
var x int = 17
m := DeepEquals(x)
var err error
// Nil candidate.
err = m.Matches(nil)
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("<nil>")))
// Int alias candidate.
type intAlias int
err = m.Matches(intAlias(x))
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("intAlias")))
// String candidate.
err = m.Matches("taco")
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("string")))
// Byte slice candidate.
err = m.Matches([]byte{})
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint8")))
// Other slice candidate.
err = m.Matches([]uint16{})
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint16")))
// Unsigned int candidate.
err = m.Matches(uint(17))
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("uint")))
}
func (t *DeepEqualsTest) WrongTypeCandidateWithByteSliceValue() {
x := []byte{}
m := DeepEquals(x)
var err error
// Nil candidate.
err = m.Matches(nil)
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("<nil>")))
// String candidate.
err = m.Matches("taco")
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("string")))
// Slice candidate with wrong value type.
err = m.Matches([]uint16{})
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint16")))
}
func (t *DeepEqualsTest) WrongTypeCandidateWithOtherSliceValue() {
x := []uint16{}
m := DeepEquals(x)
var err error
// Nil candidate.
err = m.Matches(nil)
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("<nil>")))
// String candidate.
err = m.Matches("taco")
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("string")))
// Byte slice candidate with wrong value type.
err = m.Matches([]byte{})
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint8")))
// Other slice candidate with wrong value type.
err = m.Matches([]uint32{})
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint32")))
}
func (t *DeepEqualsTest) WrongTypeCandidateWithNilLiteralValue() {
m := DeepEquals(nil)
var err error
// String candidate.
err = m.Matches("taco")
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("string")))
// Nil byte slice candidate.
err = m.Matches([]byte(nil))
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint8")))
// Nil other slice candidate.
err = m.Matches([]uint16(nil))
AssertNe(nil, err)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("type")))
ExpectThat(err, Error(HasSubstr("[]uint16")))
}
func (t *DeepEqualsTest) NilLiteralValue() {
m := DeepEquals(nil)
ExpectEq("deep equals: <nil>", m.Description())
var c interface{}
var err error
// Nil literal candidate.
c = nil
err = m.Matches(c)
ExpectEq(nil, err)
}
func (t *DeepEqualsTest) IntValue() {
m := DeepEquals(int(17))
ExpectEq("deep equals: 17", m.Description())
var c interface{}
var err error
// Matching int.
c = int(17)
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching int.
c = int(18)
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *DeepEqualsTest) ByteSliceValue() {
x := []byte{17, 19}
m := DeepEquals(x)
ExpectEq("deep equals: [17 19]", m.Description())
var c []byte
var err error
// Matching.
c = make([]byte, len(x))
AssertEq(len(x), copy(c, x))
err = m.Matches(c)
ExpectEq(nil, err)
// Nil slice.
c = []byte(nil)
err = m.Matches(c)
ExpectThat(err, Error(Equals("which is nil")))
// Prefix.
AssertGt(len(x), 1)
c = make([]byte, len(x)-1)
AssertEq(len(x)-1, copy(c, x))
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Suffix.
c = make([]byte, len(x)+1)
AssertEq(len(x), copy(c, x))
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *DeepEqualsTest) OtherSliceValue() {
x := []uint16{17, 19}
m := DeepEquals(x)
ExpectEq("deep equals: [17 19]", m.Description())
var c []uint16
var err error
// Matching.
c = make([]uint16, len(x))
AssertEq(len(x), copy(c, x))
err = m.Matches(c)
ExpectEq(nil, err)
// Nil slice.
c = []uint16(nil)
err = m.Matches(c)
ExpectThat(err, Error(Equals("which is nil")))
// Prefix.
AssertGt(len(x), 1)
c = make([]uint16, len(x)-1)
AssertEq(len(x)-1, copy(c, x))
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
// Suffix.
c = make([]uint16, len(x)+1)
AssertEq(len(x), copy(c, x))
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *DeepEqualsTest) NilByteSliceValue() {
x := []byte(nil)
m := DeepEquals(x)
ExpectEq("deep equals: <nil slice>", m.Description())
var c []byte
var err error
// Nil slice.
c = []byte(nil)
err = m.Matches(c)
ExpectEq(nil, err)
// Non-nil slice.
c = []byte{}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
func (t *DeepEqualsTest) NilOtherSliceValue() {
x := []uint16(nil)
m := DeepEquals(x)
ExpectEq("deep equals: <nil slice>", m.Description())
var c []uint16
var err error
// Nil slice.
c = []uint16(nil)
err = m.Matches(c)
ExpectEq(nil, err)
// Non-nil slice.
c = []uint16{}
err = m.Matches(c)
ExpectThat(err, Error(Equals("")))
}
////////////////////////////////////////////////////////////////////////
// Benchmarks
////////////////////////////////////////////////////////////////////////
func benchmarkWithSize(b *testing.B, size int) {
b.StopTimer()
buf := bytes.Repeat([]byte{0x01}, size)
bufCopy := make([]byte, size)
copy(bufCopy, buf)
matcher := DeepEquals(buf)
b.StartTimer()
for i := 0; i < b.N; i++ {
matcher.Matches(bufCopy)
}
b.SetBytes(int64(size))
}
func BenchmarkShortByteSlice(b *testing.B) {
benchmarkWithSize(b, 256)
}
func BenchmarkLongByteSlice(b *testing.B) {
benchmarkWithSize(b, 1<<24)
}

View File

@ -1,208 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type ElementsAreTest struct {
}
func init() { RegisterTestSuite(&ElementsAreTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *ElementsAreTest) EmptySet() {
m := ElementsAre()
ExpectEq("elements are: []", m.Description())
var c []interface{}
var err error
// No candidates.
c = []interface{}{}
err = m.Matches(c)
ExpectEq(nil, err)
// One candidate.
c = []interface{}{17}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 1")))
}
func (t *ElementsAreTest) OneMatcher() {
m := ElementsAre(LessThan(17))
ExpectEq("elements are: [less than 17]", m.Description())
var c []interface{}
var err error
// No candidates.
c = []interface{}{}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 0")))
// Matching candidate.
c = []interface{}{16}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching candidate.
c = []interface{}{19}
err = m.Matches(c)
ExpectNe(nil, err)
// Two candidates.
c = []interface{}{17, 19}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 2")))
}
func (t *ElementsAreTest) OneValue() {
m := ElementsAre(17)
ExpectEq("elements are: [17]", m.Description())
var c []interface{}
var err error
// No candidates.
c = []interface{}{}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 0")))
// Matching int.
c = []interface{}{int(17)}
err = m.Matches(c)
ExpectEq(nil, err)
// Matching float.
c = []interface{}{float32(17)}
err = m.Matches(c)
ExpectEq(nil, err)
// Non-matching candidate.
c = []interface{}{19}
err = m.Matches(c)
ExpectNe(nil, err)
// Two candidates.
c = []interface{}{17, 19}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 2")))
}
func (t *ElementsAreTest) MultipleElements() {
m := ElementsAre("taco", LessThan(17))
ExpectEq("elements are: [taco, less than 17]", m.Description())
var c []interface{}
var err error
// One candidate.
c = []interface{}{17}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 1")))
// Both matching.
c = []interface{}{"taco", 16}
err = m.Matches(c)
ExpectEq(nil, err)
// First non-matching.
c = []interface{}{"burrito", 16}
err = m.Matches(c)
ExpectThat(err, Error(Equals("whose element 0 doesn't match")))
// Second non-matching.
c = []interface{}{"taco", 17}
err = m.Matches(c)
ExpectThat(err, Error(Equals("whose element 1 doesn't match")))
// Three candidates.
c = []interface{}{"taco", 17, 19}
err = m.Matches(c)
ExpectThat(err, Error(HasSubstr("length 3")))
}
func (t *ElementsAreTest) ArrayCandidates() {
m := ElementsAre("taco", LessThan(17))
var err error
// One candidate.
err = m.Matches([1]interface{}{"taco"})
ExpectThat(err, Error(HasSubstr("length 1")))
// Both matching.
err = m.Matches([2]interface{}{"taco", 16})
ExpectEq(nil, err)
// First non-matching.
err = m.Matches([2]interface{}{"burrito", 16})
ExpectThat(err, Error(Equals("whose element 0 doesn't match")))
}
func (t *ElementsAreTest) WrongTypeCandidate() {
m := ElementsAre("taco")
var err error
// String candidate.
err = m.Matches("taco")
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
// Map candidate.
err = m.Matches(map[string]string{})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
// Nil candidate.
err = m.Matches(nil)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("array")))
ExpectThat(err, Error(HasSubstr("slice")))
}
func (t *ElementsAreTest) PropagatesFatality() {
m := ElementsAre(LessThan(17))
ExpectEq("elements are: [less than 17]", m.Description())
var c []interface{}
var err error
// Non-fatal error.
c = []interface{}{19}
err = m.Matches(c)
AssertNe(nil, err)
ExpectFalse(isFatal(err))
// Fatal error.
c = []interface{}{"taco"}
err = m.Matches(c)
AssertNe(nil, err)
ExpectTrue(isFatal(err))
}

View File

@ -1,92 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type ErrorTest struct {
matcherCalled bool
suppliedCandidate interface{}
wrappedError error
matcher Matcher
}
func init() { RegisterTestSuite(&ErrorTest{}) }
func (t *ErrorTest) SetUp(i *TestInfo) {
wrapped := &fakeMatcher{
func(c interface{}) error {
t.matcherCalled = true
t.suppliedCandidate = c
return t.wrappedError
},
"is foo",
}
t.matcher = Error(wrapped)
}
func isFatal(err error) bool {
_, isFatal := err.(*FatalError)
return isFatal
}
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *ErrorTest) Description() {
ExpectThat(t.matcher.Description(), Equals("error is foo"))
}
func (t *ErrorTest) CandidateIsNil() {
err := t.matcher.Matches(nil)
ExpectThat(t.matcherCalled, Equals(false))
ExpectThat(err.Error(), Equals("which is not an error"))
ExpectTrue(isFatal(err))
}
func (t *ErrorTest) CandidateIsString() {
err := t.matcher.Matches("taco")
ExpectThat(t.matcherCalled, Equals(false))
ExpectThat(err.Error(), Equals("which is not an error"))
ExpectTrue(isFatal(err))
}
func (t *ErrorTest) CallsWrappedMatcher() {
candidate := errors.New("taco")
t.matcher.Matches(candidate)
ExpectThat(t.matcherCalled, Equals(true))
ExpectThat(t.suppliedCandidate, Equals("taco"))
}
func (t *ErrorTest) ReturnsWrappedMatcherResult() {
t.wrappedError = errors.New("burrito")
err := t.matcher.Matches(errors.New(""))
ExpectThat(err, Equals(t.wrappedError))
}

View File

@ -1,92 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type HasSubstrTest struct {
}
func init() { RegisterTestSuite(&HasSubstrTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *HasSubstrTest) Description() {
matcher := HasSubstr("taco")
ExpectThat(matcher.Description(), Equals("has substring \"taco\""))
}
func (t *HasSubstrTest) CandidateIsNil() {
matcher := HasSubstr("")
err := matcher.Matches(nil)
ExpectThat(err, Error(Equals("which is not a string")))
ExpectTrue(isFatal(err))
}
func (t *HasSubstrTest) CandidateIsInteger() {
matcher := HasSubstr("")
err := matcher.Matches(17)
ExpectThat(err, Error(Equals("which is not a string")))
ExpectTrue(isFatal(err))
}
func (t *HasSubstrTest) CandidateIsByteSlice() {
matcher := HasSubstr("")
err := matcher.Matches([]byte{17})
ExpectThat(err, Error(Equals("which is not a string")))
ExpectTrue(isFatal(err))
}
func (t *HasSubstrTest) CandidateDoesntHaveSubstring() {
matcher := HasSubstr("taco")
err := matcher.Matches("tac")
ExpectThat(err, Error(Equals("")))
ExpectFalse(isFatal(err))
}
func (t *HasSubstrTest) CandidateEqualsArg() {
matcher := HasSubstr("taco")
err := matcher.Matches("taco")
ExpectThat(err, Equals(nil))
}
func (t *HasSubstrTest) CandidateHasProperSubstring() {
matcher := HasSubstr("taco")
err := matcher.Matches("burritos and tacos")
ExpectThat(err, Equals(nil))
}
func (t *HasSubstrTest) EmptyStringIsAlwaysSubString() {
matcher := HasSubstr("")
err := matcher.Matches("asdf")
ExpectThat(err, Equals(nil))
}

View File

@ -1,849 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"fmt"
"io"
"unsafe"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type IdenticalToTest struct {
}
func init() { RegisterTestSuite(&IdenticalToTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *IdenticalToTest) TypesNotIdentical() {
var m Matcher
var err error
type intAlias int
// Type alias expected value
m = IdenticalTo(intAlias(17))
err = m.Matches(int(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int")))
// Type alias candidate
m = IdenticalTo(int(17))
err = m.Matches(intAlias(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.intAlias")))
// int and uint
m = IdenticalTo(int(17))
err = m.Matches(uint(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type uint")))
}
func (t *IdenticalToTest) PredeclaredNilIdentifier() {
var m Matcher
var err error
// Nil literal
m = IdenticalTo(nil)
err = m.Matches(nil)
ExpectEq(nil, err)
// Zero interface var (which is the same as above since IdenticalTo takes an
// interface{} as an arg)
var nilReader io.Reader
var nilWriter io.Writer
m = IdenticalTo(nilReader)
err = m.Matches(nilWriter)
ExpectEq(nil, err)
// Typed nil value.
m = IdenticalTo(nil)
err = m.Matches((chan int)(nil))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type chan int")))
// Non-nil value.
m = IdenticalTo(nil)
err = m.Matches("taco")
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type string")))
}
func (t *IdenticalToTest) Slices() {
var m Matcher
var err error
// Nil expected value
m = IdenticalTo(([]int)(nil))
ExpectEq("identical to <[]int> []", m.Description())
err = m.Matches(([]int)(nil))
ExpectEq(nil, err)
err = m.Matches([]int{})
ExpectThat(err, Error(Equals("which is not an identical reference")))
// Non-nil expected value
o1 := make([]int, 1)
o2 := make([]int, 1)
m = IdenticalTo(o1)
ExpectEq(fmt.Sprintf("identical to <[]int> %v", o1), m.Description())
err = m.Matches(o1)
ExpectEq(nil, err)
err = m.Matches(o2)
ExpectThat(err, Error(Equals("which is not an identical reference")))
}
func (t *IdenticalToTest) Maps() {
var m Matcher
var err error
// Nil expected value
m = IdenticalTo((map[int]int)(nil))
ExpectEq("identical to <map[int]int> map[]", m.Description())
err = m.Matches((map[int]int)(nil))
ExpectEq(nil, err)
err = m.Matches(map[int]int{})
ExpectThat(err, Error(Equals("which is not an identical reference")))
// Non-nil expected value
o1 := map[int]int{}
o2 := map[int]int{}
m = IdenticalTo(o1)
ExpectEq(fmt.Sprintf("identical to <map[int]int> %v", o1), m.Description())
err = m.Matches(o1)
ExpectEq(nil, err)
err = m.Matches(o2)
ExpectThat(err, Error(Equals("which is not an identical reference")))
}
func (t *IdenticalToTest) Functions() {
var m Matcher
var err error
// Nil expected value
m = IdenticalTo((func())(nil))
ExpectEq("identical to <func()> <nil>", m.Description())
err = m.Matches((func())(nil))
ExpectEq(nil, err)
err = m.Matches(func() {})
ExpectThat(err, Error(Equals("which is not an identical reference")))
// Non-nil expected value
o1 := func() {}
o2 := func() {}
m = IdenticalTo(o1)
ExpectEq(fmt.Sprintf("identical to <func()> %v", o1), m.Description())
err = m.Matches(o1)
ExpectEq(nil, err)
err = m.Matches(o2)
ExpectThat(err, Error(Equals("which is not an identical reference")))
}
func (t *IdenticalToTest) Channels() {
var m Matcher
var err error
// Nil expected value
m = IdenticalTo((chan int)(nil))
ExpectEq("identical to <chan int> <nil>", m.Description())
err = m.Matches((chan int)(nil))
ExpectEq(nil, err)
err = m.Matches(make(chan int))
ExpectThat(err, Error(Equals("which is not an identical reference")))
// Non-nil expected value
o1 := make(chan int)
o2 := make(chan int)
m = IdenticalTo(o1)
ExpectEq(fmt.Sprintf("identical to <chan int> %v", o1), m.Description())
err = m.Matches(o1)
ExpectEq(nil, err)
err = m.Matches(o2)
ExpectThat(err, Error(Equals("which is not an identical reference")))
}
func (t *IdenticalToTest) Bools() {
var m Matcher
var err error
// false
m = IdenticalTo(false)
ExpectEq("identical to <bool> false", m.Description())
err = m.Matches(false)
ExpectEq(nil, err)
err = m.Matches(true)
ExpectThat(err, Error(Equals("")))
// true
m = IdenticalTo(true)
ExpectEq("identical to <bool> true", m.Description())
err = m.Matches(false)
ExpectThat(err, Error(Equals("")))
err = m.Matches(true)
ExpectEq(nil, err)
}
func (t *IdenticalToTest) Ints() {
var m Matcher
var err error
m = IdenticalTo(int(17))
ExpectEq("identical to <int> 17", m.Description())
// Identical value
err = m.Matches(int(17))
ExpectEq(nil, err)
// Type alias
type myType int
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Int8s() {
var m Matcher
var err error
m = IdenticalTo(int8(17))
ExpectEq("identical to <int8> 17", m.Description())
// Identical value
err = m.Matches(int8(17))
ExpectEq(nil, err)
// Type alias
type myType int8
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Int16s() {
var m Matcher
var err error
m = IdenticalTo(int16(17))
ExpectEq("identical to <int16> 17", m.Description())
// Identical value
err = m.Matches(int16(17))
ExpectEq(nil, err)
// Type alias
type myType int16
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Int32s() {
var m Matcher
var err error
m = IdenticalTo(int32(17))
ExpectEq("identical to <int32> 17", m.Description())
// Identical value
err = m.Matches(int32(17))
ExpectEq(nil, err)
// Type alias
type myType int32
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int16(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int16")))
}
func (t *IdenticalToTest) Int64s() {
var m Matcher
var err error
m = IdenticalTo(int64(17))
ExpectEq("identical to <int64> 17", m.Description())
// Identical value
err = m.Matches(int64(17))
ExpectEq(nil, err)
// Type alias
type myType int64
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uints() {
var m Matcher
var err error
m = IdenticalTo(uint(17))
ExpectEq("identical to <uint> 17", m.Description())
// Identical value
err = m.Matches(uint(17))
ExpectEq(nil, err)
// Type alias
type myType uint
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uint8s() {
var m Matcher
var err error
m = IdenticalTo(uint8(17))
ExpectEq("identical to <uint8> 17", m.Description())
// Identical value
err = m.Matches(uint8(17))
ExpectEq(nil, err)
// Type alias
type myType uint8
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uint16s() {
var m Matcher
var err error
m = IdenticalTo(uint16(17))
ExpectEq("identical to <uint16> 17", m.Description())
// Identical value
err = m.Matches(uint16(17))
ExpectEq(nil, err)
// Type alias
type myType uint16
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uint32s() {
var m Matcher
var err error
m = IdenticalTo(uint32(17))
ExpectEq("identical to <uint32> 17", m.Description())
// Identical value
err = m.Matches(uint32(17))
ExpectEq(nil, err)
// Type alias
type myType uint32
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uint64s() {
var m Matcher
var err error
m = IdenticalTo(uint64(17))
ExpectEq("identical to <uint64> 17", m.Description())
// Identical value
err = m.Matches(uint64(17))
ExpectEq(nil, err)
// Type alias
type myType uint64
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Uintptrs() {
var m Matcher
var err error
m = IdenticalTo(uintptr(17))
ExpectEq("identical to <uintptr> 17", m.Description())
// Identical value
err = m.Matches(uintptr(17))
ExpectEq(nil, err)
// Type alias
type myType uintptr
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Float32s() {
var m Matcher
var err error
m = IdenticalTo(float32(17))
ExpectEq("identical to <float32> 17", m.Description())
// Identical value
err = m.Matches(float32(17))
ExpectEq(nil, err)
// Type alias
type myType float32
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Float64s() {
var m Matcher
var err error
m = IdenticalTo(float64(17))
ExpectEq("identical to <float64> 17", m.Description())
// Identical value
err = m.Matches(float64(17))
ExpectEq(nil, err)
// Type alias
type myType float64
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Complex64s() {
var m Matcher
var err error
m = IdenticalTo(complex64(17))
ExpectEq("identical to <complex64> (17+0i)", m.Description())
// Identical value
err = m.Matches(complex64(17))
ExpectEq(nil, err)
// Type alias
type myType complex64
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) Complex128s() {
var m Matcher
var err error
m = IdenticalTo(complex128(17))
ExpectEq("identical to <complex128> (17+0i)", m.Description())
// Identical value
err = m.Matches(complex128(17))
ExpectEq(nil, err)
// Type alias
type myType complex128
err = m.Matches(myType(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) EmptyComparableArrays() {
var m Matcher
var err error
m = IdenticalTo([0]int{})
ExpectEq("identical to <[0]int> []", m.Description())
// Identical value
err = m.Matches([0]int{})
ExpectEq(nil, err)
// Length too long
err = m.Matches([1]int{17})
ExpectThat(err, Error(Equals("which is of type [1]int")))
// Element type alias
type myType int
err = m.Matches([0]myType{})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type [0]oglematchers_test.myType")))
// Completely wrong element type
err = m.Matches([0]int32{})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type [0]int32")))
}
func (t *IdenticalToTest) NonEmptyComparableArrays() {
var m Matcher
var err error
m = IdenticalTo([2]int{17, 19})
ExpectEq("identical to <[2]int> [17 19]", m.Description())
// Identical value
err = m.Matches([2]int{17, 19})
ExpectEq(nil, err)
// Length too short
err = m.Matches([1]int{17})
ExpectThat(err, Error(Equals("which is of type [1]int")))
// Length too long
err = m.Matches([3]int{17, 19, 23})
ExpectThat(err, Error(Equals("which is of type [3]int")))
// First element different
err = m.Matches([2]int{13, 19})
ExpectThat(err, Error(Equals("")))
// Second element different
err = m.Matches([2]int{17, 23})
ExpectThat(err, Error(Equals("")))
// Element type alias
type myType int
err = m.Matches([2]myType{17, 19})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type [2]oglematchers_test.myType")))
// Completely wrong element type
err = m.Matches([2]int32{17, 19})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type [2]int32")))
}
func (t *IdenticalToTest) NonEmptyArraysOfComparableArrays() {
var m Matcher
var err error
x := [2][2]int{
[2]int{17, 19},
[2]int{23, 29},
}
m = IdenticalTo(x)
ExpectEq("identical to <[2][2]int> [[17 19] [23 29]]", m.Description())
// Identical value
err = m.Matches([2][2]int{[2]int{17, 19}, [2]int{23, 29}})
ExpectEq(nil, err)
// Outer length too short
err = m.Matches([1][2]int{[2]int{17, 19}})
ExpectThat(err, Error(Equals("which is of type [1][2]int")))
// Inner length too short
err = m.Matches([2][1]int{[1]int{17}, [1]int{23}})
ExpectThat(err, Error(Equals("which is of type [2][1]int")))
// First element different
err = m.Matches([2][2]int{[2]int{13, 19}, [2]int{23, 29}})
ExpectThat(err, Error(Equals("")))
// Element type alias
type myType int
err = m.Matches([2][2]myType{[2]myType{17, 19}, [2]myType{23, 29}})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type [2][2]oglematchers_test.myType")))
}
func (t *IdenticalToTest) NonComparableArrays() {
x := [0]func(){}
f := func() { IdenticalTo(x) }
ExpectThat(f, Panics(HasSubstr("is not comparable")))
}
func (t *IdenticalToTest) ArraysOfNonComparableArrays() {
x := [0][0]func(){}
f := func() { IdenticalTo(x) }
ExpectThat(f, Panics(HasSubstr("is not comparable")))
}
func (t *IdenticalToTest) Strings() {
var m Matcher
var err error
m = IdenticalTo("taco")
ExpectEq("identical to <string> taco", m.Description())
// Identical value
err = m.Matches("ta" + "co")
ExpectEq(nil, err)
// Type alias
type myType string
err = m.Matches(myType("taco"))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) ComparableStructs() {
var m Matcher
var err error
type subStruct struct {
i int
}
type myStruct struct {
u uint
s subStruct
}
x := myStruct{17, subStruct{19}}
m = IdenticalTo(x)
ExpectEq("identical to <oglematchers_test.myStruct> {17 {19}}", m.Description())
// Identical value
err = m.Matches(myStruct{17, subStruct{19}})
ExpectEq(nil, err)
// Wrong outer field
err = m.Matches(myStruct{13, subStruct{19}})
ExpectThat(err, Error(Equals("")))
// Wrong inner field
err = m.Matches(myStruct{17, subStruct{23}})
ExpectThat(err, Error(Equals("")))
// Type alias
type myType myStruct
err = m.Matches(myType{17, subStruct{19}})
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) NonComparableStructs() {
type subStruct struct {
s []int
}
type myStruct struct {
u uint
s subStruct
}
x := myStruct{17, subStruct{[]int{19}}}
f := func() { IdenticalTo(x) }
ExpectThat(f, Panics(AllOf(HasSubstr("IdenticalTo"), HasSubstr("comparable"))))
}
func (t *IdenticalToTest) NilUnsafePointer() {
var m Matcher
var err error
x := unsafe.Pointer(nil)
m = IdenticalTo(x)
ExpectEq(fmt.Sprintf("identical to <unsafe.Pointer> %v", x), m.Description())
// Identical value
err = m.Matches(unsafe.Pointer(nil))
ExpectEq(nil, err)
// Wrong value
j := 17
err = m.Matches(unsafe.Pointer(&j))
ExpectThat(err, Error(Equals("")))
// Type alias
type myType unsafe.Pointer
err = m.Matches(myType(unsafe.Pointer(nil)))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) NonNilUnsafePointer() {
var m Matcher
var err error
i := 17
x := unsafe.Pointer(&i)
m = IdenticalTo(x)
ExpectEq(fmt.Sprintf("identical to <unsafe.Pointer> %v", x), m.Description())
// Identical value
err = m.Matches(unsafe.Pointer(&i))
ExpectEq(nil, err)
// Nil value
err = m.Matches(unsafe.Pointer(nil))
ExpectThat(err, Error(Equals("")))
// Wrong value
j := 17
err = m.Matches(unsafe.Pointer(&j))
ExpectThat(err, Error(Equals("")))
// Type alias
type myType unsafe.Pointer
err = m.Matches(myType(unsafe.Pointer(&i)))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type oglematchers_test.myType")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}
func (t *IdenticalToTest) IntAlias() {
var m Matcher
var err error
type intAlias int
m = IdenticalTo(intAlias(17))
ExpectEq("identical to <oglematchers_test.intAlias> 17", m.Description())
// Identical value
err = m.Matches(intAlias(17))
ExpectEq(nil, err)
// Int
err = m.Matches(int(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int")))
// Completely wrong type
err = m.Matches(int32(17))
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("which is of type int32")))
}

View File

@ -1,92 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type MatchesRegexpTest struct {
}
func init() { RegisterTestSuite(&MatchesRegexpTest{}) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *MatchesRegexpTest) Description() {
m := MatchesRegexp("foo.*bar")
ExpectEq("matches regexp \"foo.*bar\"", m.Description())
}
func (t *MatchesRegexpTest) InvalidRegexp() {
ExpectThat(
func() { MatchesRegexp("(foo") },
Panics(HasSubstr("missing closing )")))
}
func (t *MatchesRegexpTest) CandidateIsNil() {
m := MatchesRegexp("")
err := m.Matches(nil)
ExpectThat(err, Error(Equals("which is not a string or []byte")))
ExpectTrue(isFatal(err))
}
func (t *MatchesRegexpTest) CandidateIsInteger() {
m := MatchesRegexp("")
err := m.Matches(17)
ExpectThat(err, Error(Equals("which is not a string or []byte")))
ExpectTrue(isFatal(err))
}
func (t *MatchesRegexpTest) NonMatchingCandidates() {
m := MatchesRegexp("fo[op]\\s+x")
var err error
err = m.Matches("fon x")
ExpectThat(err, Error(Equals("")))
ExpectFalse(isFatal(err))
err = m.Matches("fopx")
ExpectThat(err, Error(Equals("")))
ExpectFalse(isFatal(err))
err = m.Matches("fop ")
ExpectThat(err, Error(Equals("")))
ExpectFalse(isFatal(err))
}
func (t *MatchesRegexpTest) MatchingCandidates() {
m := MatchesRegexp("fo[op]\\s+x")
var err error
err = m.Matches("foo x")
ExpectEq(nil, err)
err = m.Matches("fop x")
ExpectEq(nil, err)
err = m.Matches("blah blah foo x blah blah")
ExpectEq(nil, err)
}

View File

@ -1,107 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
"testing"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type fakeMatcher struct {
matchFunc func(interface{}) error
description string
}
func (m *fakeMatcher) Matches(c interface{}) error {
return m.matchFunc(c)
}
func (m *fakeMatcher) Description() string {
return m.description
}
type NotTest struct {
}
func init() { RegisterTestSuite(&NotTest{}) }
func TestOgletest(t *testing.T) { RunTests(t) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *NotTest) CallsWrapped() {
var suppliedCandidate interface{}
matchFunc := func(c interface{}) error {
suppliedCandidate = c
return nil
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Not(wrapped)
matcher.Matches(17)
ExpectThat(suppliedCandidate, Equals(17))
}
func (t *NotTest) WrappedReturnsTrue() {
matchFunc := func(c interface{}) error {
return nil
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Not(wrapped)
err := matcher.Matches(0)
ExpectThat(err, Error(Equals("")))
}
func (t *NotTest) WrappedReturnsNonFatalError() {
matchFunc := func(c interface{}) error {
return errors.New("taco")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Not(wrapped)
err := matcher.Matches(0)
ExpectEq(nil, err)
}
func (t *NotTest) WrappedReturnsFatalError() {
matchFunc := func(c interface{}) error {
return NewFatalError("taco")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Not(wrapped)
err := matcher.Matches(0)
ExpectThat(err, Error(Equals("taco")))
}
func (t *NotTest) Description() {
wrapped := &fakeMatcher{nil, "taco"}
matcher := Not(wrapped)
ExpectEq("not(taco)", matcher.Description())
}

View File

@ -1,141 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type PanicsTest struct {
matcherCalled bool
suppliedCandidate interface{}
wrappedError error
matcher Matcher
}
func init() { RegisterTestSuite(&PanicsTest{}) }
func (t *PanicsTest) SetUp(i *TestInfo) {
wrapped := &fakeMatcher{
func(c interface{}) error {
t.matcherCalled = true
t.suppliedCandidate = c
return t.wrappedError
},
"foo",
}
t.matcher = Panics(wrapped)
}
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *PanicsTest) Description() {
ExpectThat(t.matcher.Description(), Equals("panics with: foo"))
}
func (t *PanicsTest) CandidateIsNil() {
err := t.matcher.Matches(nil)
ExpectThat(err, Error(Equals("which is not a zero-arg function")))
ExpectTrue(isFatal(err))
}
func (t *PanicsTest) CandidateIsString() {
err := t.matcher.Matches("taco")
ExpectThat(err, Error(Equals("which is not a zero-arg function")))
ExpectTrue(isFatal(err))
}
func (t *PanicsTest) CandidateTakesArgs() {
err := t.matcher.Matches(func(i int) string { return "" })
ExpectThat(err, Error(Equals("which is not a zero-arg function")))
ExpectTrue(isFatal(err))
}
func (t *PanicsTest) CallsFunction() {
callCount := 0
t.matcher.Matches(func() string {
callCount++
return ""
})
ExpectThat(callCount, Equals(1))
}
func (t *PanicsTest) FunctionDoesntPanic() {
err := t.matcher.Matches(func() {})
ExpectThat(err, Error(Equals("which didn't panic")))
ExpectFalse(isFatal(err))
}
func (t *PanicsTest) CallsWrappedMatcher() {
expectedErr := 17
t.wrappedError = errors.New("")
t.matcher.Matches(func() { panic(expectedErr) })
ExpectThat(t.suppliedCandidate, Equals(expectedErr))
}
func (t *PanicsTest) WrappedReturnsTrue() {
err := t.matcher.Matches(func() { panic("") })
ExpectEq(nil, err)
}
func (t *PanicsTest) WrappedReturnsFatalErrorWithoutText() {
t.wrappedError = NewFatalError("")
err := t.matcher.Matches(func() { panic(17) })
ExpectThat(err, Error(Equals("which panicked with: 17")))
ExpectFalse(isFatal(err))
}
func (t *PanicsTest) WrappedReturnsFatalErrorWithText() {
t.wrappedError = NewFatalError("which blah")
err := t.matcher.Matches(func() { panic(17) })
ExpectThat(err, Error(Equals("which panicked with: 17, which blah")))
ExpectFalse(isFatal(err))
}
func (t *PanicsTest) WrappedReturnsNonFatalErrorWithoutText() {
t.wrappedError = errors.New("")
err := t.matcher.Matches(func() { panic(17) })
ExpectThat(err, Error(Equals("which panicked with: 17")))
ExpectFalse(isFatal(err))
}
func (t *PanicsTest) WrappedReturnsNonFatalErrorWithText() {
t.wrappedError = errors.New("which blah")
err := t.matcher.Matches(func() { panic(17) })
ExpectThat(err, Error(Equals("which panicked with: 17, which blah")))
ExpectFalse(isFatal(err))
}

View File

@ -1,153 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglematchers_test
import (
"errors"
"testing"
. "github.com/smartystreets/goconvey/convey/assertions/oglematchers"
. "github.com/smartystreets/goconvey/convey/assertions/ogletest"
)
////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////
type PointeeTest struct{}
func init() { RegisterTestSuite(&PointeeTest{}) }
func TestPointee(t *testing.T) { RunTests(t) }
////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////
func (t *PointeeTest) Description() {
wrapped := &fakeMatcher{nil, "taco"}
matcher := Pointee(wrapped)
ExpectEq("pointee(taco)", matcher.Description())
}
func (t *PointeeTest) CandidateIsNotAPointer() {
matcher := Pointee(HasSubstr(""))
err := matcher.Matches([]byte{})
ExpectThat(err, Error(Equals("which is not a pointer")))
ExpectTrue(isFatal(err))
}
func (t *PointeeTest) CandidateIsANilLiteral() {
matcher := Pointee(HasSubstr(""))
err := matcher.Matches(nil)
ExpectThat(err, Error(Equals("which is not a pointer")))
ExpectTrue(isFatal(err))
}
func (t *PointeeTest) CandidateIsANilPointer() {
matcher := Pointee(HasSubstr(""))
err := matcher.Matches((*int)(nil))
ExpectThat(err, Error(Equals("")))
ExpectTrue(isFatal(err))
}
func (t *PointeeTest) CallsWrapped() {
var suppliedCandidate interface{}
matchFunc := func(c interface{}) error {
suppliedCandidate = c
return nil
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
someSlice := []byte{}
matcher.Matches(&someSlice)
ExpectThat(suppliedCandidate, IdenticalTo(someSlice))
}
func (t *PointeeTest) WrappedReturnsOkay() {
matchFunc := func(c interface{}) error {
return nil
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
err := matcher.Matches(new(int))
ExpectEq(nil, err)
}
func (t *PointeeTest) WrappedReturnsNonFatalNonEmptyError() {
matchFunc := func(c interface{}) error {
return errors.New("taco")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
i := 17
err := matcher.Matches(&i)
ExpectFalse(isFatal(err))
ExpectThat(err, Error(Equals("taco")))
}
func (t *PointeeTest) WrappedReturnsNonFatalEmptyError() {
matchFunc := func(c interface{}) error {
return errors.New("")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
i := 17
err := matcher.Matches(&i)
ExpectFalse(isFatal(err))
ExpectThat(err, Error(HasSubstr("whose pointee")))
ExpectThat(err, Error(HasSubstr("17")))
}
func (t *PointeeTest) WrappedReturnsFatalNonEmptyError() {
matchFunc := func(c interface{}) error {
return NewFatalError("taco")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
i := 17
err := matcher.Matches(&i)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(Equals("taco")))
}
func (t *PointeeTest) WrappedReturnsFatalEmptyError() {
matchFunc := func(c interface{}) error {
return NewFatalError("")
}
wrapped := &fakeMatcher{matchFunc, ""}
matcher := Pointee(wrapped)
i := 17
err := matcher.Matches(&i)
ExpectTrue(isFatal(err))
ExpectThat(err, Error(HasSubstr("whose pointee")))
ExpectThat(err, Error(HasSubstr("17")))
}

View File

@ -1,5 +0,0 @@
*.6
6.out
_obj/
_test/
_testmain.go

View File

@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,101 +0,0 @@
`oglemock` is a mocking framework for the Go programming language with the
following features:
* An extensive and extensible set of matchers for expressing call
expectations (provided by the [oglematchers][] package).
* Clean, readable output that tells you exactly what you need to know.
* Style and semantics similar to [Google Mock][googlemock] and
[Google JS Test][google-js-test].
* Seamless integration with the [ogletest][] unit testing framework.
It can be integrated into any testing framework (including Go's `testing`
package), but out of the box support is built in to [ogletest][] and that is the
easiest place to use it.
Installation
------------
First, make sure you have installed Go 1.0.2 or newer. See
[here][golang-install] for instructions.
Use the following command to install `oglemock` and its dependencies, and to
keep them up to date:
go get -u github.com/smartystreets/goconvey/convey/assertions/oglemock
go get -u github.com/smartystreets/goconvey/convey/assertions/oglemock/createmock
Those commands will install the `oglemock` package itself, along with the
`createmock` tool that is used to auto-generate mock types.
Generating and using mock types
-------------------------------
Automatically generating a mock implementation of an interface is easy. If you
want to mock interfaces `Bar` and `Baz` from package `foo`, simply run the
following:
createmock foo Bar Baz
That will print source code that can be saved to a file and used in your tests.
For example, to create a `mock_io` package containing mock implementations of
`io.Reader` and `io.Writer`:
mkdir mock_io
createmock io Reader Writer > mock_io/mock_io.go
The new package will be named `mock_io`, and contain types called `MockReader`
and `MockWriter`, which implement `io.Reader` and `io.Writer` respectively.
For each generated mock type, there is a corresponding function for creating an
instance of that type given a `Controller` object (see below). For example, to
create a mock reader:
```go
someController := [...] // See next section.
someReader := mock_io.NewMockReader(someController, "Mock file reader")
```
The snippet above creates a mock `io.Reader` that reports failures to
`someController`. The reader can subsequently have expectations set up and be
passed to your code under test that uses an `io.Reader`.
Getting ahold of a controller
-----------------------------
[oglemock.Controller][controller-ref] is used to create mock objects, and to set
up and verify expectations for them. You can create one by calling
`NewController` with an `ErrorReporter`, which is the basic type used to
interface between `oglemock` and the testing framework within which it is being
used.
If you are using [ogletest][] you don't need to worry about any of this, since
the `TestInfo` struct provided to your test's `SetUp` function already contains
a working `Controller` that you can use to create mock object, and you can use
the built-in `ExpectCall` function for setting expectations. (See the
[ogletest documentation][ogletest-docs] for more info.) Otherwise, you will need
to implement the simple [ErrorReporter interface][reporter-ref] for your test
environment.
Documentation
-------------
For thorough documentation, including information on how to set up expectations,
see [here][oglemock-docs].
[controller-ref]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/goconvey/convey/assertions/oglemock#Controller
[reporter-ref]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/goconvey/convey/assertions/oglemock#ErrorReporter
[golang-install]: http://golang.org/doc/install.html
[google-js-test]: http://code.google.com/p/google-js-test/
[googlemock]: http://code.google.com/p/googlemock/
[oglematchers]: https://github.com/smartystreets/goconvey/convey/assertions/oglematchers
[oglemock-docs]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/goconvey/convey/assertions/oglemock
[ogletest]: https://github.com/smartystreets/goconvey/convey/assertions/oglematchers
[ogletest-docs]: http://gopkgdoc.appspot.com/pkg/github.com/smartystreets/goconvey/convey/assertions/ogletest

View File

@ -1,36 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
import (
"reflect"
)
// Action represents an action to be taken in response to a call to a mock
// method.
type Action interface {
// Set the signature of the function with which this action is being used.
// This must be called before Invoke is called.
SetSignature(signature reflect.Type) error
// Invoke runs the specified action, given the arguments to the mock method.
// It returns zero or more values that may be treated as the return values of
// the method. If the action doesn't return any values, it may return the nil
// slice.
//
// You must call SetSignature before calling Invoke.
Invoke(methodArgs []interface{}) []interface{}
}

View File

@ -1,480 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
import (
"errors"
"fmt"
"log"
"math"
"reflect"
"sync"
)
// PartialExpecation is a function that should be called exactly once with
// expected arguments or matchers in order to set up an expected method call.
// See Controller.ExpectMethodCall below. It returns an expectation that can be
// further modified (e.g. by calling WillOnce).
//
// If the arguments are of the wrong type, the function reports a fatal error
// and returns nil.
type PartialExpecation func(...interface{}) Expectation
// Controller represents an object that implements the central logic of
// oglemock: recording and verifying expectations, responding to mock method
// calls, and so on.
type Controller interface {
// ExpectCall expresses an expectation that the method of the given name
// should be called on the supplied mock object. It returns a function that
// should be called with the expected arguments, matchers for the arguments,
// or a mix of both.
//
// fileName and lineNumber should indicate the line on which the expectation
// was made, if known.
//
// For example:
//
// mockWriter := [...]
// controller.ExpectCall(mockWriter, "Write", "foo.go", 17)(ElementsAre(0x1))
// .WillOnce(Return(1, nil))
//
// If the mock object doesn't have a method of the supplied name, the
// function reports a fatal error and returns nil.
ExpectCall(
o MockObject,
methodName string,
fileName string,
lineNumber int) PartialExpecation
// Finish causes the controller to check for any unsatisfied expectations,
// and report them as errors if they exist.
//
// The controller may panic if any of its methods (including this one) are
// called after Finish is called.
Finish()
// HandleMethodCall looks for a registered expectation matching the call of
// the given method on mock object o, invokes the appropriate action (if
// any), and returns the values returned by that action (if any).
//
// If the action returns nothing, the controller returns zero values. If
// there is no matching expectation, the controller reports an error and
// returns zero values.
//
// If the mock object doesn't have a method of the supplied name, the
// arguments are of the wrong type, or the action returns the wrong types,
// the function reports a fatal error.
//
// HandleMethodCall is exported for the sake of mock implementations, and
// should not be used directly.
HandleMethodCall(
o MockObject,
methodName string,
fileName string,
lineNumber int,
args []interface{}) []interface{}
}
// methodMap represents a map from method name to set of expectations for that
// method.
type methodMap map[string][]*InternalExpectation
// objectMap represents a map from mock object ID to a methodMap for that object.
type objectMap map[uintptr]methodMap
// NewController sets up a fresh controller, without any expectations set, and
// configures the controller to use the supplied error reporter.
func NewController(reporter ErrorReporter) Controller {
return &controllerImpl{reporter, sync.RWMutex{}, objectMap{}}
}
type controllerImpl struct {
reporter ErrorReporter
mutex sync.RWMutex
expectationsByObject objectMap // Protected by mutex
}
// Return the list of registered expectations for the named method of the
// supplied object, or an empty slice if none have been registered. When this
// method returns, it is guaranteed that c.expectationsByObject has an entry
// for the object.
//
// c.mutex must be held for reading.
func (c *controllerImpl) getExpectationsLocked(
o MockObject,
methodName string) []*InternalExpectation {
id := o.Oglemock_Id()
// Look up the mock object.
expectationsByMethod, ok := c.expectationsByObject[id]
if !ok {
expectationsByMethod = methodMap{}
c.expectationsByObject[id] = expectationsByMethod
}
result, ok := expectationsByMethod[methodName]
if !ok {
return []*InternalExpectation{}
}
return result
}
// Add an expectation to the list registered for the named method of the
// supplied mock object.
//
// c.mutex must be held for writing.
func (c *controllerImpl) addExpectationLocked(
o MockObject,
methodName string,
exp *InternalExpectation) {
// Get the existing list.
existing := c.getExpectationsLocked(o, methodName)
// Store a modified list.
id := o.Oglemock_Id()
c.expectationsByObject[id][methodName] = append(existing, exp)
}
func (c *controllerImpl) ExpectCall(
o MockObject,
methodName string,
fileName string,
lineNumber int) PartialExpecation {
// Find the signature for the requested method.
ov := reflect.ValueOf(o)
method := ov.MethodByName(methodName)
if method.Kind() == reflect.Invalid {
c.reporter.ReportFatalError(
fileName,
lineNumber,
errors.New("Unknown method: "+methodName))
return nil
}
partialAlreadyCalled := false // Protected by c.mutex
return func(args ...interface{}) Expectation {
c.mutex.Lock()
defer c.mutex.Unlock()
// This function should only be called once.
if partialAlreadyCalled {
c.reporter.ReportFatalError(
fileName,
lineNumber,
errors.New("Partial expectation called more than once."))
return nil
}
partialAlreadyCalled = true
// Make sure that the number of args is legal. Keep in mind that the
// method's type has an extra receiver arg.
if len(args) != method.Type().NumIn() {
c.reporter.ReportFatalError(
fileName,
lineNumber,
errors.New(
fmt.Sprintf(
"Expectation for %s given wrong number of arguments: "+
"expected %d, got %d.",
methodName,
method.Type().NumIn(),
len(args))))
return nil
}
// Create an expectation and insert it into the controller's map.
exp := InternalNewExpectation(
c.reporter,
method.Type(),
args,
fileName,
lineNumber)
c.addExpectationLocked(o, methodName, exp)
// Return the expectation to the user.
return exp
}
}
func (c *controllerImpl) Finish() {
c.mutex.Lock()
defer c.mutex.Unlock()
// Check whether the minimum cardinality for each registered expectation has
// been satisfied.
for _, expectationsByMethod := range c.expectationsByObject {
for methodName, expectations := range expectationsByMethod {
for _, exp := range expectations {
exp.mutex.Lock()
defer exp.mutex.Unlock()
minCardinality, _ := computeCardinalityLocked(exp)
if exp.NumMatches < minCardinality {
c.reporter.ReportError(
exp.FileName,
exp.LineNumber,
errors.New(
fmt.Sprintf(
"Unsatisfied expectation; expected %s to be called "+
"at least %d times; called %d times.",
methodName,
minCardinality,
exp.NumMatches)))
}
}
}
}
}
// expectationMatches checks the matchers for the expectation against the
// supplied arguments.
func expectationMatches(exp *InternalExpectation, args []interface{}) bool {
matchers := exp.ArgMatchers
if len(args) != len(matchers) {
panic("expectationMatches: len(args)")
}
// Check each matcher.
for i, matcher := range matchers {
if err := matcher.Matches(args[i]); err != nil {
return false
}
}
return true
}
// Return the expectation that matches the supplied arguments. If there is more
// than one such expectation, the one furthest along in the list for the method
// is returned. If there is no such expectation, nil is returned.
//
// c.mutex must be held for reading.
func (c *controllerImpl) chooseExpectationLocked(
o MockObject,
methodName string,
args []interface{}) *InternalExpectation {
// Do we have any expectations for this method?
expectations := c.getExpectationsLocked(o, methodName)
if len(expectations) == 0 {
return nil
}
for i := len(expectations) - 1; i >= 0; i-- {
if expectationMatches(expectations[i], args) {
return expectations[i]
}
}
return nil
}
// makeZeroReturnValues creates a []interface{} containing appropriate zero
// values for returning from the supplied method type.
func makeZeroReturnValues(signature reflect.Type) []interface{} {
result := make([]interface{}, signature.NumOut())
for i, _ := range result {
outType := signature.Out(i)
zeroVal := reflect.Zero(outType)
result[i] = zeroVal.Interface()
}
return result
}
// computeCardinality decides on the [min, max] range of the number of expected
// matches for the supplied expectations, according to the rules documented in
// expectation.go.
//
// exp.mutex must be held for reading.
func computeCardinalityLocked(exp *InternalExpectation) (min, max uint) {
// Explicit cardinality.
if exp.ExpectedNumMatches >= 0 {
min = uint(exp.ExpectedNumMatches)
max = min
return
}
// Implicit count based on one-time actions.
if len(exp.OneTimeActions) != 0 {
min = uint(len(exp.OneTimeActions))
max = min
// If there is a fallback action, this is only a lower bound.
if exp.FallbackAction != nil {
max = math.MaxUint32
}
return
}
// Implicit lack of restriction based on a fallback action being configured.
if exp.FallbackAction != nil {
min = 0
max = math.MaxUint32
return
}
// Implicit cardinality of one.
min = 1
max = 1
return
}
// chooseAction returns the action that should be invoked for the i'th match to
// the supplied expectation (counting from zero). If the implicit "return zero
// values" action should be used, it returns nil.
//
// exp.mutex must be held for reading.
func chooseActionLocked(i uint, exp *InternalExpectation) Action {
// Exhaust one-time actions first.
if i < uint(len(exp.OneTimeActions)) {
return exp.OneTimeActions[i]
}
// Fallback action (or nil if none is configured).
return exp.FallbackAction
}
// Find an action for the method call, updating expectation match state in the
// process. Return either an action that should be invoked or a set of zero
// values to return immediately.
//
// This is split out from HandleMethodCall in order to more easily avoid
// invoking the action with locks held.
func (c *controllerImpl) chooseActionAndUpdateExpectations(
o MockObject,
methodName string,
fileName string,
lineNumber int,
args []interface{},
) (action Action, zeroVals []interface{}) {
c.mutex.Lock()
defer c.mutex.Unlock()
// Find the signature for the requested method.
ov := reflect.ValueOf(o)
method := ov.MethodByName(methodName)
if method.Kind() == reflect.Invalid {
c.reporter.ReportFatalError(
fileName,
lineNumber,
errors.New("Unknown method: "+methodName),
)
// Should never get here in real code.
log.Println("ReportFatalError unexpectedly returned.")
return
}
// HACK(jacobsa): Make sure we got the correct number of arguments. This will
// need to be refined when issue #5 (variadic methods) is handled.
if len(args) != method.Type().NumIn() {
c.reporter.ReportFatalError(
fileName,
lineNumber,
errors.New(
fmt.Sprintf(
"Wrong number of arguments: expected %d; got %d",
method.Type().NumIn(),
len(args),
),
),
)
// Should never get here in real code.
log.Println("ReportFatalError unexpectedly returned.")
return
}
// Find an expectation matching this call.
expectation := c.chooseExpectationLocked(o, methodName, args)
if expectation == nil {
c.reporter.ReportError(
fileName,
lineNumber,
errors.New(
fmt.Sprintf("Unexpected call to %s with args: %v", methodName, args),
),
)
zeroVals = makeZeroReturnValues(method.Type())
return
}
expectation.mutex.Lock()
defer expectation.mutex.Unlock()
// Increase the number of matches recorded, and check whether we're over the
// number expected.
expectation.NumMatches++
_, maxCardinality := computeCardinalityLocked(expectation)
if expectation.NumMatches > maxCardinality {
c.reporter.ReportError(
expectation.FileName,
expectation.LineNumber,
errors.New(
fmt.Sprintf(
"Unexpected call to %s: "+
"expected to be called at most %d times; called %d times.",
methodName,
maxCardinality,
expectation.NumMatches,
),
),
)
zeroVals = makeZeroReturnValues(method.Type())
return
}
// Choose an action to invoke. If there is none, just return zero values.
action = chooseActionLocked(expectation.NumMatches-1, expectation)
if action == nil {
zeroVals = makeZeroReturnValues(method.Type())
return
}
// Let the action take over.
return
}
func (c *controllerImpl) HandleMethodCall(
o MockObject,
methodName string,
fileName string,
lineNumber int,
args []interface{},
) []interface{} {
// Figure out whether to invoke an action or return zero values.
action, zeroVals := c.chooseActionAndUpdateExpectations(
o,
methodName,
fileName,
lineNumber,
args,
)
if action != nil {
return action.Invoke(args)
}
return zeroVals
}

View File

@ -1,226 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// createmock is used to generate source code for mock versions of interfaces
// from installed packages.
package main
import (
"errors"
"flag"
"fmt"
"go/build"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"regexp"
"text/template"
// Ensure that the generate package, which is used by the generated code, is
// installed by goinstall.
_ "github.com/smartystreets/goconvey/convey/assertions/oglemock/generate"
)
// A template for generated code that is used to print the result.
const tmplStr = `
{{$inputPkg := .InputPkg}}
{{$outputPkg := .OutputPkg}}
package main
import (
{{range $identifier, $import := .Imports}}
{{$identifier}} "{{$import}}"
{{end}}
)
func getTypeForPtr(ptr interface{}) reflect.Type {
return reflect.TypeOf(ptr).Elem()
}
func main() {
// Reduce noise in logging output.
log.SetFlags(0)
interfaces := []reflect.Type{
{{range $typeName := .TypeNames}}
getTypeForPtr((*{{base $inputPkg}}.{{$typeName}})(nil)),
{{end}}
}
err := generate.GenerateMockSource(os.Stdout, "{{$outputPkg}}", interfaces)
if err != nil {
log.Fatalf("Error generating mock source: %v", err)
}
}
`
// A map from import identifier to package to use that identifier for,
// containing elements for each import needed by the generated code.
type importMap map[string]string
type tmplArg struct {
InputPkg string
OutputPkg string
// Imports needed by the generated code.
Imports importMap
// Types to be mocked, relative to their package's name.
TypeNames []string
}
var unknownPackageRegexp = regexp.MustCompile(
`tool\.go:\d+:\d+: cannot find package "([^"]+)"`)
var undefinedInterfaceRegexp = regexp.MustCompile(`tool\.go:\d+: undefined: [\pL_0-9]+\.([\pL_0-9]+)`)
// Does the 'go build' output indicate that a package wasn't found? If so,
// return the name of the package.
func findUnknownPackage(output []byte) *string {
if match := unknownPackageRegexp.FindSubmatch(output); match != nil {
res := string(match[1])
return &res
}
return nil
}
// Does the 'go build' output indicate that an interface wasn't found? If so,
// return the name of the interface.
func findUndefinedInterface(output []byte) *string {
if match := undefinedInterfaceRegexp.FindSubmatch(output); match != nil {
res := string(match[1])
return &res
}
return nil
}
// Split out from main so that deferred calls are executed even in the event of
// an error.
func run() error {
// Reduce noise in logging output.
log.SetFlags(0)
// Check the command-line arguments.
flag.Parse()
cmdLineArgs := flag.Args()
if len(cmdLineArgs) < 2 {
return errors.New("Usage: createmock [package] [interface ...]")
}
// Create a temporary directory inside of $GOPATH to hold generated code.
buildPkg, err := build.Import("github.com/smartystreets/goconvey/convey/assertions/oglemock", "", build.FindOnly)
if err != nil {
return errors.New(fmt.Sprintf("Couldn't find oglemock in $GOPATH: %v", err))
}
tmpDir, err := ioutil.TempDir(buildPkg.SrcRoot, "tmp-createmock-")
if err != nil {
return errors.New(fmt.Sprintf("Creating temp dir: %v", err))
}
defer os.RemoveAll(tmpDir)
// Create a file to hold generated code.
codeFile, err := os.Create(path.Join(tmpDir, "tool.go"))
if err != nil {
return errors.New(fmt.Sprintf("Couldn't create a file to hold code: %v", err))
}
// Create an appropriate path for the built binary.
binaryPath := path.Join(tmpDir, "tool")
// Create an appropriate template argument.
var arg tmplArg
arg.InputPkg = cmdLineArgs[0]
arg.OutputPkg = "mock_" + path.Base(arg.InputPkg)
arg.TypeNames = cmdLineArgs[1:]
arg.Imports = make(importMap)
arg.Imports[path.Base(arg.InputPkg)] = arg.InputPkg
arg.Imports["generate"] = "github.com/smartystreets/goconvey/convey/assertions/oglemock/generate"
arg.Imports["log"] = "log"
arg.Imports["os"] = "os"
arg.Imports["reflect"] = "reflect"
// Execute the template to generate code that will itself generate the mock
// code. Write the code to the temp file.
tmpl := template.Must(
template.New("code").Funcs(
template.FuncMap{
"base": path.Base,
}).Parse(tmplStr))
if err := tmpl.Execute(codeFile, arg); err != nil {
return errors.New(fmt.Sprintf("Error executing template: %v", err))
}
codeFile.Close()
// Attempt to build the code.
cmd := exec.Command("go", "build", "-o", binaryPath)
cmd.Dir = tmpDir
buildOutput, err := cmd.CombinedOutput()
if err != nil {
// Did the compilation fail due to the user-specified package not being found?
if pkg := findUnknownPackage(buildOutput); pkg != nil && *pkg == arg.InputPkg {
return errors.New(fmt.Sprintf("Unknown package: %s", *pkg))
}
// Did the compilation fail due to an unknown interface?
if in := findUndefinedInterface(buildOutput); in != nil {
return errors.New(fmt.Sprintf("Unknown interface: %s", *in))
}
// Otherwise return a generic error.
return errors.New(fmt.Sprintf(
"%s\n\nError building generated code:\n\n"+
" %v\n\nPlease report this oglemock bug.",
buildOutput,
err))
}
// Run the binary.
cmd = exec.Command(binaryPath)
binaryOutput, err := cmd.CombinedOutput()
if err != nil {
return errors.New(fmt.Sprintf(
"%s\n\nError running generated code:\n\n"+
" %v\n\n Please report this oglemock bug.",
binaryOutput,
err))
}
// Copy its output.
_, err = os.Stdout.Write(binaryOutput)
if err != nil {
return errors.New(fmt.Sprintf("Error copying binary output: %v", err))
}
return nil
}
func main() {
if err := run(); err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
}

View File

@ -1 +0,0 @@
Usage: createmock [package] [interface ...]

View File

@ -1 +0,0 @@
Usage: createmock [package] [interface ...]

View File

@ -1,29 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
// ErrorReporter is an interface that wraps methods for reporting errors that
// should cause test failures.
type ErrorReporter interface {
// Report that some failure (e.g. an unsatisfied expectation) occurred. If
// known, fileName and lineNumber should contain information about where it
// occurred. The test may continue if the test framework supports it.
ReportError(fileName string, lineNumber int, err error)
// Like ReportError, but the test should be halted immediately. It is assumed
// that this method does not return.
ReportFatalError(fileName string, lineNumber int, err error)
}

View File

@ -1,59 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
// Expectation is an expectation for zero or more calls to a mock method with
// particular arguments or sets of arguments.
type Expectation interface {
// Times expresses that a matching method call should happen exactly N times.
// Times must not be called more than once, and must not be called after
// WillOnce or WillRepeatedly.
//
// The full rules for the cardinality of an expectation are as follows:
//
// 1. If an explicit cardinality is set with Times(N), then anything other
// than exactly N matching calls will cause a test failure.
//
// 2. Otherwise, if there are any one-time actions set up, then it is
// expected there will be at least that many matching calls. If there is
// not also a fallback action, then it is expected that there will be
// exactly that many.
//
// 3. Otherwise, if there is a fallback action configured, any number of
// matching calls (including zero) is allowed.
//
// 4. Otherwise, the implicit cardinality is one.
//
Times(n uint) Expectation
// WillOnce configures a "one-time action". WillOnce can be called zero or
// more times, but must be called after any call to Times and before any call
// to WillRepeatedly.
//
// When matching method calls are made on the mock object, one-time actions
// are invoked one per matching call in the order that they were set up until
// they are exhausted. Afterward the fallback action, if any, will be used.
WillOnce(a Action) Expectation
// WillRepeatedly configures a "fallback action". WillRepeatedly can be
// called zero or one times, and must not be called before Times or WillOnce.
//
// Once all one-time actions are exhausted (see above), the fallback action
// will be invoked for any further method calls. If WillRepeatedly is not
// called, the fallback action is implicitly an action that returns zero
// values for the method's return values.
WillRepeatedly(a Action) Expectation
}

View File

@ -1,329 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package generate implements code generation for mock classes. This is an
// implementation detail of the createmock command, which you probably want to
// use directly instead.
package generate
import (
"bytes"
"errors"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"reflect"
"regexp"
"text/template"
)
const tmplStr = `
// This file was auto-generated using createmock. See the following page for
// more information:
//
// https://github.com/smartystreets/goconvey/convey/assertions/oglemock
//
package {{.Pkg}}
import (
{{range $identifier, $import := .Imports}}{{$identifier}} "{{$import}}"
{{end}}
)
{{range .Interfaces}}
{{$interfaceName := printf "Mock%s" .Name}}
{{$structName := printf "mock%s" .Name}}
type {{$interfaceName}} interface {
{{getTypeString .}}
oglemock.MockObject
}
type {{$structName}} struct {
controller oglemock.Controller
description string
}
func New{{printf "Mock%s" .Name}}(
c oglemock.Controller,
desc string) {{$interfaceName}} {
return &{{$structName}}{
controller: c,
description: desc,
}
}
func (m *{{$structName}}) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *{{$structName}}) Oglemock_Description() string {
return m.description
}
{{range getMethods .}}
{{$funcType := .Type}}
{{$inputTypes := getInputs $funcType}}
{{$outputTypes := getOutputs $funcType}}
func (m *{{$structName}}) {{.Name}}({{range $i, $type := $inputTypes}}p{{$i}} {{getInputTypeString $i $funcType}}, {{end}}) ({{range $i, $type := $outputTypes}}o{{$i}} {{getTypeString $type}}, {{end}}) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"{{.Name}}",
file,
line,
[]interface{}{ {{range $i, $type := $inputTypes}}p{{$i}}, {{end}} })
if len(retVals) != {{len $outputTypes}} {
panic(fmt.Sprintf("{{$structName}}.{{.Name}}: invalid return values: %v", retVals))
}
{{range $i, $type := $outputTypes}}
// o{{$i}} {{getTypeString $type}}
if retVals[{{$i}}] != nil {
o{{$i}} = retVals[{{$i}}].({{getTypeString $type}})
}
{{end}}
return
}
{{end}}
{{end}}
`
type tmplArg struct {
// The package of the generated code.
Pkg string
// Imports needed by the interfaces.
Imports importMap
// The set of interfaces to mock.
Interfaces []reflect.Type
}
var tmpl *template.Template
func init() {
extraFuncs := make(template.FuncMap)
extraFuncs["getMethods"] = getMethods
extraFuncs["getInputs"] = getInputs
extraFuncs["getOutputs"] = getOutputs
extraFuncs["getInputTypeString"] = getInputTypeString
extraFuncs["getTypeString"] = getTypeString
tmpl = template.New("code")
tmpl.Funcs(extraFuncs)
tmpl.Parse(tmplStr)
}
func getInputTypeString(i int, ft reflect.Type) string {
numInputs := ft.NumIn()
if i == numInputs-1 && ft.IsVariadic() {
return "..." + getTypeString(ft.In(i).Elem())
}
return getTypeString(ft.In(i))
}
func getTypeString(t reflect.Type) string {
return t.String()
}
func getMethods(it reflect.Type) []reflect.Method {
numMethods := it.NumMethod()
methods := make([]reflect.Method, numMethods)
for i := 0; i < numMethods; i++ {
methods[i] = it.Method(i)
}
return methods
}
func getInputs(ft reflect.Type) []reflect.Type {
numIn := ft.NumIn()
inputs := make([]reflect.Type, numIn)
for i := 0; i < numIn; i++ {
inputs[i] = ft.In(i)
}
return inputs
}
func getOutputs(ft reflect.Type) []reflect.Type {
numOut := ft.NumOut()
outputs := make([]reflect.Type, numOut)
for i := 0; i < numOut; i++ {
outputs[i] = ft.Out(i)
}
return outputs
}
// A map from import identifier to package to use that identifier for,
// containing elements for each import needed by a set of mocked interfaces.
type importMap map[string]string
var typePackageIdentifierRegexp = regexp.MustCompile(`^([\pL_0-9]+)\.[\pL_0-9]+$`)
// Add an import for the supplied type, without recursing.
func addImportForType(imports importMap, t reflect.Type) {
// If there is no package path, this is a built-in type and we don't need an
// import.
pkgPath := t.PkgPath()
if pkgPath == "" {
return
}
// Work around a bug in Go:
//
// http://code.google.com/p/go/issues/detail?id=2660
//
var errorPtr *error
if t == reflect.TypeOf(errorPtr).Elem() {
return
}
// Use the identifier that's part of the type's string representation as the
// import identifier. This means that we'll do the right thing for package
// "foo/bar" with declaration "package baz".
match := typePackageIdentifierRegexp.FindStringSubmatch(t.String())
if match == nil {
return
}
imports[match[1]] = pkgPath
}
// Add all necessary imports for the type, recursing as appropriate.
func addImportsForType(imports importMap, t reflect.Type) {
// Add any import needed for the type itself.
addImportForType(imports, t)
// Handle special cases where recursion is needed.
switch t.Kind() {
case reflect.Array, reflect.Chan, reflect.Ptr, reflect.Slice:
addImportsForType(imports, t.Elem())
case reflect.Func:
// Input parameters.
for i := 0; i < t.NumIn(); i++ {
addImportsForType(imports, t.In(i))
}
// Return values.
for i := 0; i < t.NumOut(); i++ {
addImportsForType(imports, t.Out(i))
}
case reflect.Map:
addImportsForType(imports, t.Key())
addImportsForType(imports, t.Elem())
}
}
// Add imports for each of the methods of the interface, but not the interface
// itself.
func addImportsForInterfaceMethods(imports importMap, it reflect.Type) {
// Handle each method.
for i := 0; i < it.NumMethod(); i++ {
m := it.Method(i)
addImportsForType(imports, m.Type)
}
}
// Given a set of interfaces, return a map from import identifier to package to
// use that identifier for, containing elements for each import needed by the
// mock versions of those interfaces.
func getImports(interfaces []reflect.Type) importMap {
imports := make(importMap)
for _, it := range interfaces {
addImportForType(imports, it)
addImportsForInterfaceMethods(imports, it)
}
// Make sure there are imports for other types used by the generated code
// itself.
imports["fmt"] = "fmt"
imports["oglemock"] = "github.com/smartystreets/goconvey/convey/assertions/oglemock"
imports["runtime"] = "runtime"
imports["unsafe"] = "unsafe"
return imports
}
// Given a set of interfaces to mock, write out source code for a package named
// `pkg` that contains mock implementations of those interfaces.
func GenerateMockSource(w io.Writer, pkg string, interfaces []reflect.Type) error {
// Sanity-check arguments.
if pkg == "" {
return errors.New("Package name must be non-empty.")
}
if len(interfaces) == 0 {
return errors.New("List of interfaces must be non-empty.")
}
// Make sure each type is indeed an interface.
for _, it := range interfaces {
if it.Kind() != reflect.Interface {
return errors.New("Invalid type: " + it.String())
}
}
// Create an appropriate template arg, then execute the template. Write the
// raw output into a buffer.
var arg tmplArg
arg.Pkg = pkg
arg.Imports = getImports(interfaces)
arg.Interfaces = interfaces
buf := new(bytes.Buffer)
if err := tmpl.Execute(buf, arg); err != nil {
return err
}
// Parse the output.
fset := token.NewFileSet()
astFile, err := parser.ParseFile(fset, pkg+".go", buf, parser.ParseComments)
if err != nil {
return errors.New("Error parsing generated code: " + err.Error())
}
// Sort the import lines in the AST in the same way that gofmt does.
ast.SortImports(fset, astFile)
// Pretty-print the AST, using the same options that gofmt does by default.
cfg := &printer.Config{
Mode: printer.UseSpaces | printer.TabIndent,
Tabwidth: 8,
}
if err = cfg.Fprint(w, fset, astFile); err != nil {
return errors.New("Error pretty printing: " + err.Error())
}
return nil
}

View File

@ -1,41 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package complicated_pkg contains an interface with lots of interesting
// cases, for use in integration testing.
package complicated_pkg
import (
"image"
"io"
"net"
"github.com/smartystreets/goconvey/convey/assertions/oglemock/generate/test_cases/renamed_pkg"
)
type Byte uint8
type ComplicatedThing interface {
Channels(a chan chan<- <-chan net.Conn) chan int
Pointers(a *int, b *net.Conn, c **io.Reader) (*int, error)
Functions(a func(int, image.Image) int) func(string, int) net.Conn
Maps(a map[string]*int) (map[int]*string, error)
Arrays(a [3]string) ([3]int, error)
Slices(a []string) ([]int, error)
NamedScalarType(a Byte) ([]Byte, error)
EmptyInterface(a interface{}) (interface{}, error)
RenamedPackage(a tony.SomeUint8Alias)
Variadic(a int, b ...net.Conn) int
}

View File

@ -1,312 +0,0 @@
// This file was auto-generated using createmock. See the following page for
// more information:
//
// https://github.com/smartystreets/goconvey/convey/assertions/oglemock
//
package some_pkg
import (
fmt "fmt"
image "image"
io "io"
net "net"
runtime "runtime"
unsafe "unsafe"
oglemock "github.com/smartystreets/goconvey/convey/assertions/oglemock"
complicated_pkg "github.com/smartystreets/goconvey/convey/assertions/oglemock/generate/test_cases/complicated_pkg"
tony "github.com/smartystreets/goconvey/convey/assertions/oglemock/generate/test_cases/renamed_pkg"
)
type MockComplicatedThing interface {
complicated_pkg.ComplicatedThing
oglemock.MockObject
}
type mockComplicatedThing struct {
controller oglemock.Controller
description string
}
func NewMockComplicatedThing(
c oglemock.Controller,
desc string) MockComplicatedThing {
return &mockComplicatedThing{
controller: c,
description: desc,
}
}
func (m *mockComplicatedThing) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockComplicatedThing) Oglemock_Description() string {
return m.description
}
func (m *mockComplicatedThing) Arrays(p0 [3]string) (o0 [3]int, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Arrays",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.Arrays: invalid return values: %v", retVals))
}
// o0 [3]int
if retVals[0] != nil {
o0 = retVals[0].([3]int)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) Channels(p0 chan chan<- <-chan net.Conn) (o0 chan int) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Channels",
file,
line,
[]interface{}{p0})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockComplicatedThing.Channels: invalid return values: %v", retVals))
}
// o0 chan int
if retVals[0] != nil {
o0 = retVals[0].(chan int)
}
return
}
func (m *mockComplicatedThing) EmptyInterface(p0 interface{}) (o0 interface{}, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"EmptyInterface",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.EmptyInterface: invalid return values: %v", retVals))
}
// o0 interface {}
if retVals[0] != nil {
o0 = retVals[0].(interface{})
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) Functions(p0 func(int, image.Image) int) (o0 func(string, int) net.Conn) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Functions",
file,
line,
[]interface{}{p0})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockComplicatedThing.Functions: invalid return values: %v", retVals))
}
// o0 func(string, int) net.Conn
if retVals[0] != nil {
o0 = retVals[0].(func(string, int) net.Conn)
}
return
}
func (m *mockComplicatedThing) Maps(p0 map[string]*int) (o0 map[int]*string, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Maps",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.Maps: invalid return values: %v", retVals))
}
// o0 map[int]*string
if retVals[0] != nil {
o0 = retVals[0].(map[int]*string)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) NamedScalarType(p0 complicated_pkg.Byte) (o0 []complicated_pkg.Byte, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"NamedScalarType",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.NamedScalarType: invalid return values: %v", retVals))
}
// o0 []complicated_pkg.Byte
if retVals[0] != nil {
o0 = retVals[0].([]complicated_pkg.Byte)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) Pointers(p0 *int, p1 *net.Conn, p2 **io.Reader) (o0 *int, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Pointers",
file,
line,
[]interface{}{p0, p1, p2})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.Pointers: invalid return values: %v", retVals))
}
// o0 *int
if retVals[0] != nil {
o0 = retVals[0].(*int)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) RenamedPackage(p0 tony.SomeUint8Alias) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"RenamedPackage",
file,
line,
[]interface{}{p0})
if len(retVals) != 0 {
panic(fmt.Sprintf("mockComplicatedThing.RenamedPackage: invalid return values: %v", retVals))
}
return
}
func (m *mockComplicatedThing) Slices(p0 []string) (o0 []int, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Slices",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockComplicatedThing.Slices: invalid return values: %v", retVals))
}
// o0 []int
if retVals[0] != nil {
o0 = retVals[0].([]int)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
func (m *mockComplicatedThing) Variadic(p0 int, p1 ...net.Conn) (o0 int) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Variadic",
file,
line,
[]interface{}{p0, p1})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockComplicatedThing.Variadic: invalid return values: %v", retVals))
}
// o0 int
if retVals[0] != nil {
o0 = retVals[0].(int)
}
return
}

View File

@ -1,239 +0,0 @@
// This file was auto-generated using createmock. See the following page for
// more information:
//
// https://github.com/smartystreets/goconvey/convey/assertions/oglemock
//
package some_pkg
import (
fmt "fmt"
image "image"
color "image/color"
runtime "runtime"
unsafe "unsafe"
oglemock "github.com/smartystreets/goconvey/convey/assertions/oglemock"
)
type MockImage interface {
image.Image
oglemock.MockObject
}
type mockImage struct {
controller oglemock.Controller
description string
}
func NewMockImage(
c oglemock.Controller,
desc string) MockImage {
return &mockImage{
controller: c,
description: desc,
}
}
func (m *mockImage) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockImage) Oglemock_Description() string {
return m.description
}
func (m *mockImage) At(p0 int, p1 int) (o0 color.Color) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"At",
file,
line,
[]interface{}{p0, p1})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockImage.At: invalid return values: %v", retVals))
}
// o0 color.Color
if retVals[0] != nil {
o0 = retVals[0].(color.Color)
}
return
}
func (m *mockImage) Bounds() (o0 image.Rectangle) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Bounds",
file,
line,
[]interface{}{})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockImage.Bounds: invalid return values: %v", retVals))
}
// o0 image.Rectangle
if retVals[0] != nil {
o0 = retVals[0].(image.Rectangle)
}
return
}
func (m *mockImage) ColorModel() (o0 color.Model) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"ColorModel",
file,
line,
[]interface{}{})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockImage.ColorModel: invalid return values: %v", retVals))
}
// o0 color.Model
if retVals[0] != nil {
o0 = retVals[0].(color.Model)
}
return
}
type MockPalettedImage interface {
image.PalettedImage
oglemock.MockObject
}
type mockPalettedImage struct {
controller oglemock.Controller
description string
}
func NewMockPalettedImage(
c oglemock.Controller,
desc string) MockPalettedImage {
return &mockPalettedImage{
controller: c,
description: desc,
}
}
func (m *mockPalettedImage) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockPalettedImage) Oglemock_Description() string {
return m.description
}
func (m *mockPalettedImage) At(p0 int, p1 int) (o0 color.Color) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"At",
file,
line,
[]interface{}{p0, p1})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockPalettedImage.At: invalid return values: %v", retVals))
}
// o0 color.Color
if retVals[0] != nil {
o0 = retVals[0].(color.Color)
}
return
}
func (m *mockPalettedImage) Bounds() (o0 image.Rectangle) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Bounds",
file,
line,
[]interface{}{})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockPalettedImage.Bounds: invalid return values: %v", retVals))
}
// o0 image.Rectangle
if retVals[0] != nil {
o0 = retVals[0].(image.Rectangle)
}
return
}
func (m *mockPalettedImage) ColorIndexAt(p0 int, p1 int) (o0 uint8) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"ColorIndexAt",
file,
line,
[]interface{}{p0, p1})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockPalettedImage.ColorIndexAt: invalid return values: %v", retVals))
}
// o0 uint8
if retVals[0] != nil {
o0 = retVals[0].(uint8)
}
return
}
func (m *mockPalettedImage) ColorModel() (o0 color.Model) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"ColorModel",
file,
line,
[]interface{}{})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockPalettedImage.ColorModel: invalid return values: %v", retVals))
}
// o0 color.Model
if retVals[0] != nil {
o0 = retVals[0].(color.Model)
}
return
}

View File

@ -1,128 +0,0 @@
// This file was auto-generated using createmock. See the following page for
// more information:
//
// https://github.com/smartystreets/goconvey/convey/assertions/oglemock
//
package some_pkg
import (
fmt "fmt"
io "io"
runtime "runtime"
unsafe "unsafe"
oglemock "github.com/smartystreets/goconvey/convey/assertions/oglemock"
)
type MockReader interface {
io.Reader
oglemock.MockObject
}
type mockReader struct {
controller oglemock.Controller
description string
}
func NewMockReader(
c oglemock.Controller,
desc string) MockReader {
return &mockReader{
controller: c,
description: desc,
}
}
func (m *mockReader) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockReader) Oglemock_Description() string {
return m.description
}
func (m *mockReader) Read(p0 []uint8) (o0 int, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Read",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockReader.Read: invalid return values: %v", retVals))
}
// o0 int
if retVals[0] != nil {
o0 = retVals[0].(int)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}
type MockWriter interface {
io.Writer
oglemock.MockObject
}
type mockWriter struct {
controller oglemock.Controller
description string
}
func NewMockWriter(
c oglemock.Controller,
desc string) MockWriter {
return &mockWriter{
controller: c,
description: desc,
}
}
func (m *mockWriter) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockWriter) Oglemock_Description() string {
return m.description
}
func (m *mockWriter) Write(p0 []uint8) (o0 int, o1 error) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"Write",
file,
line,
[]interface{}{p0})
if len(retVals) != 2 {
panic(fmt.Sprintf("mockWriter.Write: invalid return values: %v", retVals))
}
// o0 int
if retVals[0] != nil {
o0 = retVals[0].(int)
}
// o1 error
if retVals[1] != nil {
o1 = retVals[1].(error)
}
return
}

View File

@ -1,67 +0,0 @@
// This file was auto-generated using createmock. See the following page for
// more information:
//
// https://github.com/smartystreets/goconvey/convey/assertions/oglemock
//
package some_pkg
import (
fmt "fmt"
runtime "runtime"
unsafe "unsafe"
oglemock "github.com/smartystreets/goconvey/convey/assertions/oglemock"
tony "github.com/smartystreets/goconvey/convey/assertions/oglemock/generate/test_cases/renamed_pkg"
)
type MockSomeInterface interface {
tony.SomeInterface
oglemock.MockObject
}
type mockSomeInterface struct {
controller oglemock.Controller
description string
}
func NewMockSomeInterface(
c oglemock.Controller,
desc string) MockSomeInterface {
return &mockSomeInterface{
controller: c,
description: desc,
}
}
func (m *mockSomeInterface) Oglemock_Id() uintptr {
return uintptr(unsafe.Pointer(m))
}
func (m *mockSomeInterface) Oglemock_Description() string {
return m.description
}
func (m *mockSomeInterface) DoFoo(p0 int) (o0 int) {
// Get a file name and line number for the caller.
_, file, line, _ := runtime.Caller(1)
// Hand the call off to the controller, which does most of the work.
retVals := m.controller.HandleMethodCall(
m,
"DoFoo",
file,
line,
[]interface{}{p0})
if len(retVals) != 1 {
panic(fmt.Sprintf("mockSomeInterface.DoFoo: invalid return values: %v", retVals))
}
// o0 int
if retVals[0] != nil {
o0 = retVals[0].(int)
}
return
}

View File

@ -1,181 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
import (
"errors"
"fmt"
"reflect"
"sync"
"github.com/smartystreets/goconvey/convey/assertions/oglematchers"
)
// InternalExpectation is exported for purposes of testing only. You should not
// touch it.
//
// InternalExpectation represents an expectation for zero or more calls to a
// mock method, and a set of actions to be taken when those calls are received.
type InternalExpectation struct {
// The signature of the method to which this expectation is bound, for
// checking action types.
methodSignature reflect.Type
// An error reporter to use for reporting errors in the way that expectations
// are set.
errorReporter ErrorReporter
// A mutex protecting mutable fields of the struct.
mutex sync.Mutex
// Matchers that the arguments to the mock method must satisfy in order to
// match this expectation.
ArgMatchers []oglematchers.Matcher
// The name of the file in which this expectation was expressed.
FileName string
// The line number at which this expectation was expressed.
LineNumber int
// The number of times this expectation should be matched, as explicitly
// listed by the user. If there was no explicit number expressed, this is -1.
ExpectedNumMatches int
// Actions to be taken for the first N calls, one per call in order, where N
// is the length of this slice.
OneTimeActions []Action
// An action to be taken when the one-time actions have expired, or nil if
// there is no such action.
FallbackAction Action
// The number of times this expectation has been matched so far.
NumMatches uint
}
// InternalNewExpectation is exported for purposes of testing only. You should
// not touch it.
func InternalNewExpectation(
reporter ErrorReporter,
methodSignature reflect.Type,
args []interface{},
fileName string,
lineNumber int) *InternalExpectation {
result := &InternalExpectation{}
// Store fields that can be stored directly.
result.methodSignature = methodSignature
result.errorReporter = reporter
result.FileName = fileName
result.LineNumber = lineNumber
// Set up defaults.
result.ExpectedNumMatches = -1
result.OneTimeActions = make([]Action, 0)
// Set up the ArgMatchers slice, using Equals(x) for each x that is not a
// matcher itself.
result.ArgMatchers = make([]oglematchers.Matcher, len(args))
for i, x := range args {
if matcher, ok := x.(oglematchers.Matcher); ok {
result.ArgMatchers[i] = matcher
} else {
result.ArgMatchers[i] = oglematchers.Equals(x)
}
}
return result
}
func (e *InternalExpectation) Times(n uint) Expectation {
e.mutex.Lock()
defer e.mutex.Unlock()
// It is illegal to call this more than once.
if e.ExpectedNumMatches != -1 {
e.reportFatalError("Times called more than once.")
return nil
}
// It is illegal to call this after any actions are configured.
if len(e.OneTimeActions) != 0 {
e.reportFatalError("Times called after WillOnce.")
return nil
}
if e.FallbackAction != nil {
e.reportFatalError("Times called after WillRepeatedly.")
return nil
}
// Make sure the number is reasonable (and will fit in an int).
if n > 1000 {
e.reportFatalError("Expectation.Times: N must be at most 1000")
return nil
}
e.ExpectedNumMatches = int(n)
return e
}
func (e *InternalExpectation) WillOnce(a Action) Expectation {
e.mutex.Lock()
defer e.mutex.Unlock()
// It is illegal to call this after WillRepeatedly.
if e.FallbackAction != nil {
e.reportFatalError("WillOnce called after WillRepeatedly.")
return nil
}
// Tell the action about the method's signature.
if err := a.SetSignature(e.methodSignature); err != nil {
e.reportFatalError(fmt.Sprintf("WillOnce given invalid action: %v", err))
return nil
}
// Store the action.
e.OneTimeActions = append(e.OneTimeActions, a)
return e
}
func (e *InternalExpectation) WillRepeatedly(a Action) Expectation {
e.mutex.Lock()
defer e.mutex.Unlock()
// It is illegal to call this twice.
if e.FallbackAction != nil {
e.reportFatalError("WillRepeatedly called more than once.")
return nil
}
// Tell the action about the method's signature.
if err := a.SetSignature(e.methodSignature); err != nil {
e.reportFatalError(fmt.Sprintf("WillRepeatedly given invalid action: %v", err))
return nil
}
// Store the action.
e.FallbackAction = a
return e
}
func (e *InternalExpectation) reportFatalError(errorText string) {
e.errorReporter.ReportFatalError(e.FileName, e.LineNumber, errors.New(errorText))
}

View File

@ -1,73 +0,0 @@
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
import (
"errors"
"fmt"
"reflect"
)
// Create an Action that invokes the supplied function, returning whatever it
// returns. The signature of the function must match that of the mocked method
// exactly.
func Invoke(f interface{}) Action {
// Make sure f is a function.
fv := reflect.ValueOf(f)
fk := fv.Kind()
if fk != reflect.Func {
desc := "<nil>"
if fk != reflect.Invalid {
desc = fv.Type().String()
}
panic(fmt.Sprintf("Invoke: expected function, got %s", desc))
}
return &invokeAction{fv}
}
type invokeAction struct {
f reflect.Value
}
func (a *invokeAction) SetSignature(signature reflect.Type) error {
// The signature must match exactly.
ft := a.f.Type()
if ft != signature {
return errors.New(fmt.Sprintf("Invoke: expected %v, got %v", signature, ft))
}
return nil
}
func (a *invokeAction) Invoke(vals []interface{}) []interface{} {
// Create a slice of args for the function.
in := make([]reflect.Value, len(vals))
for i, x := range vals {
in[i] = reflect.ValueOf(x)
}
// Call the function and return its return values.
out := a.f.Call(in)
result := make([]interface{}, len(out))
for i, v := range out {
result[i] = v.Interface()
}
return result
}

View File

@ -1,30 +0,0 @@
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oglemock
// MockObject is an interface that mock object implementations must conform to
// in order to register expectations with and hand off calls to a
// MockController. Users should not interact with this interface directly.
type MockObject interface {
// Oglemock_Id returns an identifier for the mock object that is guaranteed
// to be unique within the process at least until the mock object is garbage
// collected.
Oglemock_Id() uintptr
// Oglemock_Description returns a description of the mock object that may be
// helpful in test failure messages.
Oglemock_Description() string
}

View File

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

Some files were not shown because too many files have changed in this diff Show More