mirror of
https://gitlab.com/ric_harvey/MailHog.git
synced 2024-11-27 16:24:04 +00:00
fix build issue
This commit is contained in:
parent
e36957a0db
commit
5c4899c652
112 changed files with 7060 additions and 7621 deletions
18
vendor/github.com/jtolds/gls/LICENSE
generated
vendored
Normal file
18
vendor/github.com/jtolds/gls/LICENSE
generated
vendored
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
Copyright (c) 2013, Space Monkey, Inc.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the "Software"), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||||
|
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||||
|
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||||
|
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||||
|
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
89
vendor/github.com/jtolds/gls/README.md
generated
vendored
Normal file
89
vendor/github.com/jtolds/gls/README.md
generated
vendored
Normal file
|
@ -0,0 +1,89 @@
|
||||||
|
gls
|
||||||
|
===
|
||||||
|
|
||||||
|
Goroutine local storage
|
||||||
|
|
||||||
|
### IMPORTANT NOTE ###
|
||||||
|
|
||||||
|
It is my duty to point you to https://blog.golang.org/context, which is how
|
||||||
|
Google solves all of the problems you'd perhaps consider using this package
|
||||||
|
for at scale.
|
||||||
|
|
||||||
|
One downside to Google's approach is that *all* of your functions must have
|
||||||
|
a new first argument, but after clearing that hurdle everything else is much
|
||||||
|
better.
|
||||||
|
|
||||||
|
If you aren't interested in this warning, read on.
|
||||||
|
|
||||||
|
### Huhwaht? Why? ###
|
||||||
|
|
||||||
|
Every so often, a thread shows up on the
|
||||||
|
[golang-nuts](https://groups.google.com/d/forum/golang-nuts) asking for some
|
||||||
|
form of goroutine-local-storage, or some kind of goroutine id, or some kind of
|
||||||
|
context. There are a few valid use cases for goroutine-local-storage, one of
|
||||||
|
the most prominent being log line context. One poster was interested in being
|
||||||
|
able to log an HTTP request context id in every log line in the same goroutine
|
||||||
|
as the incoming HTTP request, without having to change every library and
|
||||||
|
function call he was interested in logging.
|
||||||
|
|
||||||
|
This would be pretty useful. Provided that you could get some kind of
|
||||||
|
goroutine-local-storage, you could call
|
||||||
|
[log.SetOutput](http://golang.org/pkg/log/#SetOutput) with your own logging
|
||||||
|
writer that checks goroutine-local-storage for some context information and
|
||||||
|
adds that context to your log lines.
|
||||||
|
|
||||||
|
But alas, Andrew Gerrand's typically diplomatic answer to the question of
|
||||||
|
goroutine-local variables was:
|
||||||
|
|
||||||
|
> We wouldn't even be having this discussion if thread local storage wasn't
|
||||||
|
> useful. But every feature comes at a cost, and in my opinion the cost of
|
||||||
|
> threadlocals far outweighs their benefits. They're just not a good fit for
|
||||||
|
> Go.
|
||||||
|
|
||||||
|
So, yeah, that makes sense. That's a pretty good reason for why the language
|
||||||
|
won't support a specific and (relatively) unuseful feature that requires some
|
||||||
|
runtime changes, just for the sake of a little bit of log improvement.
|
||||||
|
|
||||||
|
But does Go require runtime changes?
|
||||||
|
|
||||||
|
### How it works ###
|
||||||
|
|
||||||
|
Go has pretty fantastic introspective and reflective features, but one thing Go
|
||||||
|
doesn't give you is any kind of access to the stack pointer, or frame pointer,
|
||||||
|
or goroutine id, or anything contextual about your current stack. It gives you
|
||||||
|
access to your list of callers, but only along with program counters, which are
|
||||||
|
fixed at compile time.
|
||||||
|
|
||||||
|
But it does give you the stack.
|
||||||
|
|
||||||
|
So, we define 16 special functions and embed base-16 tags into the stack using
|
||||||
|
the call order of those 16 functions. Then, we can read our tags back out of
|
||||||
|
the stack looking at the callers list.
|
||||||
|
|
||||||
|
We then use these tags as an index into a traditional map for implementing
|
||||||
|
this library.
|
||||||
|
|
||||||
|
### What are people saying? ###
|
||||||
|
|
||||||
|
"Wow, that's horrifying."
|
||||||
|
|
||||||
|
"This is the most terrible thing I have seen in a very long time."
|
||||||
|
|
||||||
|
"Where is it getting a context from? Is this serializing all the requests?
|
||||||
|
What the heck is the client being bound to? What are these tags? Why does he
|
||||||
|
need callers? Oh god no. No no no."
|
||||||
|
|
||||||
|
### Docs ###
|
||||||
|
|
||||||
|
Please see the docs at http://godoc.org/github.com/jtolds/gls
|
||||||
|
|
||||||
|
### Related ###
|
||||||
|
|
||||||
|
If you're okay relying on the string format of the current runtime stacktrace
|
||||||
|
including a unique goroutine id (not guaranteed by the spec or anything, but
|
||||||
|
very unlikely to change within a Go release), you might be able to squeeze
|
||||||
|
out a bit more performance by using this similar library, inspired by some
|
||||||
|
code Brad Fitzpatrick wrote for debugging his HTTP/2 library:
|
||||||
|
https://github.com/tylerb/gls (in contrast, jtolds/gls doesn't require
|
||||||
|
any knowledge of the string format of the runtime stacktrace, which
|
||||||
|
probably adds unnecessary overhead).
|
153
vendor/github.com/jtolds/gls/context.go
generated
vendored
Normal file
153
vendor/github.com/jtolds/gls/context.go
generated
vendored
Normal file
|
@ -0,0 +1,153 @@
|
||||||
|
// Package gls implements goroutine-local storage.
|
||||||
|
package gls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
mgrRegistry = make(map[*ContextManager]bool)
|
||||||
|
mgrRegistryMtx sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// Values is simply a map of key types to value types. Used by SetValues to
|
||||||
|
// set multiple values at once.
|
||||||
|
type Values map[interface{}]interface{}
|
||||||
|
|
||||||
|
// ContextManager is the main entrypoint for interacting with
|
||||||
|
// Goroutine-local-storage. You can have multiple independent ContextManagers
|
||||||
|
// at any given time. ContextManagers are usually declared globally for a given
|
||||||
|
// class of context variables. You should use NewContextManager for
|
||||||
|
// construction.
|
||||||
|
type ContextManager struct {
|
||||||
|
mtx sync.Mutex
|
||||||
|
values map[uint]Values
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewContextManager returns a brand new ContextManager. It also registers the
|
||||||
|
// new ContextManager in the ContextManager registry which is used by the Go
|
||||||
|
// method. ContextManagers are typically defined globally at package scope.
|
||||||
|
func NewContextManager() *ContextManager {
|
||||||
|
mgr := &ContextManager{values: make(map[uint]Values)}
|
||||||
|
mgrRegistryMtx.Lock()
|
||||||
|
defer mgrRegistryMtx.Unlock()
|
||||||
|
mgrRegistry[mgr] = true
|
||||||
|
return mgr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unregister removes a ContextManager from the global registry, used by the
|
||||||
|
// Go method. Only intended for use when you're completely done with a
|
||||||
|
// ContextManager. Use of Unregister at all is rare.
|
||||||
|
func (m *ContextManager) Unregister() {
|
||||||
|
mgrRegistryMtx.Lock()
|
||||||
|
defer mgrRegistryMtx.Unlock()
|
||||||
|
delete(mgrRegistry, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetValues takes a collection of values and a function to call for those
|
||||||
|
// values to be set in. Anything further down the stack will have the set
|
||||||
|
// values available through GetValue. SetValues will add new values or replace
|
||||||
|
// existing values of the same key and will not mutate or change values for
|
||||||
|
// previous stack frames.
|
||||||
|
// SetValues is slow (makes a copy of all current and new values for the new
|
||||||
|
// gls-context) in order to reduce the amount of lookups GetValue requires.
|
||||||
|
func (m *ContextManager) SetValues(new_values Values, context_call func()) {
|
||||||
|
if len(new_values) == 0 {
|
||||||
|
context_call()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
mutated_keys := make([]interface{}, 0, len(new_values))
|
||||||
|
mutated_vals := make(Values, len(new_values))
|
||||||
|
|
||||||
|
EnsureGoroutineId(func(gid uint) {
|
||||||
|
m.mtx.Lock()
|
||||||
|
state, found := m.values[gid]
|
||||||
|
if !found {
|
||||||
|
state = make(Values, len(new_values))
|
||||||
|
m.values[gid] = state
|
||||||
|
}
|
||||||
|
m.mtx.Unlock()
|
||||||
|
|
||||||
|
for key, new_val := range new_values {
|
||||||
|
mutated_keys = append(mutated_keys, key)
|
||||||
|
if old_val, ok := state[key]; ok {
|
||||||
|
mutated_vals[key] = old_val
|
||||||
|
}
|
||||||
|
state[key] = new_val
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
if !found {
|
||||||
|
m.mtx.Lock()
|
||||||
|
delete(m.values, gid)
|
||||||
|
m.mtx.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, key := range mutated_keys {
|
||||||
|
if val, ok := mutated_vals[key]; ok {
|
||||||
|
state[key] = val
|
||||||
|
} else {
|
||||||
|
delete(state, key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
context_call()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetValue will return a previously set value, provided that the value was set
|
||||||
|
// by SetValues somewhere higher up the stack. If the value is not found, ok
|
||||||
|
// will be false.
|
||||||
|
func (m *ContextManager) GetValue(key interface{}) (
|
||||||
|
value interface{}, ok bool) {
|
||||||
|
gid, ok := GetGoroutineId()
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
m.mtx.Lock()
|
||||||
|
state, found := m.values[gid]
|
||||||
|
m.mtx.Unlock()
|
||||||
|
|
||||||
|
if !found {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
value, ok = state[key]
|
||||||
|
return value, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *ContextManager) getValues() Values {
|
||||||
|
gid, ok := GetGoroutineId()
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m.mtx.Lock()
|
||||||
|
state, _ := m.values[gid]
|
||||||
|
m.mtx.Unlock()
|
||||||
|
return state
|
||||||
|
}
|
||||||
|
|
||||||
|
// Go preserves ContextManager values and Goroutine-local-storage across new
|
||||||
|
// goroutine invocations. The Go method makes a copy of all existing values on
|
||||||
|
// all registered context managers and makes sure they are still set after
|
||||||
|
// kicking off the provided function in a new goroutine. If you don't use this
|
||||||
|
// Go method instead of the standard 'go' keyword, you will lose values in
|
||||||
|
// ContextManagers, as goroutines have brand new stacks.
|
||||||
|
func Go(cb func()) {
|
||||||
|
mgrRegistryMtx.RLock()
|
||||||
|
defer mgrRegistryMtx.RUnlock()
|
||||||
|
|
||||||
|
for mgr := range mgrRegistry {
|
||||||
|
values := mgr.getValues()
|
||||||
|
if len(values) > 0 {
|
||||||
|
cb = func(mgr *ContextManager, cb func()) func() {
|
||||||
|
return func() { mgr.SetValues(values, cb) }
|
||||||
|
}(mgr, cb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
go cb()
|
||||||
|
}
|
21
vendor/github.com/jtolds/gls/gen_sym.go
generated
vendored
Normal file
21
vendor/github.com/jtolds/gls/gen_sym.go
generated
vendored
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
package gls
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
keyMtx sync.Mutex
|
||||||
|
keyCounter uint64
|
||||||
|
)
|
||||||
|
|
||||||
|
// ContextKey is a throwaway value you can use as a key to a ContextManager
|
||||||
|
type ContextKey struct{ id uint64 }
|
||||||
|
|
||||||
|
// GenSym will return a brand new, never-before-used ContextKey
|
||||||
|
func GenSym() ContextKey {
|
||||||
|
keyMtx.Lock()
|
||||||
|
defer keyMtx.Unlock()
|
||||||
|
keyCounter += 1
|
||||||
|
return ContextKey{id: keyCounter}
|
||||||
|
}
|
25
vendor/github.com/jtolds/gls/gid.go
generated
vendored
Normal file
25
vendor/github.com/jtolds/gls/gid.go
generated
vendored
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
package gls
|
||||||
|
|
||||||
|
var (
|
||||||
|
stackTagPool = &idPool{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// Will return this goroutine's identifier if set. If you always need a
|
||||||
|
// goroutine identifier, you should use EnsureGoroutineId which will make one
|
||||||
|
// if there isn't one already.
|
||||||
|
func GetGoroutineId() (gid uint, ok bool) {
|
||||||
|
return readStackTag()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Will call cb with the current goroutine identifier. If one hasn't already
|
||||||
|
// been generated, one will be created and set first. The goroutine identifier
|
||||||
|
// might be invalid after cb returns.
|
||||||
|
func EnsureGoroutineId(cb func(gid uint)) {
|
||||||
|
if gid, ok := readStackTag(); ok {
|
||||||
|
cb(gid)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
gid := stackTagPool.Acquire()
|
||||||
|
defer stackTagPool.Release(gid)
|
||||||
|
addStackTag(gid, func() { cb(gid) })
|
||||||
|
}
|
34
vendor/github.com/jtolds/gls/id_pool.go
generated
vendored
Normal file
34
vendor/github.com/jtolds/gls/id_pool.go
generated
vendored
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
package gls
|
||||||
|
|
||||||
|
// though this could probably be better at keeping ids smaller, the goal of
|
||||||
|
// this class is to keep a registry of the smallest unique integer ids
|
||||||
|
// per-process possible
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type idPool struct {
|
||||||
|
mtx sync.Mutex
|
||||||
|
released []uint
|
||||||
|
max_id uint
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *idPool) Acquire() (id uint) {
|
||||||
|
p.mtx.Lock()
|
||||||
|
defer p.mtx.Unlock()
|
||||||
|
if len(p.released) > 0 {
|
||||||
|
id = p.released[len(p.released)-1]
|
||||||
|
p.released = p.released[:len(p.released)-1]
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
id = p.max_id
|
||||||
|
p.max_id++
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *idPool) Release(id uint) {
|
||||||
|
p.mtx.Lock()
|
||||||
|
defer p.mtx.Unlock()
|
||||||
|
p.released = append(p.released, id)
|
||||||
|
}
|
108
vendor/github.com/jtolds/gls/stack_tags.go
generated
vendored
Normal file
108
vendor/github.com/jtolds/gls/stack_tags.go
generated
vendored
Normal file
|
@ -0,0 +1,108 @@
|
||||||
|
package gls
|
||||||
|
|
||||||
|
// so, basically, we're going to encode integer tags in base-16 on the stack
|
||||||
|
|
||||||
|
const (
|
||||||
|
bitWidth = 4
|
||||||
|
stackBatchSize = 16
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
pc_lookup = make(map[uintptr]int8, 17)
|
||||||
|
mark_lookup [16]func(uint, func())
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
setEntries := func(f func(uint, func()), v int8) {
|
||||||
|
var ptr uintptr
|
||||||
|
f(0, func() {
|
||||||
|
ptr = findPtr()
|
||||||
|
})
|
||||||
|
pc_lookup[ptr] = v
|
||||||
|
if v >= 0 {
|
||||||
|
mark_lookup[v] = f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setEntries(github_com_jtolds_gls_markS, -0x1)
|
||||||
|
setEntries(github_com_jtolds_gls_mark0, 0x0)
|
||||||
|
setEntries(github_com_jtolds_gls_mark1, 0x1)
|
||||||
|
setEntries(github_com_jtolds_gls_mark2, 0x2)
|
||||||
|
setEntries(github_com_jtolds_gls_mark3, 0x3)
|
||||||
|
setEntries(github_com_jtolds_gls_mark4, 0x4)
|
||||||
|
setEntries(github_com_jtolds_gls_mark5, 0x5)
|
||||||
|
setEntries(github_com_jtolds_gls_mark6, 0x6)
|
||||||
|
setEntries(github_com_jtolds_gls_mark7, 0x7)
|
||||||
|
setEntries(github_com_jtolds_gls_mark8, 0x8)
|
||||||
|
setEntries(github_com_jtolds_gls_mark9, 0x9)
|
||||||
|
setEntries(github_com_jtolds_gls_markA, 0xa)
|
||||||
|
setEntries(github_com_jtolds_gls_markB, 0xb)
|
||||||
|
setEntries(github_com_jtolds_gls_markC, 0xc)
|
||||||
|
setEntries(github_com_jtolds_gls_markD, 0xd)
|
||||||
|
setEntries(github_com_jtolds_gls_markE, 0xe)
|
||||||
|
setEntries(github_com_jtolds_gls_markF, 0xf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func addStackTag(tag uint, context_call func()) {
|
||||||
|
if context_call == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
github_com_jtolds_gls_markS(tag, context_call)
|
||||||
|
}
|
||||||
|
|
||||||
|
// these private methods are named this horrendous name so gopherjs support
|
||||||
|
// is easier. it shouldn't add any runtime cost in non-js builds.
|
||||||
|
func github_com_jtolds_gls_markS(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark0(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark1(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark2(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark3(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark4(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark5(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark6(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark7(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark8(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_mark9(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markA(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markB(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markC(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markD(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markE(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
func github_com_jtolds_gls_markF(tag uint, cb func()) { _m(tag, cb) }
|
||||||
|
|
||||||
|
func _m(tag_remainder uint, cb func()) {
|
||||||
|
if tag_remainder == 0 {
|
||||||
|
cb()
|
||||||
|
} else {
|
||||||
|
mark_lookup[tag_remainder&0xf](tag_remainder>>bitWidth, cb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readStackTag() (tag uint, ok bool) {
|
||||||
|
var current_tag uint
|
||||||
|
offset := 0
|
||||||
|
for {
|
||||||
|
// the expectation with getStack is that it will either:
|
||||||
|
// * return everything when offset is 0 and ignore stackBatchSize,
|
||||||
|
// otherwise returning nothing when offset is not 0 (the gopherjs case)
|
||||||
|
// * or it will return at most stackBatchSize, respect offset, and
|
||||||
|
// shouldn't be called when it returns less than stackBatchSize
|
||||||
|
// (the runtime.Callers case).
|
||||||
|
batch := getStack(offset, stackBatchSize)
|
||||||
|
for _, pc := range batch {
|
||||||
|
val, ok := pc_lookup[pc]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if val < 0 {
|
||||||
|
return current_tag, true
|
||||||
|
}
|
||||||
|
current_tag <<= bitWidth
|
||||||
|
current_tag += uint(val)
|
||||||
|
}
|
||||||
|
if len(batch) < stackBatchSize {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
offset += len(batch)
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
75
vendor/github.com/jtolds/gls/stack_tags_js.go
generated
vendored
Normal file
75
vendor/github.com/jtolds/gls/stack_tags_js.go
generated
vendored
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
// +build js
|
||||||
|
|
||||||
|
package gls
|
||||||
|
|
||||||
|
// This file is used for GopherJS builds, which don't have normal runtime
|
||||||
|
// stack trace support
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gopherjs/gopherjs/js"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
jsFuncNamePrefix = "github_com_jtolds_gls_mark"
|
||||||
|
)
|
||||||
|
|
||||||
|
func jsMarkStack() (f []uintptr) {
|
||||||
|
lines := strings.Split(
|
||||||
|
js.Global.Get("Error").New().Get("stack").String(), "\n")
|
||||||
|
f = make([]uintptr, 0, len(lines))
|
||||||
|
for i, line := range lines {
|
||||||
|
line = strings.TrimSpace(line)
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if i == 0 {
|
||||||
|
if line != "Error" {
|
||||||
|
panic("didn't understand js stack trace")
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
if len(fields) < 2 || fields[0] != "at" {
|
||||||
|
panic("didn't understand js stack trace")
|
||||||
|
}
|
||||||
|
|
||||||
|
pos := strings.Index(fields[1], jsFuncNamePrefix)
|
||||||
|
if pos < 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pos += len(jsFuncNamePrefix)
|
||||||
|
if pos >= len(fields[1]) {
|
||||||
|
panic("didn't understand js stack trace")
|
||||||
|
}
|
||||||
|
char := string(fields[1][pos])
|
||||||
|
switch char {
|
||||||
|
case "S":
|
||||||
|
f = append(f, uintptr(0))
|
||||||
|
default:
|
||||||
|
val, err := strconv.ParseUint(char, 16, 8)
|
||||||
|
if err != nil {
|
||||||
|
panic("didn't understand js stack trace")
|
||||||
|
}
|
||||||
|
f = append(f, uintptr(val)+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func findPtr() uintptr {
|
||||||
|
funcs := jsMarkStack()
|
||||||
|
if len(funcs) == 0 {
|
||||||
|
panic("failed to find function pointer")
|
||||||
|
}
|
||||||
|
return funcs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func getStack(offset, amount int) []uintptr {
|
||||||
|
if offset != 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return jsMarkStack()
|
||||||
|
}
|
23
vendor/github.com/jtolds/gls/stack_tags_main.go
generated
vendored
Normal file
23
vendor/github.com/jtolds/gls/stack_tags_main.go
generated
vendored
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
// +build !js
|
||||||
|
|
||||||
|
package gls
|
||||||
|
|
||||||
|
// This file is used for standard Go builds, which have the expected runtime
|
||||||
|
// support
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getStack(offset, amount int) []uintptr {
|
||||||
|
stack := make([]uintptr, amount)
|
||||||
|
return stack[:runtime.Callers(offset, stack)]
|
||||||
|
}
|
||||||
|
|
||||||
|
func findPtr() uintptr {
|
||||||
|
pc, _, _, ok := runtime.Caller(3)
|
||||||
|
if !ok {
|
||||||
|
panic("failed to find function pointer")
|
||||||
|
}
|
||||||
|
return pc
|
||||||
|
}
|
23
vendor/github.com/mailhog/MailHog-Server/api/api.go
generated
vendored
23
vendor/github.com/mailhog/MailHog-Server/api/api.go
generated
vendored
|
@ -1,23 +0,0 @@
|
||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
gohttp "net/http"
|
|
||||||
|
|
||||||
"github.com/gorilla/pat"
|
|
||||||
"github.com/mailhog/MailHog-Server/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
func CreateAPI(conf *config.Config, r gohttp.Handler) {
|
|
||||||
apiv1 := createAPIv1(conf, r.(*pat.Router))
|
|
||||||
apiv2 := createAPIv2(conf, r.(*pat.Router))
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case msg := <-conf.MessageChan:
|
|
||||||
apiv1.messageChan <- msg
|
|
||||||
apiv2.messageChan <- msg
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
359
vendor/github.com/mailhog/MailHog-Server/api/v1.go
generated
vendored
359
vendor/github.com/mailhog/MailHog-Server/api/v1.go
generated
vendored
|
@ -1,359 +0,0 @@
|
||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/smtp"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/pat"
|
|
||||||
"github.com/ian-kent/go-log/log"
|
|
||||||
"github.com/mailhog/MailHog-Server/config"
|
|
||||||
"github.com/mailhog/data"
|
|
||||||
"github.com/mailhog/storage"
|
|
||||||
|
|
||||||
"github.com/ian-kent/goose"
|
|
||||||
)
|
|
||||||
|
|
||||||
// APIv1 implements version 1 of the MailHog API
|
|
||||||
//
|
|
||||||
// The specification has been frozen and will eventually be deprecated.
|
|
||||||
// Only bug fixes and non-breaking changes will be applied here.
|
|
||||||
//
|
|
||||||
// Any changes/additions should be added in APIv2.
|
|
||||||
type APIv1 struct {
|
|
||||||
config *config.Config
|
|
||||||
messageChan chan *data.Message
|
|
||||||
}
|
|
||||||
|
|
||||||
// FIXME should probably move this into APIv1 struct
|
|
||||||
var stream *goose.EventStream
|
|
||||||
|
|
||||||
// ReleaseConfig is an alias to preserve go package API
|
|
||||||
type ReleaseConfig config.OutgoingSMTP
|
|
||||||
|
|
||||||
func createAPIv1(conf *config.Config, r *pat.Router) *APIv1 {
|
|
||||||
log.Println("Creating API v1 with WebPath: " + conf.WebPath)
|
|
||||||
apiv1 := &APIv1{
|
|
||||||
config: conf,
|
|
||||||
messageChan: make(chan *data.Message),
|
|
||||||
}
|
|
||||||
|
|
||||||
stream = goose.NewEventStream()
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages").Methods("GET").HandlerFunc(apiv1.messages)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages").Methods("DELETE").HandlerFunc(apiv1.delete_all)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}").Methods("GET").HandlerFunc(apiv1.message)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}").Methods("DELETE").HandlerFunc(apiv1.delete_one)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/download").Methods("GET").HandlerFunc(apiv1.download)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/download").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/mime/part/{part}/download").Methods("GET").HandlerFunc(apiv1.download_part)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/mime/part/{part}/download").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/release").Methods("POST").HandlerFunc(apiv1.release_one)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/messages/{id}/release").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v1/events").Methods("GET").HandlerFunc(apiv1.eventstream)
|
|
||||||
r.Path(conf.WebPath + "/api/v1/events").Methods("OPTIONS").HandlerFunc(apiv1.defaultOptions)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
keepaliveTicker := time.Tick(time.Minute)
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case msg := <-apiv1.messageChan:
|
|
||||||
log.Println("Got message in APIv1 event stream")
|
|
||||||
bytes, _ := json.MarshalIndent(msg, "", " ")
|
|
||||||
json := string(bytes)
|
|
||||||
log.Printf("Sending content: %s\n", json)
|
|
||||||
apiv1.broadcast(json)
|
|
||||||
case <-keepaliveTicker:
|
|
||||||
apiv1.keepalive()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return apiv1
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) defaultOptions(w http.ResponseWriter, req *http.Request) {
|
|
||||||
if len(apiv1.config.CORSOrigin) > 0 {
|
|
||||||
w.Header().Add("Access-Control-Allow-Origin", apiv1.config.CORSOrigin)
|
|
||||||
w.Header().Add("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE")
|
|
||||||
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) broadcast(json string) {
|
|
||||||
log.Println("[APIv1] BROADCAST /api/v1/events")
|
|
||||||
b := []byte(json)
|
|
||||||
stream.Notify("data", b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// keepalive sends an empty keep alive message.
|
|
||||||
//
|
|
||||||
// This not only can keep connections alive, but also will detect broken
|
|
||||||
// connections. Without this it is possible for the server to become
|
|
||||||
// unresponsive due to too many open files.
|
|
||||||
func (apiv1 *APIv1) keepalive() {
|
|
||||||
log.Println("[APIv1] KEEPALIVE /api/v1/events")
|
|
||||||
stream.Notify("keepalive", []byte{})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) eventstream(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv1] GET /api/v1/events")
|
|
||||||
|
|
||||||
//apiv1.defaultOptions(session)
|
|
||||||
if len(apiv1.config.CORSOrigin) > 0 {
|
|
||||||
w.Header().Add("Access-Control-Allow-Origin", apiv1.config.CORSOrigin)
|
|
||||||
w.Header().Add("Access-Control-Allow-Methods", "OPTIONS,GET,POST,DELETE")
|
|
||||||
}
|
|
||||||
|
|
||||||
stream.AddReceiver(w)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) messages(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv1] GET /api/v1/messages")
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
// TODO start, limit
|
|
||||||
switch apiv1.config.Storage.(type) {
|
|
||||||
case *storage.MongoDB:
|
|
||||||
messages, _ := apiv1.config.Storage.(*storage.MongoDB).List(0, 1000)
|
|
||||||
bytes, _ := json.Marshal(messages)
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
w.Write(bytes)
|
|
||||||
case *storage.InMemory:
|
|
||||||
messages, _ := apiv1.config.Storage.(*storage.InMemory).List(0, 1000)
|
|
||||||
bytes, _ := json.Marshal(messages)
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
w.Write(bytes)
|
|
||||||
default:
|
|
||||||
w.WriteHeader(500)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) message(w http.ResponseWriter, req *http.Request) {
|
|
||||||
id := req.URL.Query().Get(":id")
|
|
||||||
log.Printf("[APIv1] GET /api/v1/messages/%s\n", id)
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
message, err := apiv1.config.Storage.Load(id)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("- Error: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
bytes, err := json.Marshal(message)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("- Error: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/json")
|
|
||||||
w.Write(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) download(w http.ResponseWriter, req *http.Request) {
|
|
||||||
id := req.URL.Query().Get(":id")
|
|
||||||
log.Printf("[APIv1] GET /api/v1/messages/%s\n", id)
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "message/rfc822")
|
|
||||||
w.Header().Set("Content-Disposition", "attachment; filename=\""+id+".eml\"")
|
|
||||||
|
|
||||||
switch apiv1.config.Storage.(type) {
|
|
||||||
case *storage.MongoDB:
|
|
||||||
message, _ := apiv1.config.Storage.(*storage.MongoDB).Load(id)
|
|
||||||
for h, l := range message.Content.Headers {
|
|
||||||
for _, v := range l {
|
|
||||||
w.Write([]byte(h + ": " + v + "\r\n"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.Write([]byte("\r\n" + message.Content.Body))
|
|
||||||
case *storage.InMemory:
|
|
||||||
message, _ := apiv1.config.Storage.(*storage.InMemory).Load(id)
|
|
||||||
for h, l := range message.Content.Headers {
|
|
||||||
for _, v := range l {
|
|
||||||
w.Write([]byte(h + ": " + v + "\r\n"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.Write([]byte("\r\n" + message.Content.Body))
|
|
||||||
default:
|
|
||||||
w.WriteHeader(500)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) download_part(w http.ResponseWriter, req *http.Request) {
|
|
||||||
id := req.URL.Query().Get(":id")
|
|
||||||
part := req.URL.Query().Get(":part")
|
|
||||||
log.Printf("[APIv1] GET /api/v1/messages/%s/mime/part/%s/download\n", id, part)
|
|
||||||
|
|
||||||
// TODO extension from content-type?
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
w.Header().Set("Content-Disposition", "attachment; filename=\""+id+"-part-"+part+"\"")
|
|
||||||
|
|
||||||
message, _ := apiv1.config.Storage.Load(id)
|
|
||||||
contentTransferEncoding := ""
|
|
||||||
pid, _ := strconv.Atoi(part)
|
|
||||||
for h, l := range message.MIME.Parts[pid].Headers {
|
|
||||||
for _, v := range l {
|
|
||||||
switch strings.ToLower(h) {
|
|
||||||
case "content-disposition":
|
|
||||||
// Prevent duplicate "content-disposition"
|
|
||||||
w.Header().Set(h, v)
|
|
||||||
case "content-transfer-encoding":
|
|
||||||
if contentTransferEncoding == "" {
|
|
||||||
contentTransferEncoding = v
|
|
||||||
}
|
|
||||||
fallthrough
|
|
||||||
default:
|
|
||||||
w.Header().Add(h, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
body := []byte(message.MIME.Parts[pid].Body)
|
|
||||||
if strings.ToLower(contentTransferEncoding) == "base64" {
|
|
||||||
var e error
|
|
||||||
body, e = base64.StdEncoding.DecodeString(message.MIME.Parts[pid].Body)
|
|
||||||
if e != nil {
|
|
||||||
log.Printf("[APIv1] Decoding base64 encoded body failed: %s", e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.Write(body)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) delete_all(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv1] POST /api/v1/messages")
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
|
|
||||||
err := apiv1.config.Storage.DeleteAll()
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(200)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) release_one(w http.ResponseWriter, req *http.Request) {
|
|
||||||
id := req.URL.Query().Get(":id")
|
|
||||||
log.Printf("[APIv1] POST /api/v1/messages/%s/release\n", id)
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
msg, _ := apiv1.config.Storage.Load(id)
|
|
||||||
|
|
||||||
decoder := json.NewDecoder(req.Body)
|
|
||||||
var cfg ReleaseConfig
|
|
||||||
err := decoder.Decode(&cfg)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Error decoding request body: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
w.Write([]byte("Error decoding request body"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("%+v", cfg)
|
|
||||||
|
|
||||||
log.Printf("Got message: %s", msg.ID)
|
|
||||||
|
|
||||||
if cfg.Save {
|
|
||||||
if _, ok := apiv1.config.OutgoingSMTP[cfg.Name]; ok {
|
|
||||||
log.Printf("Server already exists named %s", cfg.Name)
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
cf := config.OutgoingSMTP(cfg)
|
|
||||||
apiv1.config.OutgoingSMTP[cfg.Name] = &cf
|
|
||||||
log.Printf("Saved server with name %s", cfg.Name)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(cfg.Name) > 0 {
|
|
||||||
if c, ok := apiv1.config.OutgoingSMTP[cfg.Name]; ok {
|
|
||||||
log.Printf("Using server with name: %s", cfg.Name)
|
|
||||||
cfg.Name = c.Name
|
|
||||||
if len(cfg.Email) == 0 {
|
|
||||||
cfg.Email = c.Email
|
|
||||||
}
|
|
||||||
cfg.Host = c.Host
|
|
||||||
cfg.Port = c.Port
|
|
||||||
cfg.Username = c.Username
|
|
||||||
cfg.Password = c.Password
|
|
||||||
cfg.Mechanism = c.Mechanism
|
|
||||||
} else {
|
|
||||||
log.Printf("Server not found: %s", cfg.Name)
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("Releasing to %s (via %s:%s)", cfg.Email, cfg.Host, cfg.Port)
|
|
||||||
|
|
||||||
bytes := make([]byte, 0)
|
|
||||||
for h, l := range msg.Content.Headers {
|
|
||||||
for _, v := range l {
|
|
||||||
bytes = append(bytes, []byte(h+": "+v+"\r\n")...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
bytes = append(bytes, []byte("\r\n"+msg.Content.Body)...)
|
|
||||||
|
|
||||||
var auth smtp.Auth
|
|
||||||
|
|
||||||
if len(cfg.Username) > 0 || len(cfg.Password) > 0 {
|
|
||||||
log.Printf("Found username/password, using auth mechanism: [%s]", cfg.Mechanism)
|
|
||||||
switch cfg.Mechanism {
|
|
||||||
case "CRAMMD5":
|
|
||||||
auth = smtp.CRAMMD5Auth(cfg.Username, cfg.Password)
|
|
||||||
case "PLAIN":
|
|
||||||
auth = smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
|
|
||||||
default:
|
|
||||||
log.Printf("Error - invalid authentication mechanism")
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
err = smtp.SendMail(cfg.Host+":"+cfg.Port, auth, "nobody@"+apiv1.config.Hostname, []string{cfg.Email}, bytes)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("Failed to release message: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("Message released successfully")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv1 *APIv1) delete_one(w http.ResponseWriter, req *http.Request) {
|
|
||||||
id := req.URL.Query().Get(":id")
|
|
||||||
|
|
||||||
log.Printf("[APIv1] POST /api/v1/messages/%s/delete\n", id)
|
|
||||||
|
|
||||||
apiv1.defaultOptions(w, req)
|
|
||||||
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
err := apiv1.config.Storage.DeleteOne(id)
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w.WriteHeader(200)
|
|
||||||
}
|
|
258
vendor/github.com/mailhog/MailHog-Server/api/v2.go
generated
vendored
258
vendor/github.com/mailhog/MailHog-Server/api/v2.go
generated
vendored
|
@ -1,258 +0,0 @@
|
||||||
package api
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/gorilla/pat"
|
|
||||||
"github.com/ian-kent/go-log/log"
|
|
||||||
"github.com/mailhog/MailHog-Server/config"
|
|
||||||
"github.com/mailhog/MailHog-Server/monkey"
|
|
||||||
"github.com/mailhog/MailHog-Server/websockets"
|
|
||||||
"github.com/mailhog/data"
|
|
||||||
)
|
|
||||||
|
|
||||||
// APIv2 implements version 2 of the MailHog API
|
|
||||||
//
|
|
||||||
// It is currently experimental and may change in future releases.
|
|
||||||
// Use APIv1 for guaranteed compatibility.
|
|
||||||
type APIv2 struct {
|
|
||||||
config *config.Config
|
|
||||||
messageChan chan *data.Message
|
|
||||||
wsHub *websockets.Hub
|
|
||||||
}
|
|
||||||
|
|
||||||
func createAPIv2(conf *config.Config, r *pat.Router) *APIv2 {
|
|
||||||
log.Println("Creating API v2 with WebPath: " + conf.WebPath)
|
|
||||||
apiv2 := &APIv2{
|
|
||||||
config: conf,
|
|
||||||
messageChan: make(chan *data.Message),
|
|
||||||
wsHub: websockets.NewHub(),
|
|
||||||
}
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v2/messages").Methods("GET").HandlerFunc(apiv2.messages)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/messages").Methods("OPTIONS").HandlerFunc(apiv2.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v2/search").Methods("GET").HandlerFunc(apiv2.search)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/search").Methods("OPTIONS").HandlerFunc(apiv2.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v2/jim").Methods("GET").HandlerFunc(apiv2.jim)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/jim").Methods("POST").HandlerFunc(apiv2.createJim)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/jim").Methods("PUT").HandlerFunc(apiv2.updateJim)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/jim").Methods("DELETE").HandlerFunc(apiv2.deleteJim)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/jim").Methods("OPTIONS").HandlerFunc(apiv2.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v2/outgoing-smtp").Methods("GET").HandlerFunc(apiv2.listOutgoingSMTP)
|
|
||||||
r.Path(conf.WebPath + "/api/v2/outgoing-smtp").Methods("OPTIONS").HandlerFunc(apiv2.defaultOptions)
|
|
||||||
|
|
||||||
r.Path(conf.WebPath + "/api/v2/websocket").Methods("GET").HandlerFunc(apiv2.websocket)
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case msg := <-apiv2.messageChan:
|
|
||||||
log.Println("Got message in APIv2 websocket channel")
|
|
||||||
apiv2.broadcast(msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return apiv2
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) defaultOptions(w http.ResponseWriter, req *http.Request) {
|
|
||||||
if len(apiv2.config.CORSOrigin) > 0 {
|
|
||||||
w.Header().Add("Access-Control-Allow-Origin", apiv2.config.CORSOrigin)
|
|
||||||
w.Header().Add("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE")
|
|
||||||
w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type messagesResult struct {
|
|
||||||
Total int `json:"total"`
|
|
||||||
Count int `json:"count"`
|
|
||||||
Start int `json:"start"`
|
|
||||||
Items []data.Message `json:"items"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) getStartLimit(w http.ResponseWriter, req *http.Request) (start, limit int) {
|
|
||||||
start = 0
|
|
||||||
limit = 50
|
|
||||||
|
|
||||||
s := req.URL.Query().Get("start")
|
|
||||||
if n, e := strconv.ParseInt(s, 10, 64); e == nil && n > 0 {
|
|
||||||
start = int(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
l := req.URL.Query().Get("limit")
|
|
||||||
if n, e := strconv.ParseInt(l, 10, 64); e == nil && n > 0 {
|
|
||||||
if n > 250 {
|
|
||||||
n = 250
|
|
||||||
}
|
|
||||||
limit = int(n)
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) messages(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] GET /api/v2/messages")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
start, limit := apiv2.getStartLimit(w, req)
|
|
||||||
|
|
||||||
var res messagesResult
|
|
||||||
|
|
||||||
messages, err := apiv2.config.Storage.List(start, limit)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
res.Count = len([]data.Message(*messages))
|
|
||||||
res.Start = start
|
|
||||||
res.Items = []data.Message(*messages)
|
|
||||||
res.Total = apiv2.config.Storage.Count()
|
|
||||||
|
|
||||||
bytes, _ := json.Marshal(res)
|
|
||||||
w.Header().Add("Content-Type", "text/json")
|
|
||||||
w.Write(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) search(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] GET /api/v2/search")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
start, limit := apiv2.getStartLimit(w, req)
|
|
||||||
|
|
||||||
kind := req.URL.Query().Get("kind")
|
|
||||||
if kind != "from" && kind != "to" && kind != "containing" {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
query := req.URL.Query().Get("query")
|
|
||||||
if len(query) == 0 {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var res messagesResult
|
|
||||||
|
|
||||||
messages, total, _ := apiv2.config.Storage.Search(kind, query, start, limit)
|
|
||||||
|
|
||||||
res.Count = len([]data.Message(*messages))
|
|
||||||
res.Start = start
|
|
||||||
res.Items = []data.Message(*messages)
|
|
||||||
res.Total = total
|
|
||||||
|
|
||||||
b, _ := json.Marshal(res)
|
|
||||||
w.Header().Add("Content-Type", "application/json")
|
|
||||||
w.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) jim(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] GET /api/v2/jim")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
if apiv2.config.Monkey == nil {
|
|
||||||
w.WriteHeader(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
b, _ := json.Marshal(apiv2.config.Monkey)
|
|
||||||
w.Header().Add("Content-Type", "application/json")
|
|
||||||
w.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) deleteJim(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] DELETE /api/v2/jim")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
if apiv2.config.Monkey == nil {
|
|
||||||
w.WriteHeader(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apiv2.config.Monkey = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) createJim(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] POST /api/v2/jim")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
if apiv2.config.Monkey != nil {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
apiv2.config.Monkey = config.Jim
|
|
||||||
|
|
||||||
// Try, but ignore errors
|
|
||||||
// Could be better (e.g., ok if no json, error if badly formed json)
|
|
||||||
// but this works for now
|
|
||||||
apiv2.newJimFromBody(w, req)
|
|
||||||
|
|
||||||
w.WriteHeader(201)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) newJimFromBody(w http.ResponseWriter, req *http.Request) error {
|
|
||||||
var jim monkey.Jim
|
|
||||||
|
|
||||||
dec := json.NewDecoder(req.Body)
|
|
||||||
err := dec.Decode(&jim)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
jim.ConfigureFrom(config.Jim)
|
|
||||||
|
|
||||||
config.Jim = &jim
|
|
||||||
apiv2.config.Monkey = &jim
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) updateJim(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] PUT /api/v2/jim")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
if apiv2.config.Monkey == nil {
|
|
||||||
w.WriteHeader(404)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := apiv2.newJimFromBody(w, req)
|
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) listOutgoingSMTP(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] GET /api/v2/outgoing-smtp")
|
|
||||||
|
|
||||||
apiv2.defaultOptions(w, req)
|
|
||||||
|
|
||||||
b, _ := json.Marshal(apiv2.config.OutgoingSMTP)
|
|
||||||
w.Header().Add("Content-Type", "application/json")
|
|
||||||
w.Write(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) websocket(w http.ResponseWriter, req *http.Request) {
|
|
||||||
log.Println("[APIv2] GET /api/v2/websocket")
|
|
||||||
|
|
||||||
apiv2.wsHub.Serve(w, req)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (apiv2 *APIv2) broadcast(msg *data.Message) {
|
|
||||||
log.Println("[APIv2] BROADCAST /api/v2/websocket")
|
|
||||||
|
|
||||||
apiv2.wsHub.Broadcast(msg)
|
|
||||||
}
|
|
132
vendor/github.com/mailhog/MailHog-Server/config/config.go
generated
vendored
132
vendor/github.com/mailhog/MailHog-Server/config/config.go
generated
vendored
|
@ -1,132 +0,0 @@
|
||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"flag"
|
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"github.com/ian-kent/envconf"
|
|
||||||
"github.com/mailhog/MailHog-Server/monkey"
|
|
||||||
"github.com/mailhog/data"
|
|
||||||
"github.com/mailhog/storage"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultConfig is the default config
|
|
||||||
func DefaultConfig() *Config {
|
|
||||||
return &Config{
|
|
||||||
SMTPBindAddr: "0.0.0.0:1025",
|
|
||||||
APIBindAddr: "0.0.0.0:8025",
|
|
||||||
Hostname: "mailhog.example",
|
|
||||||
MongoURI: "127.0.0.1:27017",
|
|
||||||
MongoDb: "mailhog",
|
|
||||||
MongoColl: "messages",
|
|
||||||
MaildirPath: "",
|
|
||||||
StorageType: "memory",
|
|
||||||
CORSOrigin: "",
|
|
||||||
WebPath: "",
|
|
||||||
MessageChan: make(chan *data.Message),
|
|
||||||
OutgoingSMTP: make(map[string]*OutgoingSMTP),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config is the config, kind of
|
|
||||||
type Config struct {
|
|
||||||
SMTPBindAddr string
|
|
||||||
APIBindAddr string
|
|
||||||
Hostname string
|
|
||||||
MongoURI string
|
|
||||||
MongoDb string
|
|
||||||
MongoColl string
|
|
||||||
StorageType string
|
|
||||||
CORSOrigin string
|
|
||||||
MaildirPath string
|
|
||||||
InviteJim bool
|
|
||||||
Storage storage.Storage
|
|
||||||
MessageChan chan *data.Message
|
|
||||||
Assets func(asset string) ([]byte, error)
|
|
||||||
Monkey monkey.ChaosMonkey
|
|
||||||
OutgoingSMTPFile string
|
|
||||||
OutgoingSMTP map[string]*OutgoingSMTP
|
|
||||||
WebPath string
|
|
||||||
}
|
|
||||||
|
|
||||||
// OutgoingSMTP is an outgoing SMTP server config
|
|
||||||
type OutgoingSMTP struct {
|
|
||||||
Name string
|
|
||||||
Save bool
|
|
||||||
Email string
|
|
||||||
Host string
|
|
||||||
Port string
|
|
||||||
Username string
|
|
||||||
Password string
|
|
||||||
Mechanism string
|
|
||||||
}
|
|
||||||
|
|
||||||
var cfg = DefaultConfig()
|
|
||||||
|
|
||||||
// Jim is a monkey
|
|
||||||
var Jim = &monkey.Jim{}
|
|
||||||
|
|
||||||
// Configure configures stuff
|
|
||||||
func Configure() *Config {
|
|
||||||
switch cfg.StorageType {
|
|
||||||
case "memory":
|
|
||||||
log.Println("Using in-memory storage")
|
|
||||||
cfg.Storage = storage.CreateInMemory()
|
|
||||||
case "mongodb":
|
|
||||||
log.Println("Using MongoDB message storage")
|
|
||||||
s := storage.CreateMongoDB(cfg.MongoURI, cfg.MongoDb, cfg.MongoColl)
|
|
||||||
if s == nil {
|
|
||||||
log.Println("MongoDB storage unavailable, reverting to in-memory storage")
|
|
||||||
cfg.Storage = storage.CreateInMemory()
|
|
||||||
} else {
|
|
||||||
log.Println("Connected to MongoDB")
|
|
||||||
cfg.Storage = s
|
|
||||||
}
|
|
||||||
case "maildir":
|
|
||||||
log.Println("Using maildir message storage")
|
|
||||||
s := storage.CreateMaildir(cfg.MaildirPath)
|
|
||||||
cfg.Storage = s
|
|
||||||
default:
|
|
||||||
log.Fatalf("Invalid storage type %s", cfg.StorageType)
|
|
||||||
}
|
|
||||||
|
|
||||||
Jim.Configure(func(message string, args ...interface{}) {
|
|
||||||
log.Printf(message, args...)
|
|
||||||
})
|
|
||||||
if cfg.InviteJim {
|
|
||||||
cfg.Monkey = Jim
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(cfg.OutgoingSMTPFile) > 0 {
|
|
||||||
b, err := ioutil.ReadFile(cfg.OutgoingSMTPFile)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
var o map[string]*OutgoingSMTP
|
|
||||||
err = json.Unmarshal(b, &o)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
cfg.OutgoingSMTP = o
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisterFlags registers flags
|
|
||||||
func RegisterFlags() {
|
|
||||||
flag.StringVar(&cfg.SMTPBindAddr, "smtp-bind-addr", envconf.FromEnvP("MH_SMTP_BIND_ADDR", "0.0.0.0:1025").(string), "SMTP bind interface and port, e.g. 0.0.0.0:1025 or just :1025")
|
|
||||||
flag.StringVar(&cfg.APIBindAddr, "api-bind-addr", envconf.FromEnvP("MH_API_BIND_ADDR", "0.0.0.0:8025").(string), "HTTP bind interface and port for API, e.g. 0.0.0.0:8025 or just :8025")
|
|
||||||
flag.StringVar(&cfg.Hostname, "hostname", envconf.FromEnvP("MH_HOSTNAME", "mailhog.example").(string), "Hostname for EHLO/HELO response, e.g. mailhog.example")
|
|
||||||
flag.StringVar(&cfg.StorageType, "storage", envconf.FromEnvP("MH_STORAGE", "memory").(string), "Message storage: 'memory' (default), 'mongodb' or 'maildir'")
|
|
||||||
flag.StringVar(&cfg.MongoURI, "mongo-uri", envconf.FromEnvP("MH_MONGO_URI", "127.0.0.1:27017").(string), "MongoDB URI, e.g. 127.0.0.1:27017")
|
|
||||||
flag.StringVar(&cfg.MongoDb, "mongo-db", envconf.FromEnvP("MH_MONGO_DB", "mailhog").(string), "MongoDB database, e.g. mailhog")
|
|
||||||
flag.StringVar(&cfg.MongoColl, "mongo-coll", envconf.FromEnvP("MH_MONGO_COLLECTION", "messages").(string), "MongoDB collection, e.g. messages")
|
|
||||||
flag.StringVar(&cfg.CORSOrigin, "cors-origin", envconf.FromEnvP("MH_CORS_ORIGIN", "").(string), "CORS Access-Control-Allow-Origin header for API endpoints")
|
|
||||||
flag.StringVar(&cfg.MaildirPath, "maildir-path", envconf.FromEnvP("MH_MAILDIR_PATH", "").(string), "Maildir path (if storage type is 'maildir')")
|
|
||||||
flag.BoolVar(&cfg.InviteJim, "invite-jim", envconf.FromEnvP("MH_INVITE_JIM", false).(bool), "Decide whether to invite Jim (beware, he causes trouble)")
|
|
||||||
flag.StringVar(&cfg.OutgoingSMTPFile, "outgoing-smtp", envconf.FromEnvP("MH_OUTGOING_SMTP", "").(string), "JSON file containing outgoing SMTP servers")
|
|
||||||
Jim.RegisterFlags()
|
|
||||||
}
|
|
111
vendor/github.com/mailhog/MailHog-Server/monkey/jim.go
generated
vendored
111
vendor/github.com/mailhog/MailHog-Server/monkey/jim.go
generated
vendored
|
@ -1,111 +0,0 @@
|
||||||
package monkey
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"math/rand"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/ian-kent/linkio"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Jim is a chaos monkey
|
|
||||||
type Jim struct {
|
|
||||||
DisconnectChance float64
|
|
||||||
AcceptChance float64
|
|
||||||
LinkSpeedAffect float64
|
|
||||||
LinkSpeedMin float64
|
|
||||||
LinkSpeedMax float64
|
|
||||||
RejectSenderChance float64
|
|
||||||
RejectRecipientChance float64
|
|
||||||
RejectAuthChance float64
|
|
||||||
logf func(message string, args ...interface{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// RegisterFlags implements ChaosMonkey.RegisterFlags
|
|
||||||
func (j *Jim) RegisterFlags() {
|
|
||||||
flag.Float64Var(&j.DisconnectChance, "jim-disconnect", 0.005, "Chance of disconnect")
|
|
||||||
flag.Float64Var(&j.AcceptChance, "jim-accept", 0.99, "Chance of accept")
|
|
||||||
flag.Float64Var(&j.LinkSpeedAffect, "jim-linkspeed-affect", 0.1, "Chance of affecting link speed")
|
|
||||||
flag.Float64Var(&j.LinkSpeedMin, "jim-linkspeed-min", 1024, "Minimum link speed (in bytes per second)")
|
|
||||||
flag.Float64Var(&j.LinkSpeedMax, "jim-linkspeed-max", 10240, "Maximum link speed (in bytes per second)")
|
|
||||||
flag.Float64Var(&j.RejectSenderChance, "jim-reject-sender", 0.05, "Chance of rejecting a sender (MAIL FROM)")
|
|
||||||
flag.Float64Var(&j.RejectRecipientChance, "jim-reject-recipient", 0.05, "Chance of rejecting a recipient (RCPT TO)")
|
|
||||||
flag.Float64Var(&j.RejectAuthChance, "jim-reject-auth", 0.05, "Chance of rejecting authentication (AUTH)")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Configure implements ChaosMonkey.Configure
|
|
||||||
func (j *Jim) Configure(logf func(string, ...interface{})) {
|
|
||||||
j.logf = logf
|
|
||||||
rand.Seed(time.Now().Unix())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConfigureFrom lets us configure a new Jim from an old one without
|
|
||||||
// having to expose logf (and any other future private vars)
|
|
||||||
func (j *Jim) ConfigureFrom(j2 *Jim) {
|
|
||||||
j.Configure(j2.logf)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept implements ChaosMonkey.Accept
|
|
||||||
func (j *Jim) Accept(conn net.Conn) bool {
|
|
||||||
if rand.Float64() > j.AcceptChance {
|
|
||||||
j.logf("Jim: Rejecting connection\n")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
j.logf("Jim: Allowing connection\n")
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// LinkSpeed implements ChaosMonkey.LinkSpeed
|
|
||||||
func (j *Jim) LinkSpeed() *linkio.Throughput {
|
|
||||||
rand.Seed(time.Now().Unix())
|
|
||||||
if rand.Float64() < j.LinkSpeedAffect {
|
|
||||||
lsDiff := j.LinkSpeedMax - j.LinkSpeedMin
|
|
||||||
lsAffect := j.LinkSpeedMin + (lsDiff * rand.Float64())
|
|
||||||
f := linkio.Throughput(lsAffect) * linkio.BytePerSecond
|
|
||||||
j.logf("Jim: Restricting throughput to %s\n", f)
|
|
||||||
return &f
|
|
||||||
}
|
|
||||||
j.logf("Jim: Allowing unrestricted throughput")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidRCPT implements ChaosMonkey.ValidRCPT
|
|
||||||
func (j *Jim) ValidRCPT(rcpt string) bool {
|
|
||||||
if rand.Float64() < j.RejectRecipientChance {
|
|
||||||
j.logf("Jim: Rejecting recipient %s\n", rcpt)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
j.logf("Jim: Allowing recipient%s\n", rcpt)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidMAIL implements ChaosMonkey.ValidMAIL
|
|
||||||
func (j *Jim) ValidMAIL(mail string) bool {
|
|
||||||
if rand.Float64() < j.RejectSenderChance {
|
|
||||||
j.logf("Jim: Rejecting sender %s\n", mail)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
j.logf("Jim: Allowing sender %s\n", mail)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidAUTH implements ChaosMonkey.ValidAUTH
|
|
||||||
func (j *Jim) ValidAUTH(mechanism string, args ...string) bool {
|
|
||||||
if rand.Float64() < j.RejectAuthChance {
|
|
||||||
j.logf("Jim: Rejecting authentication %s: %s\n", mechanism, args)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
j.logf("Jim: Allowing authentication %s: %s\n", mechanism, args)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Disconnect implements ChaosMonkey.Disconnect
|
|
||||||
func (j *Jim) Disconnect() bool {
|
|
||||||
if rand.Float64() < j.DisconnectChance {
|
|
||||||
j.logf("Jim: Being nasty, kicking them off\n")
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
j.logf("Jim: Being nice, letting them stay\n")
|
|
||||||
return false
|
|
||||||
}
|
|
28
vendor/github.com/mailhog/MailHog-Server/monkey/monkey.go
generated
vendored
28
vendor/github.com/mailhog/MailHog-Server/monkey/monkey.go
generated
vendored
|
@ -1,28 +0,0 @@
|
||||||
package monkey
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/ian-kent/linkio"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ChaosMonkey should be implemented by chaos monkeys!
|
|
||||||
type ChaosMonkey interface {
|
|
||||||
RegisterFlags()
|
|
||||||
Configure(func(string, ...interface{}))
|
|
||||||
|
|
||||||
// Accept is called for each incoming connection. Returning false closes the connection.
|
|
||||||
Accept(conn net.Conn) bool
|
|
||||||
// LinkSpeed sets the maximum connection throughput (in one direction)
|
|
||||||
LinkSpeed() *linkio.Throughput
|
|
||||||
|
|
||||||
// ValidRCPT is called for the RCPT command. Returning false signals an invalid recipient.
|
|
||||||
ValidRCPT(rcpt string) bool
|
|
||||||
// ValidMAIL is called for the MAIL command. Returning false signals an invalid sender.
|
|
||||||
ValidMAIL(mail string) bool
|
|
||||||
// ValidAUTH is called after authentication. Returning false signals invalid authentication.
|
|
||||||
ValidAUTH(mechanism string, args ...string) bool
|
|
||||||
|
|
||||||
// Disconnect is called after every read. Returning true will close the connection.
|
|
||||||
Disconnect() bool
|
|
||||||
}
|
|
163
vendor/github.com/mailhog/MailHog-Server/smtp/session.go
generated
vendored
163
vendor/github.com/mailhog/MailHog-Server/smtp/session.go
generated
vendored
|
@ -1,163 +0,0 @@
|
||||||
package smtp
|
|
||||||
|
|
||||||
// http://www.rfc-editor.org/rfc/rfc5321.txt
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/ian-kent/linkio"
|
|
||||||
"github.com/mailhog/MailHog-Server/monkey"
|
|
||||||
"github.com/mailhog/data"
|
|
||||||
"github.com/mailhog/smtp"
|
|
||||||
"github.com/mailhog/storage"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Session represents a SMTP session using net.TCPConn
|
|
||||||
type Session struct {
|
|
||||||
conn io.ReadWriteCloser
|
|
||||||
proto *smtp.Protocol
|
|
||||||
storage storage.Storage
|
|
||||||
messageChan chan *data.Message
|
|
||||||
remoteAddress string
|
|
||||||
isTLS bool
|
|
||||||
line string
|
|
||||||
link *linkio.Link
|
|
||||||
|
|
||||||
reader io.Reader
|
|
||||||
writer io.Writer
|
|
||||||
monkey monkey.ChaosMonkey
|
|
||||||
}
|
|
||||||
|
|
||||||
// Accept starts a new SMTP session using io.ReadWriteCloser
|
|
||||||
func Accept(remoteAddress string, conn io.ReadWriteCloser, storage storage.Storage, messageChan chan *data.Message, hostname string, monkey monkey.ChaosMonkey) {
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
proto := smtp.NewProtocol()
|
|
||||||
proto.Hostname = hostname
|
|
||||||
var link *linkio.Link
|
|
||||||
reader := io.Reader(conn)
|
|
||||||
writer := io.Writer(conn)
|
|
||||||
if monkey != nil {
|
|
||||||
linkSpeed := monkey.LinkSpeed()
|
|
||||||
if linkSpeed != nil {
|
|
||||||
link = linkio.NewLink(*linkSpeed * linkio.BytePerSecond)
|
|
||||||
reader = link.NewLinkReader(io.Reader(conn))
|
|
||||||
writer = link.NewLinkWriter(io.Writer(conn))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
session := &Session{conn, proto, storage, messageChan, remoteAddress, false, "", link, reader, writer, monkey}
|
|
||||||
proto.LogHandler = session.logf
|
|
||||||
proto.MessageReceivedHandler = session.acceptMessage
|
|
||||||
proto.ValidateSenderHandler = session.validateSender
|
|
||||||
proto.ValidateRecipientHandler = session.validateRecipient
|
|
||||||
proto.ValidateAuthenticationHandler = session.validateAuthentication
|
|
||||||
proto.GetAuthenticationMechanismsHandler = func() []string { return []string{"PLAIN"} }
|
|
||||||
|
|
||||||
session.logf("Starting session")
|
|
||||||
session.Write(proto.Start())
|
|
||||||
for session.Read() == true {
|
|
||||||
if monkey != nil && monkey.Disconnect != nil && monkey.Disconnect() {
|
|
||||||
session.conn.Close()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
session.logf("Session ended")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Session) validateAuthentication(mechanism string, args ...string) (errorReply *smtp.Reply, ok bool) {
|
|
||||||
if c.monkey != nil {
|
|
||||||
ok := c.monkey.ValidAUTH(mechanism, args...)
|
|
||||||
if !ok {
|
|
||||||
// FIXME better error?
|
|
||||||
return smtp.ReplyUnrecognisedCommand(), false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Session) validateRecipient(to string) bool {
|
|
||||||
if c.monkey != nil {
|
|
||||||
ok := c.monkey.ValidRCPT(to)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Session) validateSender(from string) bool {
|
|
||||||
if c.monkey != nil {
|
|
||||||
ok := c.monkey.ValidMAIL(from)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Session) acceptMessage(msg *data.SMTPMessage) (id string, err error) {
|
|
||||||
m := msg.Parse(c.proto.Hostname)
|
|
||||||
c.logf("Storing message %s", m.ID)
|
|
||||||
id, err = c.storage.Store(m)
|
|
||||||
c.messageChan <- m
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Session) logf(message string, args ...interface{}) {
|
|
||||||
message = strings.Join([]string{"[SMTP %s]", message}, " ")
|
|
||||||
args = append([]interface{}{c.remoteAddress}, args...)
|
|
||||||
log.Printf(message, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read reads from the underlying net.TCPConn
|
|
||||||
func (c *Session) Read() bool {
|
|
||||||
buf := make([]byte, 1024)
|
|
||||||
n, err := c.reader.Read(buf)
|
|
||||||
|
|
||||||
if n == 0 {
|
|
||||||
c.logf("Connection closed by remote host\n")
|
|
||||||
io.Closer(c.conn).Close() // not sure this is necessary?
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
c.logf("Error reading from socket: %s\n", err)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
text := string(buf[0:n])
|
|
||||||
logText := strings.Replace(text, "\n", "\\n", -1)
|
|
||||||
logText = strings.Replace(logText, "\r", "\\r", -1)
|
|
||||||
c.logf("Received %d bytes: '%s'\n", n, logText)
|
|
||||||
|
|
||||||
c.line += text
|
|
||||||
|
|
||||||
for strings.Contains(c.line, "\r\n") {
|
|
||||||
line, reply := c.proto.Parse(c.line)
|
|
||||||
c.line = line
|
|
||||||
|
|
||||||
if reply != nil {
|
|
||||||
c.Write(reply)
|
|
||||||
if reply.Status == 221 {
|
|
||||||
io.Closer(c.conn).Close()
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write writes a reply to the underlying net.TCPConn
|
|
||||||
func (c *Session) Write(reply *smtp.Reply) {
|
|
||||||
lines := reply.Lines()
|
|
||||||
for _, l := range lines {
|
|
||||||
logText := strings.Replace(l, "\n", "\\n", -1)
|
|
||||||
logText = strings.Replace(logText, "\r", "\\r", -1)
|
|
||||||
c.logf("Sent %d bytes: '%s'", len(l), logText)
|
|
||||||
c.writer.Write([]byte(l))
|
|
||||||
}
|
|
||||||
}
|
|
43
vendor/github.com/mailhog/MailHog-Server/smtp/smtp.go
generated
vendored
43
vendor/github.com/mailhog/MailHog-Server/smtp/smtp.go
generated
vendored
|
@ -1,43 +0,0 @@
|
||||||
package smtp
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
"github.com/mailhog/MailHog-Server/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Listen(cfg *config.Config, exitCh chan int) *net.TCPListener {
|
|
||||||
log.Printf("[SMTP] Binding to address: %s\n", cfg.SMTPBindAddr)
|
|
||||||
ln, err := net.Listen("tcp", cfg.SMTPBindAddr)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("[SMTP] Error listening on socket: %s\n", err)
|
|
||||||
}
|
|
||||||
defer ln.Close()
|
|
||||||
|
|
||||||
for {
|
|
||||||
conn, err := ln.Accept()
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[SMTP] Error accepting connection: %s\n", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.Monkey != nil {
|
|
||||||
ok := cfg.Monkey.Accept(conn)
|
|
||||||
if !ok {
|
|
||||||
conn.Close()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
go Accept(
|
|
||||||
conn.(*net.TCPConn).RemoteAddr().String(),
|
|
||||||
io.ReadWriteCloser(conn),
|
|
||||||
cfg.Storage,
|
|
||||||
cfg.MessageChan,
|
|
||||||
cfg.Hostname,
|
|
||||||
cfg.Monkey,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
73
vendor/github.com/mailhog/MailHog-Server/websockets/connection.go
generated
vendored
73
vendor/github.com/mailhog/MailHog-Server/websockets/connection.go
generated
vendored
|
@ -1,73 +0,0 @@
|
||||||
package websockets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Time allowed to write a message to the peer.
|
|
||||||
writeWait = 10 * time.Second
|
|
||||||
// Time allowed to read the next pong message from the peer.
|
|
||||||
pongWait = 60 * time.Second
|
|
||||||
// Send pings to peer with this period. Must be less than pongWait.
|
|
||||||
pingPeriod = (pongWait * 9) / 10
|
|
||||||
// Maximum message size allowed from peer. Set to minimum allowed value as we don't expect the client to send non-control messages.
|
|
||||||
maxMessageSize = 1
|
|
||||||
)
|
|
||||||
|
|
||||||
type connection struct {
|
|
||||||
hub *Hub
|
|
||||||
ws *websocket.Conn
|
|
||||||
send chan interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *connection) readLoop() {
|
|
||||||
defer func() {
|
|
||||||
c.hub.unregisterChan <- c
|
|
||||||
c.ws.Close()
|
|
||||||
}()
|
|
||||||
c.ws.SetReadLimit(maxMessageSize)
|
|
||||||
c.ws.SetReadDeadline(time.Now().Add(pongWait))
|
|
||||||
c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
|
|
||||||
for {
|
|
||||||
if _, _, err := c.ws.NextReader(); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *connection) writeLoop() {
|
|
||||||
ticker := time.NewTicker(pingPeriod)
|
|
||||||
defer func() {
|
|
||||||
ticker.Stop()
|
|
||||||
c.ws.Close()
|
|
||||||
}()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case message, ok := <-c.send:
|
|
||||||
if !ok {
|
|
||||||
c.writeControl(websocket.CloseMessage)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := c.writeJSON(message); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
case <-ticker.C:
|
|
||||||
if err := c.writeControl(websocket.PingMessage); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *connection) writeJSON(message interface{}) error {
|
|
||||||
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
|
|
||||||
return c.ws.WriteJSON(message)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *connection) writeControl(messageType int) error {
|
|
||||||
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
|
|
||||||
return c.ws.WriteMessage(messageType, []byte{})
|
|
||||||
}
|
|
76
vendor/github.com/mailhog/MailHog-Server/websockets/hub.go
generated
vendored
76
vendor/github.com/mailhog/MailHog-Server/websockets/hub.go
generated
vendored
|
@ -1,76 +0,0 @@
|
||||||
package websockets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
|
||||||
"github.com/ian-kent/go-log/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Hub struct {
|
|
||||||
upgrader websocket.Upgrader
|
|
||||||
connections map[*connection]bool
|
|
||||||
messages chan interface{}
|
|
||||||
registerChan chan *connection
|
|
||||||
unregisterChan chan *connection
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHub() *Hub {
|
|
||||||
hub := &Hub{
|
|
||||||
upgrader: websocket.Upgrader{
|
|
||||||
ReadBufferSize: 256,
|
|
||||||
WriteBufferSize: 4096,
|
|
||||||
CheckOrigin: func(r *http.Request) bool {
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
},
|
|
||||||
connections: make(map[*connection]bool),
|
|
||||||
messages: make(chan interface{}),
|
|
||||||
registerChan: make(chan *connection),
|
|
||||||
unregisterChan: make(chan *connection),
|
|
||||||
}
|
|
||||||
go hub.run()
|
|
||||||
return hub
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) run() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case c := <-h.registerChan:
|
|
||||||
h.connections[c] = true
|
|
||||||
case c := <-h.unregisterChan:
|
|
||||||
h.unregister(c)
|
|
||||||
case m := <-h.messages:
|
|
||||||
for c := range h.connections {
|
|
||||||
select {
|
|
||||||
case c.send <- m:
|
|
||||||
default:
|
|
||||||
h.unregister(c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) unregister(c *connection) {
|
|
||||||
if _, ok := h.connections[c]; ok {
|
|
||||||
close(c.send)
|
|
||||||
delete(h.connections, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) Serve(w http.ResponseWriter, r *http.Request) {
|
|
||||||
ws, err := h.upgrader.Upgrade(w, r, nil)
|
|
||||||
if err != nil {
|
|
||||||
log.Println(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c := &connection{hub: h, ws: ws, send: make(chan interface{}, 256)}
|
|
||||||
h.registerChan <- c
|
|
||||||
go c.writeLoop()
|
|
||||||
go c.readLoop()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Hub) Broadcast(data interface{}) {
|
|
||||||
h.messages <- data
|
|
||||||
}
|
|
753
vendor/github.com/mailhog/MailHog-UI/assets/assets.go
generated
vendored
753
vendor/github.com/mailhog/MailHog-UI/assets/assets.go
generated
vendored
File diff suppressed because one or more lines are too long
32
vendor/github.com/mailhog/MailHog-UI/config/config.go
generated
vendored
32
vendor/github.com/mailhog/MailHog-UI/config/config.go
generated
vendored
|
@ -1,32 +0,0 @@
|
||||||
package config
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
|
|
||||||
"github.com/ian-kent/envconf"
|
|
||||||
)
|
|
||||||
|
|
||||||
func DefaultConfig() *Config {
|
|
||||||
return &Config{
|
|
||||||
APIHost: "",
|
|
||||||
UIBindAddr: "0.0.0.0:8025",
|
|
||||||
WebPath: "",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Config struct {
|
|
||||||
APIHost string
|
|
||||||
UIBindAddr string
|
|
||||||
WebPath string
|
|
||||||
}
|
|
||||||
|
|
||||||
var cfg = DefaultConfig()
|
|
||||||
|
|
||||||
func Configure() *Config {
|
|
||||||
return cfg
|
|
||||||
}
|
|
||||||
|
|
||||||
func RegisterFlags() {
|
|
||||||
flag.StringVar(&cfg.APIHost, "api-host", envconf.FromEnvP("MH_API_HOST", "").(string), "API URL for MailHog UI to connect to, e.g. http://some.host:1234")
|
|
||||||
flag.StringVar(&cfg.UIBindAddr, "ui-bind-addr", envconf.FromEnvP("MH_UI_BIND_ADDR", "0.0.0.0:8025").(string), "HTTP bind interface and port for UI, e.g. 0.0.0.0:8025 or just :8025")
|
|
||||||
}
|
|
117
vendor/github.com/mailhog/MailHog-UI/web/web.go
generated
vendored
117
vendor/github.com/mailhog/MailHog-UI/web/web.go
generated
vendored
|
@ -1,117 +0,0 @@
|
||||||
package web
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"html/template"
|
|
||||||
"log"
|
|
||||||
"mime"
|
|
||||||
"net/http"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gorilla/pat"
|
|
||||||
"github.com/mailhog/MailHog-UI/config"
|
|
||||||
)
|
|
||||||
|
|
||||||
var APIHost string
|
|
||||||
var WebPath string
|
|
||||||
|
|
||||||
type Web struct {
|
|
||||||
config *config.Config
|
|
||||||
asset func(string) ([]byte, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateWeb(cfg *config.Config, pat *pat.Router, asset func(string) ([]byte, error)) *Web {
|
|
||||||
web := &Web{
|
|
||||||
config: cfg,
|
|
||||||
asset: asset,
|
|
||||||
}
|
|
||||||
|
|
||||||
WebPath = cfg.WebPath
|
|
||||||
|
|
||||||
log.Printf("Serving under http://%s%s/", cfg.UIBindAddr, WebPath)
|
|
||||||
|
|
||||||
pat.Path(WebPath + "/images/{file:.*}").Methods("GET").HandlerFunc(web.Static("assets/images/{{file}}"))
|
|
||||||
pat.Path(WebPath + "/css/{file:.*}").Methods("GET").HandlerFunc(web.Static("assets/css/{{file}}"))
|
|
||||||
pat.Path(WebPath + "/js/{file:.*}").Methods("GET").HandlerFunc(web.Static("assets/js/{{file}}"))
|
|
||||||
pat.Path(WebPath + "/fonts/{file:.*}").Methods("GET").HandlerFunc(web.Static("assets/fonts/{{file}}"))
|
|
||||||
pat.StrictSlash(true).Path(WebPath + "/").Methods("GET").HandlerFunc(web.Index())
|
|
||||||
|
|
||||||
return web
|
|
||||||
}
|
|
||||||
|
|
||||||
func (web Web) Static(pattern string) func(http.ResponseWriter, *http.Request) {
|
|
||||||
return func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
fp := strings.TrimSuffix(pattern, "{{file}}") + req.URL.Query().Get(":file")
|
|
||||||
if b, err := web.asset(fp); err == nil {
|
|
||||||
ext := filepath.Ext(fp)
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", mime.TypeByExtension(ext))
|
|
||||||
w.WriteHeader(200)
|
|
||||||
w.Write(b)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Printf("[UI] File not found: %s", fp)
|
|
||||||
w.WriteHeader(404)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (web Web) Index() func(http.ResponseWriter, *http.Request) {
|
|
||||||
tmpl := template.New("index.html")
|
|
||||||
tmpl.Delims("[:", ":]")
|
|
||||||
|
|
||||||
asset, err := web.asset("assets/templates/index.html")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("[UI] Error loading index.html: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tmpl, err = tmpl.Parse(string(asset))
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("[UI] Error parsing index.html: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
layout := template.New("layout.html")
|
|
||||||
layout.Delims("[:", ":]")
|
|
||||||
|
|
||||||
asset, err = web.asset("assets/templates/layout.html")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("[UI] Error loading layout.html: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
layout, err = layout.Parse(string(asset))
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("[UI] Error parsing layout.html: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return func(w http.ResponseWriter, req *http.Request) {
|
|
||||||
data := map[string]interface{}{
|
|
||||||
"config": web.config,
|
|
||||||
"Page": "Browse",
|
|
||||||
"APIHost": APIHost,
|
|
||||||
}
|
|
||||||
|
|
||||||
b := new(bytes.Buffer)
|
|
||||||
err := tmpl.Execute(b, data)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[UI] Error executing template: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
data["Content"] = template.HTML(b.String())
|
|
||||||
|
|
||||||
b = new(bytes.Buffer)
|
|
||||||
err = layout.Execute(b, data)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[UI] Error executing template: %s", err)
|
|
||||||
w.WriteHeader(500)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
||||||
w.WriteHeader(200)
|
|
||||||
w.Write(b.Bytes())
|
|
||||||
}
|
|
||||||
}
|
|
184
vendor/github.com/mailhog/storage/maildir.go
generated
vendored
Normal file
184
vendor/github.com/mailhog/storage/maildir.go
generated
vendored
Normal file
|
@ -0,0 +1,184 @@
|
||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io/ioutil"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/mailhog/data"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Maildir is a maildir storage backend
|
||||||
|
type Maildir struct {
|
||||||
|
Path string
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateMaildir creates a new maildir storage backend
|
||||||
|
func CreateMaildir(path string) *Maildir {
|
||||||
|
if len(path) == 0 {
|
||||||
|
dir, err := ioutil.TempDir("", "mailhog")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
path = dir
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
err := os.MkdirAll(path, 0770)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Println("Maildir path is", path)
|
||||||
|
return &Maildir{
|
||||||
|
Path: path,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store stores a message and returns its storage ID
|
||||||
|
func (maildir *Maildir) Store(m *data.Message) (string, error) {
|
||||||
|
b, err := ioutil.ReadAll(m.Raw.Bytes())
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
err = ioutil.WriteFile(filepath.Join(maildir.Path, string(m.ID)), b, 0660)
|
||||||
|
return string(m.ID), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Count returns the number of stored messages
|
||||||
|
func (maildir *Maildir) Count() int {
|
||||||
|
// FIXME may be wrong, ../. ?
|
||||||
|
// and handle error?
|
||||||
|
dir, err := os.Open(maildir.Path)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
defer dir.Close()
|
||||||
|
n, _ := dir.Readdirnames(0)
|
||||||
|
return len(n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search finds messages matching the query
|
||||||
|
func (maildir *Maildir) Search(kind, query string, start, limit int) (*data.Messages, int, error) {
|
||||||
|
query = strings.ToLower(query)
|
||||||
|
var filteredMessages = make([]data.Message, 0)
|
||||||
|
|
||||||
|
var matched int
|
||||||
|
|
||||||
|
err := filepath.Walk(maildir.Path, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if limit > 0 && len(filteredMessages) >= limit {
|
||||||
|
return errors.New("reached limit")
|
||||||
|
}
|
||||||
|
|
||||||
|
if info.IsDir() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
msg, err := maildir.Load(info.Name())
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
switch kind {
|
||||||
|
case "to":
|
||||||
|
for _, t := range msg.To {
|
||||||
|
if strings.Contains(strings.ToLower(t.Mailbox+"@"+t.Domain), query) {
|
||||||
|
if start > matched {
|
||||||
|
matched++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
filteredMessages = append(filteredMessages, *msg)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "from":
|
||||||
|
if strings.Contains(strings.ToLower(msg.From.Mailbox+"@"+msg.From.Domain), query) {
|
||||||
|
if start > matched {
|
||||||
|
matched++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
filteredMessages = append(filteredMessages, *msg)
|
||||||
|
}
|
||||||
|
case "containing":
|
||||||
|
if strings.Contains(strings.ToLower(msg.Raw.Data), query) {
|
||||||
|
if start > matched {
|
||||||
|
matched++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
filteredMessages = append(filteredMessages, *msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs := data.Messages(filteredMessages)
|
||||||
|
return &msgs, len(filteredMessages), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List lists stored messages by index
|
||||||
|
func (maildir *Maildir) List(start, limit int) (*data.Messages, error) {
|
||||||
|
log.Println("Listing messages in", maildir.Path)
|
||||||
|
messages := make([]data.Message, 0)
|
||||||
|
|
||||||
|
dir, err := os.Open(maildir.Path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer dir.Close()
|
||||||
|
|
||||||
|
n, err := dir.Readdir(0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, fileinfo := range n {
|
||||||
|
b, err := ioutil.ReadFile(filepath.Join(maildir.Path, fileinfo.Name()))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
msg := data.FromBytes(b)
|
||||||
|
// FIXME domain
|
||||||
|
m := *msg.Parse("mailhog.example")
|
||||||
|
m.ID = data.MessageID(fileinfo.Name())
|
||||||
|
m.Created = fileinfo.ModTime()
|
||||||
|
messages = append(messages, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("Found %d messages", len(messages))
|
||||||
|
msgs := data.Messages(messages)
|
||||||
|
return &msgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteOne deletes an individual message by storage ID
|
||||||
|
func (maildir *Maildir) DeleteOne(id string) error {
|
||||||
|
return os.Remove(filepath.Join(maildir.Path, id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAll deletes all in memory messages
|
||||||
|
func (maildir *Maildir) DeleteAll() error {
|
||||||
|
err := os.RemoveAll(maildir.Path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Mkdir(maildir.Path, 0770)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load returns an individual message by storage ID
|
||||||
|
func (maildir *Maildir) Load(id string) (*data.Message, error) {
|
||||||
|
b, err := ioutil.ReadFile(filepath.Join(maildir.Path, id))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// FIXME domain
|
||||||
|
m := data.FromBytes(b).Parse("mailhog.example")
|
||||||
|
m.ID = data.MessageID(id)
|
||||||
|
return m, nil
|
||||||
|
}
|
199
vendor/github.com/mailhog/storage/memory.go
generated
vendored
Normal file
199
vendor/github.com/mailhog/storage/memory.go
generated
vendored
Normal file
|
@ -0,0 +1,199 @@
|
||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/mailhog/data"
|
||||||
|
)
|
||||||
|
|
||||||
|
// InMemory is an in memory storage backend
|
||||||
|
type InMemory struct {
|
||||||
|
MessageIDIndex map[string]int
|
||||||
|
Messages []*data.Message
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateInMemory creates a new in memory storage backend
|
||||||
|
func CreateInMemory() *InMemory {
|
||||||
|
return &InMemory{
|
||||||
|
MessageIDIndex: make(map[string]int),
|
||||||
|
Messages: make([]*data.Message, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store stores a message and returns its storage ID
|
||||||
|
func (memory *InMemory) Store(m *data.Message) (string, error) {
|
||||||
|
memory.mu.Lock()
|
||||||
|
defer memory.mu.Unlock()
|
||||||
|
memory.Messages = append(memory.Messages, m)
|
||||||
|
memory.MessageIDIndex[string(m.ID)] = len(memory.Messages) - 1
|
||||||
|
return string(m.ID), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Count returns the number of stored messages
|
||||||
|
func (memory *InMemory) Count() int {
|
||||||
|
return len(memory.Messages)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search finds messages matching the query
|
||||||
|
func (memory *InMemory) Search(kind, query string, start, limit int) (*data.Messages, int, error) {
|
||||||
|
// FIXME needs optimising, or replacing with a proper db!
|
||||||
|
query = strings.ToLower(query)
|
||||||
|
var filteredMessages = make([]*data.Message, 0)
|
||||||
|
for _, m := range memory.Messages {
|
||||||
|
doAppend := false
|
||||||
|
|
||||||
|
switch kind {
|
||||||
|
case "to":
|
||||||
|
for _, to := range m.To {
|
||||||
|
if strings.Contains(strings.ToLower(to.Mailbox+"@"+to.Domain), query) {
|
||||||
|
doAppend = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !doAppend {
|
||||||
|
if hdr, ok := m.Content.Headers["To"]; ok {
|
||||||
|
for _, to := range hdr {
|
||||||
|
if strings.Contains(strings.ToLower(to), query) {
|
||||||
|
doAppend = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "from":
|
||||||
|
if strings.Contains(strings.ToLower(m.From.Mailbox+"@"+m.From.Domain), query) {
|
||||||
|
doAppend = true
|
||||||
|
}
|
||||||
|
if !doAppend {
|
||||||
|
if hdr, ok := m.Content.Headers["From"]; ok {
|
||||||
|
for _, from := range hdr {
|
||||||
|
if strings.Contains(strings.ToLower(from), query) {
|
||||||
|
doAppend = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "containing":
|
||||||
|
if strings.Contains(strings.ToLower(m.Content.Body), query) {
|
||||||
|
doAppend = true
|
||||||
|
}
|
||||||
|
if !doAppend {
|
||||||
|
for _, hdr := range m.Content.Headers {
|
||||||
|
for _, v := range hdr {
|
||||||
|
if strings.Contains(strings.ToLower(v), query) {
|
||||||
|
doAppend = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if doAppend {
|
||||||
|
filteredMessages = append(filteredMessages, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var messages = make([]data.Message, 0)
|
||||||
|
|
||||||
|
if len(filteredMessages) == 0 || start > len(filteredMessages) {
|
||||||
|
msgs := data.Messages(messages)
|
||||||
|
return &msgs, 0, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if start+limit > len(filteredMessages) {
|
||||||
|
limit = len(filteredMessages) - start
|
||||||
|
}
|
||||||
|
|
||||||
|
start = len(filteredMessages) - start - 1
|
||||||
|
end := start - limit
|
||||||
|
|
||||||
|
if start < 0 {
|
||||||
|
start = 0
|
||||||
|
}
|
||||||
|
if end < -1 {
|
||||||
|
end = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := start; i > end; i-- {
|
||||||
|
//for _, m := range memory.MessageIndex[start:end] {
|
||||||
|
messages = append(messages, *filteredMessages[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs := data.Messages(messages)
|
||||||
|
return &msgs, len(filteredMessages), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List lists stored messages by index
|
||||||
|
func (memory *InMemory) List(start int, limit int) (*data.Messages, error) {
|
||||||
|
var messages = make([]data.Message, 0)
|
||||||
|
|
||||||
|
if len(memory.Messages) == 0 || start > len(memory.Messages) {
|
||||||
|
msgs := data.Messages(messages)
|
||||||
|
return &msgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if start+limit > len(memory.Messages) {
|
||||||
|
limit = len(memory.Messages) - start
|
||||||
|
}
|
||||||
|
|
||||||
|
start = len(memory.Messages) - start - 1
|
||||||
|
end := start - limit
|
||||||
|
|
||||||
|
if start < 0 {
|
||||||
|
start = 0
|
||||||
|
}
|
||||||
|
if end < -1 {
|
||||||
|
end = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := start; i > end; i-- {
|
||||||
|
//for _, m := range memory.MessageIndex[start:end] {
|
||||||
|
messages = append(messages, *memory.Messages[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
msgs := data.Messages(messages)
|
||||||
|
return &msgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteOne deletes an individual message by storage ID
|
||||||
|
func (memory *InMemory) DeleteOne(id string) error {
|
||||||
|
memory.mu.Lock()
|
||||||
|
defer memory.mu.Unlock()
|
||||||
|
|
||||||
|
var index int
|
||||||
|
var ok bool
|
||||||
|
|
||||||
|
if index, ok = memory.MessageIDIndex[id]; !ok && true {
|
||||||
|
return errors.New("message not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(memory.MessageIDIndex, id)
|
||||||
|
for k, v := range memory.MessageIDIndex {
|
||||||
|
if v > index {
|
||||||
|
memory.MessageIDIndex[k] = v - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
memory.Messages = append(memory.Messages[:index], memory.Messages[index+1:]...)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAll deletes all in memory messages
|
||||||
|
func (memory *InMemory) DeleteAll() error {
|
||||||
|
memory.mu.Lock()
|
||||||
|
defer memory.mu.Unlock()
|
||||||
|
memory.Messages = make([]*data.Message, 0)
|
||||||
|
memory.MessageIDIndex = make(map[string]int)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load returns an individual message by storage ID
|
||||||
|
func (memory *InMemory) Load(id string) (*data.Message, error) {
|
||||||
|
if idx, ok := memory.MessageIDIndex[id]; ok {
|
||||||
|
return memory.Messages[idx], nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
122
vendor/github.com/mailhog/storage/mongodb.go
generated
vendored
Normal file
122
vendor/github.com/mailhog/storage/mongodb.go
generated
vendored
Normal file
|
@ -0,0 +1,122 @@
|
||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/mailhog/data"
|
||||||
|
"gopkg.in/mgo.v2"
|
||||||
|
"gopkg.in/mgo.v2/bson"
|
||||||
|
"log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MongoDB represents MongoDB backed storage backend
|
||||||
|
type MongoDB struct {
|
||||||
|
Session *mgo.Session
|
||||||
|
Collection *mgo.Collection
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateMongoDB creates a MongoDB backed storage backend
|
||||||
|
func CreateMongoDB(uri, db, coll string) *MongoDB {
|
||||||
|
log.Printf("Connecting to MongoDB: %s\n", uri)
|
||||||
|
session, err := mgo.Dial(uri)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error connecting to MongoDB: %s", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
err = session.DB(db).C(coll).EnsureIndexKey("created")
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed creating index: %s", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &MongoDB{
|
||||||
|
Session: session,
|
||||||
|
Collection: session.DB(db).C(coll),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store stores a message in MongoDB and returns its storage ID
|
||||||
|
func (mongo *MongoDB) Store(m *data.Message) (string, error) {
|
||||||
|
err := mongo.Collection.Insert(m)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error inserting message: %s", err)
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(m.ID), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Count returns the number of stored messages
|
||||||
|
func (mongo *MongoDB) Count() int {
|
||||||
|
c, _ := mongo.Collection.Count()
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search finds messages matching the query
|
||||||
|
func (mongo *MongoDB) Search(kind, query string, start, limit int) (*data.Messages, int, error) {
|
||||||
|
messages := &data.Messages{}
|
||||||
|
var count = 0
|
||||||
|
var field = "raw.data"
|
||||||
|
switch kind {
|
||||||
|
case "to":
|
||||||
|
field = "raw.to"
|
||||||
|
case "from":
|
||||||
|
field = "raw.from"
|
||||||
|
}
|
||||||
|
err := mongo.Collection.Find(bson.M{field: bson.RegEx{Pattern: query, Options: "i"}}).Skip(start).Limit(limit).Sort("-created").Select(bson.M{
|
||||||
|
"id": 1,
|
||||||
|
"_id": 1,
|
||||||
|
"from": 1,
|
||||||
|
"to": 1,
|
||||||
|
"content.headers": 1,
|
||||||
|
"content.size": 1,
|
||||||
|
"created": 1,
|
||||||
|
"raw": 1,
|
||||||
|
}).All(messages)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error loading messages: %s", err)
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
count, _ = mongo.Collection.Find(bson.M{field: bson.RegEx{Pattern: query, Options: "i"}}).Count()
|
||||||
|
|
||||||
|
return messages, count, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// List returns a list of messages by index
|
||||||
|
func (mongo *MongoDB) List(start int, limit int) (*data.Messages, error) {
|
||||||
|
messages := &data.Messages{}
|
||||||
|
err := mongo.Collection.Find(bson.M{}).Skip(start).Limit(limit).Sort("-created").Select(bson.M{
|
||||||
|
"id": 1,
|
||||||
|
"_id": 1,
|
||||||
|
"from": 1,
|
||||||
|
"to": 1,
|
||||||
|
"content.headers": 1,
|
||||||
|
"content.size": 1,
|
||||||
|
"created": 1,
|
||||||
|
"raw": 1,
|
||||||
|
}).All(messages)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error loading messages: %s", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return messages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteOne deletes an individual message by storage ID
|
||||||
|
func (mongo *MongoDB) DeleteOne(id string) error {
|
||||||
|
_, err := mongo.Collection.RemoveAll(bson.M{"id": id})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteAll deletes all messages stored in MongoDB
|
||||||
|
func (mongo *MongoDB) DeleteAll() error {
|
||||||
|
_, err := mongo.Collection.RemoveAll(bson.M{})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads an individual message by storage ID
|
||||||
|
func (mongo *MongoDB) Load(id string) (*data.Message, error) {
|
||||||
|
result := &data.Message{}
|
||||||
|
err := mongo.Collection.Find(bson.M{"id": id}).One(&result)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error loading message: %s", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
14
vendor/github.com/mailhog/storage/storage.go
generated
vendored
Normal file
14
vendor/github.com/mailhog/storage/storage.go
generated
vendored
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
package storage
|
||||||
|
|
||||||
|
import "github.com/mailhog/data"
|
||||||
|
|
||||||
|
// Storage represents a storage backend
|
||||||
|
type Storage interface {
|
||||||
|
Store(m *data.Message) (string, error)
|
||||||
|
List(start, limit int) (*data.Messages, error)
|
||||||
|
Search(kind, query string, start, limit int) (*data.Messages, int, error)
|
||||||
|
Count() int
|
||||||
|
DeleteOne(id string) error
|
||||||
|
DeleteAll() error
|
||||||
|
Load(id string) (*data.Message, error)
|
||||||
|
}
|
12
vendor/github.com/smartystreets/assertions/CONTRIBUTING.md
generated
vendored
Normal file
12
vendor/github.com/smartystreets/assertions/CONTRIBUTING.md
generated
vendored
Normal 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...
|
|
@ -1,6 +1,4 @@
|
||||||
The MIT License (MIT)
|
Copyright (c) 2016 SmartyStreets, LLC
|
||||||
|
|
||||||
Copyright (c) 2014 - 2016 Ian Kent
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
@ -19,3 +17,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
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
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
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.
|
575
vendor/github.com/smartystreets/assertions/README.md
generated
vendored
Normal file
575
vendor/github.com/smartystreets/assertions/README.md
generated
vendored
Normal 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
|
||||||
|
}
|
||||||
|
```
|
244
vendor/github.com/smartystreets/assertions/collections.go
generated
vendored
Normal file
244
vendor/github.com/smartystreets/assertions/collections.go
generated
vendored
Normal file
|
@ -0,0 +1,244 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
|
||||||
|
"github.com/smartystreets/assertions/internal/oglematchers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ShouldContain receives exactly two parameters. The first is a slice and the
|
||||||
|
// second is a proposed member. Membership is determined using ShouldEqual.
|
||||||
|
func ShouldContain(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
typeName := reflect.TypeOf(actual)
|
||||||
|
|
||||||
|
if fmt.Sprintf("%v", matchError) == "which is not a slice or array" {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldHaveContained, typeName, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotContain receives exactly two parameters. The first is a slice and the
|
||||||
|
// second is a proposed member. Membership is determinied using ShouldEqual.
|
||||||
|
func ShouldNotContain(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
typeName := reflect.TypeOf(actual)
|
||||||
|
|
||||||
|
if matchError := oglematchers.Contains(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
if fmt.Sprintf("%v", matchError) == "which is not a slice or array" {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenAValidCollection, typeName)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldNotHaveContained, typeName, expected[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// the collection (using ShouldEqual).
|
||||||
|
func ShouldBeIn(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := atLeast(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(expected) == 1 {
|
||||||
|
return shouldBeIn(actual, expected[0])
|
||||||
|
}
|
||||||
|
return shouldBeIn(actual, expected)
|
||||||
|
}
|
||||||
|
func shouldBeIn(actual interface{}, expected interface{}) string {
|
||||||
|
if matchError := oglematchers.Contains(actual).Matches(expected); matchError != nil {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenIn, actual, reflect.TypeOf(expected))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeIn receives at least 2 parameters. The first is a proposed member of the collection
|
||||||
|
// that is passed in either as the second parameter, or of the collection that is comprised
|
||||||
|
// of all the remaining parameters. This assertion ensures that the proposed member is NOT in
|
||||||
|
// the collection (using ShouldEqual).
|
||||||
|
func ShouldNotBeIn(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := atLeast(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(expected) == 1 {
|
||||||
|
return shouldNotBeIn(actual, expected[0])
|
||||||
|
}
|
||||||
|
return shouldNotBeIn(actual, expected)
|
||||||
|
}
|
||||||
|
func shouldNotBeIn(actual interface{}, expected interface{}) string {
|
||||||
|
if matchError := oglematchers.Contains(actual).Matches(expected); matchError == nil {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenIn, actual, reflect.TypeOf(expected))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeEmpty receives a single parameter (actual) and determines whether or not
|
||||||
|
// calling len(actual) would return `0`. It obeys the rules specified by the len
|
||||||
|
// function for determining length: http://golang.org/pkg/builtin/#len
|
||||||
|
func ShouldBeEmpty(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if actual == nil {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
value := reflect.ValueOf(actual)
|
||||||
|
switch value.Kind() {
|
||||||
|
case reflect.Slice:
|
||||||
|
if value.Len() == 0 {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
case reflect.Chan:
|
||||||
|
if value.Len() == 0 {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
case reflect.Map:
|
||||||
|
if value.Len() == 0 {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
case reflect.String:
|
||||||
|
if value.Len() == 0 {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
case reflect.Ptr:
|
||||||
|
elem := value.Elem()
|
||||||
|
kind := elem.Kind()
|
||||||
|
if (kind == reflect.Slice || kind == reflect.Array) && elem.Len() == 0 {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf(shouldHaveBeenEmpty, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeEmpty receives a single parameter (actual) and determines whether or not
|
||||||
|
// calling len(actual) would return a value greater than zero. It obeys the rules
|
||||||
|
// specified by the `len` function for determining length: http://golang.org/pkg/builtin/#len
|
||||||
|
func ShouldNotBeEmpty(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if empty := ShouldBeEmpty(actual, expected...); empty != success {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenEmpty, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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))
|
||||||
|
}
|
105
vendor/github.com/smartystreets/assertions/doc.go
generated
vendored
Normal file
105
vendor/github.com/smartystreets/assertions/doc.go
generated
vendored
Normal 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 usage 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
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////////////////////////
|
280
vendor/github.com/smartystreets/assertions/equality.go
generated
vendored
Normal file
280
vendor/github.com/smartystreets/assertions/equality.go
generated
vendored
Normal file
|
@ -0,0 +1,280 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/smartystreets/assertions/internal/go-render/render"
|
||||||
|
"github.com/smartystreets/assertions/internal/oglematchers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// default acceptable delta for ShouldAlmostEqual
|
||||||
|
const defaultDelta = 0.0000000001
|
||||||
|
|
||||||
|
// ShouldEqual receives exactly two parameters and does an equality check.
|
||||||
|
func ShouldEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
if message := need(1, expected); message != success {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
return shouldEqual(actual, expected[0])
|
||||||
|
}
|
||||||
|
func shouldEqual(actual, expected interface{}) (message string) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
message = serializer.serialize(expected, actual, fmt.Sprintf(shouldHaveBeenEqual, expected, actual))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if matchError := oglematchers.Equals(expected).Matches(actual); matchError != nil {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotEqual receives exactly two parameters and does an inequality check.
|
||||||
|
func ShouldNotEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if ShouldEqual(actual, expected[0]) == success {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenEqual, actual, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldAlmostEqual makes sure that two parameters are close enough to being equal.
|
||||||
|
// The acceptable delta may be specified with a third argument,
|
||||||
|
// or a very small default delta will be used.
|
||||||
|
func ShouldAlmostEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...)
|
||||||
|
|
||||||
|
if err != "" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if math.Abs(actualFloat-expectedFloat) <= deltaFloat {
|
||||||
|
return success
|
||||||
|
} else {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenAlmostEqual, actualFloat, expectedFloat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotAlmostEqual is the inverse of ShouldAlmostEqual
|
||||||
|
func ShouldNotAlmostEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
actualFloat, expectedFloat, deltaFloat, err := cleanAlmostEqualInput(actual, expected...)
|
||||||
|
|
||||||
|
if err != "" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if math.Abs(actualFloat-expectedFloat) > deltaFloat {
|
||||||
|
return success
|
||||||
|
} else {
|
||||||
|
return fmt.Sprintf(shouldHaveNotBeenAlmostEqual, actualFloat, expectedFloat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanAlmostEqualInput(actual interface{}, expected ...interface{}) (float64, float64, float64, string) {
|
||||||
|
deltaFloat := 0.0000000001
|
||||||
|
|
||||||
|
if len(expected) == 0 {
|
||||||
|
return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided neither)"
|
||||||
|
} else if len(expected) == 2 {
|
||||||
|
delta, err := getFloat(expected[1])
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return 0.0, 0.0, 0.0, "delta must be a numerical type"
|
||||||
|
}
|
||||||
|
|
||||||
|
deltaFloat = delta
|
||||||
|
} else if len(expected) > 2 {
|
||||||
|
return 0.0, 0.0, 0.0, "This assertion requires exactly one comparison value and an optional delta (you provided more values)"
|
||||||
|
}
|
||||||
|
|
||||||
|
actualFloat, err := getFloat(actual)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return 0.0, 0.0, 0.0, err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedFloat, err := getFloat(expected[0])
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return 0.0, 0.0, 0.0, err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
return actualFloat, expectedFloat, deltaFloat, ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns the float value of any real number, or error if it is not a numerical type
|
||||||
|
func getFloat(num interface{}) (float64, error) {
|
||||||
|
numValue := reflect.ValueOf(num)
|
||||||
|
numKind := numValue.Kind()
|
||||||
|
|
||||||
|
if numKind == reflect.Int ||
|
||||||
|
numKind == reflect.Int8 ||
|
||||||
|
numKind == reflect.Int16 ||
|
||||||
|
numKind == reflect.Int32 ||
|
||||||
|
numKind == reflect.Int64 {
|
||||||
|
return float64(numValue.Int()), nil
|
||||||
|
} else if numKind == reflect.Uint ||
|
||||||
|
numKind == reflect.Uint8 ||
|
||||||
|
numKind == reflect.Uint16 ||
|
||||||
|
numKind == reflect.Uint32 ||
|
||||||
|
numKind == reflect.Uint64 {
|
||||||
|
return float64(numValue.Uint()), nil
|
||||||
|
} else if numKind == reflect.Float32 ||
|
||||||
|
numKind == reflect.Float64 {
|
||||||
|
return numValue.Float(), nil
|
||||||
|
} else {
|
||||||
|
return 0.0, errors.New("must be a numerical type, but was " + numKind.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldResemble receives exactly two parameters and does a deep equal check (see reflect.DeepEqual)
|
||||||
|
func ShouldResemble(actual interface{}, expected ...interface{}) string {
|
||||||
|
if message := need(1, expected); message != success {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
|
||||||
|
if matchError := oglematchers.DeepEquals(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
return serializer.serializeDetailed(expected[0], actual,
|
||||||
|
fmt.Sprintf(shouldHaveResembled, render.Render(expected[0]), render.Render(actual)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotResemble receives exactly two parameters and does an inverse deep equal check (see reflect.DeepEqual)
|
||||||
|
func ShouldNotResemble(actual interface{}, expected ...interface{}) string {
|
||||||
|
if message := need(1, expected); message != success {
|
||||||
|
return message
|
||||||
|
} else if ShouldResemble(actual, expected[0]) == success {
|
||||||
|
return fmt.Sprintf(shouldNotHaveResembled, render.Render(actual), render.Render(expected[0]))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldPointTo receives exactly two parameters and checks to see that they point to the same address.
|
||||||
|
func ShouldPointTo(actual interface{}, expected ...interface{}) string {
|
||||||
|
if message := need(1, expected); message != success {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
return shouldPointTo(actual, expected[0])
|
||||||
|
|
||||||
|
}
|
||||||
|
func shouldPointTo(actual, expected interface{}) string {
|
||||||
|
actualValue := reflect.ValueOf(actual)
|
||||||
|
expectedValue := reflect.ValueOf(expected)
|
||||||
|
|
||||||
|
if ShouldNotBeNil(actual) != success {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "nil")
|
||||||
|
} else if ShouldNotBeNil(expected) != success {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "nil")
|
||||||
|
} else if actualValue.Kind() != reflect.Ptr {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenNonNilPointer, "first", "not")
|
||||||
|
} else if expectedValue.Kind() != reflect.Ptr {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenNonNilPointer, "second", "not")
|
||||||
|
} else if ShouldEqual(actualValue.Pointer(), expectedValue.Pointer()) != success {
|
||||||
|
actualAddress := reflect.ValueOf(actual).Pointer()
|
||||||
|
expectedAddress := reflect.ValueOf(expected).Pointer()
|
||||||
|
return serializer.serialize(expectedAddress, actualAddress, fmt.Sprintf(shouldHavePointedTo,
|
||||||
|
actual, actualAddress,
|
||||||
|
expected, expectedAddress))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotPointTo receives exactly two parameters and checks to see that they point to different addresess.
|
||||||
|
func ShouldNotPointTo(actual interface{}, expected ...interface{}) string {
|
||||||
|
if message := need(1, expected); message != success {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
compare := ShouldPointTo(actual, expected[0])
|
||||||
|
if strings.HasPrefix(compare, shouldBePointers) {
|
||||||
|
return compare
|
||||||
|
} else if compare == success {
|
||||||
|
return fmt.Sprintf(shouldNotHavePointedTo, actual, expected[0], reflect.ValueOf(actual).Pointer())
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeNil receives a single parameter and ensures that it is nil.
|
||||||
|
func ShouldBeNil(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if actual == nil {
|
||||||
|
return success
|
||||||
|
} else if interfaceHasNilValue(actual) {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldHaveBeenNil, actual)
|
||||||
|
}
|
||||||
|
func interfaceHasNilValue(actual interface{}) bool {
|
||||||
|
value := reflect.ValueOf(actual)
|
||||||
|
kind := value.Kind()
|
||||||
|
nilable := kind == reflect.Slice ||
|
||||||
|
kind == reflect.Chan ||
|
||||||
|
kind == reflect.Func ||
|
||||||
|
kind == reflect.Ptr ||
|
||||||
|
kind == reflect.Map
|
||||||
|
|
||||||
|
// Careful: reflect.Value.IsNil() will panic unless it's an interface, chan, map, func, slice, or ptr
|
||||||
|
// Reference: http://golang.org/pkg/reflect/#Value.IsNil
|
||||||
|
return nilable && value.IsNil()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeNil receives a single parameter and ensures that it is not nil.
|
||||||
|
func ShouldNotBeNil(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if ShouldBeNil(actual) == success {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenNil, actual)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeTrue receives a single parameter and ensures that it is true.
|
||||||
|
func ShouldBeTrue(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if actual != true {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenTrue, actual)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeFalse receives a single parameter and ensures that it is false.
|
||||||
|
func ShouldBeFalse(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if actual != false {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenFalse, actual)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeZeroValue receives a single parameter and ensures that it is
|
||||||
|
// the Go equivalent of the default value, or "zero" value.
|
||||||
|
func ShouldBeZeroValue(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
zeroVal := reflect.Zero(reflect.TypeOf(actual)).Interface()
|
||||||
|
if !reflect.DeepEqual(zeroVal, actual) {
|
||||||
|
return serializer.serialize(zeroVal, actual, fmt.Sprintf(shouldHaveBeenZeroValue, actual))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
23
vendor/github.com/smartystreets/assertions/filter.go
generated
vendored
Normal file
23
vendor/github.com/smartystreets/assertions/filter.go
generated
vendored
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
const (
|
||||||
|
success = ""
|
||||||
|
needExactValues = "This assertion requires exactly %d comparison values (you provided %d)."
|
||||||
|
needNonEmptyCollection = "This assertion requires at least 1 comparison value (you provided 0)."
|
||||||
|
)
|
||||||
|
|
||||||
|
func need(needed int, expected []interface{}) string {
|
||||||
|
if len(expected) != needed {
|
||||||
|
return fmt.Sprintf(needExactValues, needed, len(expected))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
func atLeast(minimum int, expected []interface{}) string {
|
||||||
|
if len(expected) < 1 {
|
||||||
|
return needNonEmptyCollection
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
27
vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE
generated
vendored
Normal file
27
vendor/github.com/smartystreets/assertions/internal/go-render/LICENSE
generated
vendored
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
|
||||||
|
//
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// * Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
// * Redistributions in binary form must reproduce the above
|
||||||
|
// copyright notice, this list of conditions and the following disclaimer
|
||||||
|
// in the documentation and/or other materials provided with the
|
||||||
|
// distribution.
|
||||||
|
// * Neither the name of Google Inc. nor the names of its
|
||||||
|
// contributors may be used to endorse or promote products derived from
|
||||||
|
// this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
477
vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go
generated
vendored
Normal file
477
vendor/github.com/smartystreets/assertions/internal/go-render/render/render.go
generated
vendored
Normal 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})
|
||||||
|
}
|
||||||
|
}
|
202
vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE
generated
vendored
Normal file
202
vendor/github.com/smartystreets/assertions/internal/oglematchers/LICENSE
generated
vendored
Normal file
|
@ -0,0 +1,202 @@
|
||||||
|
|
||||||
|
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.
|
58
vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md
generated
vendored
Normal file
58
vendor/github.com/smartystreets/assertions/internal/oglematchers/README.md
generated
vendored
Normal file
|
@ -0,0 +1,58 @@
|
||||||
|
[![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
|
||||||
|
[Google JS Test][google-js-test]. The package is used by the
|
||||||
|
[ogletest][ogletest] testing framework and [oglemock][oglemock] mocking
|
||||||
|
framework, which may be more directly useful to you, but can be generically used
|
||||||
|
elsewhere as well.
|
||||||
|
|
||||||
|
A "matcher" is simply an object with a `Matches` method defining a set of golang
|
||||||
|
values matched by the matcher, and a `Description` method describing that set.
|
||||||
|
For example, here are some matchers:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Numbers
|
||||||
|
Equals(17.13)
|
||||||
|
LessThan(19)
|
||||||
|
|
||||||
|
// Strings
|
||||||
|
Equals("taco")
|
||||||
|
HasSubstr("burrito")
|
||||||
|
MatchesRegex("t.*o")
|
||||||
|
|
||||||
|
// Combining matchers
|
||||||
|
AnyOf(LessThan(17), GreaterThan(19))
|
||||||
|
```
|
||||||
|
|
||||||
|
There are lots more; see [here][reference] for a reference. You can also add
|
||||||
|
your own simply by implementing the `oglematchers.Matcher` interface.
|
||||||
|
|
||||||
|
|
||||||
|
Installation
|
||||||
|
------------
|
||||||
|
|
||||||
|
First, make sure you have installed Go 1.0.2 or newer. See
|
||||||
|
[here][golang-install] for instructions.
|
||||||
|
|
||||||
|
Use the following command to install `oglematchers` and keep it up to date:
|
||||||
|
|
||||||
|
go get -u github.com/smartystreets/assertions/internal/oglematchers
|
||||||
|
|
||||||
|
|
||||||
|
Documentation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
See [here][reference] for documentation. Alternatively, you can install the
|
||||||
|
package and then use `godoc`:
|
||||||
|
|
||||||
|
godoc github.com/smartystreets/assertions/internal/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/assertions/internal/ogletest
|
||||||
|
[oglemock]: http://github.com/smartystreets/assertions/internal/oglemock
|
94
vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go
generated
vendored
Normal file
94
vendor/github.com/smartystreets/assertions/internal/oglematchers/any_of.go
generated
vendored
Normal file
|
@ -0,0 +1,94 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AnyOf accepts a set of values S and returns a matcher that follows the
|
||||||
|
// algorithm below when considering a candidate c:
|
||||||
|
//
|
||||||
|
// 1. If there exists a value m in S such that m implements the Matcher
|
||||||
|
// interface and m matches c, return true.
|
||||||
|
//
|
||||||
|
// 2. Otherwise, if there exists a value v in S such that v does not implement
|
||||||
|
// the Matcher interface and the matcher Equals(v) matches c, return true.
|
||||||
|
//
|
||||||
|
// 3. Otherwise, if there is a value m in S such that m implements the Matcher
|
||||||
|
// interface and m returns a fatal error for c, return that fatal error.
|
||||||
|
//
|
||||||
|
// 4. Otherwise, return false.
|
||||||
|
//
|
||||||
|
// This is akin to a logical OR operation for matchers, with non-matchers x
|
||||||
|
// being treated as Equals(x).
|
||||||
|
func AnyOf(vals ...interface{}) Matcher {
|
||||||
|
// Get ahold of a type variable for the Matcher interface.
|
||||||
|
var dummy *Matcher
|
||||||
|
matcherType := reflect.TypeOf(dummy).Elem()
|
||||||
|
|
||||||
|
// Create a matcher for each value, or use the value itself if it's already a
|
||||||
|
// matcher.
|
||||||
|
wrapped := make([]Matcher, len(vals))
|
||||||
|
for i, v := range vals {
|
||||||
|
t := reflect.TypeOf(v)
|
||||||
|
if t != nil && t.Implements(matcherType) {
|
||||||
|
wrapped[i] = v.(Matcher)
|
||||||
|
} else {
|
||||||
|
wrapped[i] = Equals(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &anyOfMatcher{wrapped}
|
||||||
|
}
|
||||||
|
|
||||||
|
type anyOfMatcher struct {
|
||||||
|
wrapped []Matcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *anyOfMatcher) Description() string {
|
||||||
|
wrappedDescs := make([]string, len(m.wrapped))
|
||||||
|
for i, matcher := range m.wrapped {
|
||||||
|
wrappedDescs[i] = matcher.Description()
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("or(%s)", strings.Join(wrappedDescs, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *anyOfMatcher) Matches(c interface{}) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
// Try each matcher in turn.
|
||||||
|
for _, matcher := range m.wrapped {
|
||||||
|
wrappedErr := matcher.Matches(c)
|
||||||
|
|
||||||
|
// Return immediately if there's a match.
|
||||||
|
if wrappedErr == nil {
|
||||||
|
err = nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note the fatal error, if any.
|
||||||
|
if _, isFatal := wrappedErr.(*FatalError); isFatal {
|
||||||
|
err = wrappedErr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
61
vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go
generated
vendored
Normal file
61
vendor/github.com/smartystreets/assertions/internal/oglematchers/contains.go
generated
vendored
Normal file
|
@ -0,0 +1,61 @@
|
||||||
|
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Return a matcher that matches arrays slices with at least one element that
|
||||||
|
// matches the supplied argument. If the argument x is not itself a Matcher,
|
||||||
|
// this is equivalent to Contains(Equals(x)).
|
||||||
|
func Contains(x interface{}) Matcher {
|
||||||
|
var result containsMatcher
|
||||||
|
var ok bool
|
||||||
|
|
||||||
|
if result.elementMatcher, ok = x.(Matcher); !ok {
|
||||||
|
result.elementMatcher = DeepEquals(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &result
|
||||||
|
}
|
||||||
|
|
||||||
|
type containsMatcher struct {
|
||||||
|
elementMatcher Matcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *containsMatcher) Description() string {
|
||||||
|
return fmt.Sprintf("contains: %s", m.elementMatcher.Description())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *containsMatcher) Matches(candidate interface{}) error {
|
||||||
|
// The candidate must be a slice or an array.
|
||||||
|
v := reflect.ValueOf(candidate)
|
||||||
|
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
|
||||||
|
return NewFatalError("which is not a slice or array")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check each element.
|
||||||
|
for i := 0; i < v.Len(); i++ {
|
||||||
|
elem := v.Index(i)
|
||||||
|
if matchErr := m.elementMatcher.Matches(elem.Interface()); matchErr == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("")
|
||||||
|
}
|
88
vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go
generated
vendored
Normal file
88
vendor/github.com/smartystreets/assertions/internal/oglematchers/deep_equals.go
generated
vendored
Normal file
|
@ -0,0 +1,88 @@
|
||||||
|
// Copyright 2012 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
var byteSliceType reflect.Type = reflect.TypeOf([]byte{})
|
||||||
|
|
||||||
|
// DeepEquals returns a matcher that matches based on 'deep equality', as
|
||||||
|
// defined by the reflect package. This matcher requires that values have
|
||||||
|
// identical types to x.
|
||||||
|
func DeepEquals(x interface{}) Matcher {
|
||||||
|
return &deepEqualsMatcher{x}
|
||||||
|
}
|
||||||
|
|
||||||
|
type deepEqualsMatcher struct {
|
||||||
|
x interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *deepEqualsMatcher) Description() string {
|
||||||
|
xDesc := fmt.Sprintf("%v", m.x)
|
||||||
|
xValue := reflect.ValueOf(m.x)
|
||||||
|
|
||||||
|
// Special case: fmt.Sprintf presents nil slices as "[]", but
|
||||||
|
// reflect.DeepEqual makes a distinction between nil and empty slices. Make
|
||||||
|
// this less confusing.
|
||||||
|
if xValue.Kind() == reflect.Slice && xValue.IsNil() {
|
||||||
|
xDesc = "<nil slice>"
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("deep equals: %s", xDesc)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *deepEqualsMatcher) Matches(c interface{}) error {
|
||||||
|
// Make sure the types match.
|
||||||
|
ct := reflect.TypeOf(c)
|
||||||
|
xt := reflect.TypeOf(m.x)
|
||||||
|
|
||||||
|
if ct != xt {
|
||||||
|
return NewFatalError(fmt.Sprintf("which is of type %v", ct))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case: handle byte slices more efficiently.
|
||||||
|
cValue := reflect.ValueOf(c)
|
||||||
|
xValue := reflect.ValueOf(m.x)
|
||||||
|
|
||||||
|
if ct == byteSliceType && !cValue.IsNil() && !xValue.IsNil() {
|
||||||
|
xBytes := m.x.([]byte)
|
||||||
|
cBytes := c.([]byte)
|
||||||
|
|
||||||
|
if bytes.Equal(cBytes, xBytes) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defer to the reflect package.
|
||||||
|
if reflect.DeepEqual(m.x, c) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Special case: if the comparison failed because c is the nil slice, given
|
||||||
|
// an indication of this (since its value is printed as "[]").
|
||||||
|
if cValue.Kind() == reflect.Slice && cValue.IsNil() {
|
||||||
|
return errors.New("which is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.New("")
|
||||||
|
}
|
541
vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go
generated
vendored
Normal file
541
vendor/github.com/smartystreets/assertions/internal/oglematchers/equals.go
generated
vendored
Normal file
|
@ -0,0 +1,541 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Equals(x) returns a matcher that matches values v such that v and x are
|
||||||
|
// equivalent. This includes the case when the comparison v == x using Go's
|
||||||
|
// built-in comparison operator is legal (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:
|
||||||
|
//
|
||||||
|
// type stringAlias1 string
|
||||||
|
// type stringAlias2 string
|
||||||
|
//
|
||||||
|
// a := "taco"
|
||||||
|
// b := stringAlias1("taco")
|
||||||
|
// c := stringAlias2("taco")
|
||||||
|
//
|
||||||
|
// ExpectTrue(a == b) // Legal, passes
|
||||||
|
// ExpectTrue(b == c) // Illegal, doesn't compile
|
||||||
|
//
|
||||||
|
// ExpectThat(a, Equals(b)) // Passes
|
||||||
|
// ExpectThat(b, Equals(c)) // Passes
|
||||||
|
//
|
||||||
|
// * Values of numeric type are treated as if they were abstract numbers, and
|
||||||
|
// compared accordingly. Therefore Equals(17) will match int(17),
|
||||||
|
// int16(17), uint(17), float32(17), complex64(17), and so on.
|
||||||
|
//
|
||||||
|
// If you want a stricter matcher that contains no such cleverness, see
|
||||||
|
// IdenticalTo instead.
|
||||||
|
//
|
||||||
|
// 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)
|
||||||
|
|
||||||
|
// This matcher doesn't support structs.
|
||||||
|
if v.Kind() == reflect.Struct {
|
||||||
|
panic(fmt.Sprintf("oglematchers.Equals: unsupported kind %v", v.Kind()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// The == operator is not defined for non-nil slices.
|
||||||
|
if v.Kind() == reflect.Slice && v.Pointer() != uintptr(0) {
|
||||||
|
panic(fmt.Sprintf("oglematchers.Equals: non-nil slice"))
|
||||||
|
}
|
||||||
|
|
||||||
|
return &equalsMatcher{v}
|
||||||
|
}
|
||||||
|
|
||||||
|
type equalsMatcher struct {
|
||||||
|
expectedValue reflect.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
// Numeric types
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
func isSignedInteger(v reflect.Value) bool {
|
||||||
|
k := v.Kind()
|
||||||
|
return k >= reflect.Int && k <= reflect.Int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func isUnsignedInteger(v reflect.Value) bool {
|
||||||
|
k := v.Kind()
|
||||||
|
return k >= reflect.Uint && k <= reflect.Uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
func isInteger(v reflect.Value) bool {
|
||||||
|
return isSignedInteger(v) || isUnsignedInteger(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
func isFloat(v reflect.Value) bool {
|
||||||
|
k := v.Kind()
|
||||||
|
return k == reflect.Float32 || k == reflect.Float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func isComplex(v reflect.Value) bool {
|
||||||
|
k := v.Kind()
|
||||||
|
return k == reflect.Complex64 || k == reflect.Complex128
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstInt64(e int64, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(c):
|
||||||
|
if c.Int() == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isUnsignedInteger(c):
|
||||||
|
u := c.Uint()
|
||||||
|
if u <= math.MaxInt64 && int64(u) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turn around the various floating point types so that the checkAgainst*
|
||||||
|
// functions for them can deal with precision issues.
|
||||||
|
case isFloat(c), isComplex(c):
|
||||||
|
return Equals(c.Interface()).Matches(e)
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstUint64(e uint64, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(c):
|
||||||
|
i := c.Int()
|
||||||
|
if i >= 0 && uint64(i) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isUnsignedInteger(c):
|
||||||
|
if c.Uint() == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Turn around the various floating point types so that the checkAgainst*
|
||||||
|
// functions for them can deal with precision issues.
|
||||||
|
case isFloat(c), isComplex(c):
|
||||||
|
return Equals(c.Interface()).Matches(e)
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstFloat32(e float32, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(c):
|
||||||
|
if float32(c.Int()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isUnsignedInteger(c):
|
||||||
|
if float32(c.Uint()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isFloat(c):
|
||||||
|
// Compare using float32 to avoid a false sense of precision; otherwise
|
||||||
|
// e.g. Equals(float32(0.1)) won't match float32(0.1).
|
||||||
|
if float32(c.Float()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isComplex(c):
|
||||||
|
comp := c.Complex()
|
||||||
|
rl := real(comp)
|
||||||
|
im := imag(comp)
|
||||||
|
|
||||||
|
// Compare using float32 to avoid a false sense of precision; otherwise
|
||||||
|
// e.g. Equals(float32(0.1)) won't match (0.1 + 0i).
|
||||||
|
if im == 0 && float32(rl) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstFloat64(e float64, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
ck := c.Kind()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(c):
|
||||||
|
if float64(c.Int()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isUnsignedInteger(c):
|
||||||
|
if float64(c.Uint()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the actual value is lower precision, turn the comparison around so we
|
||||||
|
// apply the low-precision rules. Otherwise, e.g. Equals(0.1) may not match
|
||||||
|
// float32(0.1).
|
||||||
|
case ck == reflect.Float32 || ck == reflect.Complex64:
|
||||||
|
return Equals(c.Interface()).Matches(e)
|
||||||
|
|
||||||
|
// Otherwise, compare with double precision.
|
||||||
|
case isFloat(c):
|
||||||
|
if c.Float() == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case isComplex(c):
|
||||||
|
comp := c.Complex()
|
||||||
|
rl := real(comp)
|
||||||
|
im := imag(comp)
|
||||||
|
|
||||||
|
if im == 0 && rl == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstComplex64(e complex64, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
realPart := real(e)
|
||||||
|
imaginaryPart := imag(e)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isInteger(c) || isFloat(c):
|
||||||
|
// If we have no imaginary part, then we should just compare against the
|
||||||
|
// real part. Otherwise, we can't be equal.
|
||||||
|
if imaginaryPart != 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return checkAgainstFloat32(realPart, c)
|
||||||
|
|
||||||
|
case isComplex(c):
|
||||||
|
// Compare using complex64 to avoid a false sense of precision; otherwise
|
||||||
|
// e.g. Equals(0.1 + 0i) won't match float32(0.1).
|
||||||
|
if complex64(c.Complex()) == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstComplex128(e complex128, c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
realPart := real(e)
|
||||||
|
imaginaryPart := imag(e)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isInteger(c) || isFloat(c):
|
||||||
|
// If we have no imaginary part, then we should just compare against the
|
||||||
|
// real part. Otherwise, we can't be equal.
|
||||||
|
if imaginaryPart != 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
return checkAgainstFloat64(realPart, c)
|
||||||
|
|
||||||
|
case isComplex(c):
|
||||||
|
if c.Complex() == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which is not numeric")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
// Other types
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
func checkAgainstBool(e bool, c reflect.Value) (err error) {
|
||||||
|
if c.Kind() != reflect.Bool {
|
||||||
|
err = NewFatalError("which is not a bool")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Bool() == e {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstChan(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Create a description of e's type, e.g. "chan int".
|
||||||
|
typeStr := fmt.Sprintf("%s %s", e.Type().ChanDir(), e.Type().Elem())
|
||||||
|
|
||||||
|
// Make sure c is a chan of the correct type.
|
||||||
|
if c.Kind() != reflect.Chan ||
|
||||||
|
c.Type().ChanDir() != e.Type().ChanDir() ||
|
||||||
|
c.Type().Elem() != e.Type().Elem() {
|
||||||
|
err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstFunc(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Make sure c is a function.
|
||||||
|
if c.Kind() != reflect.Func {
|
||||||
|
err = NewFatalError("which is not a function")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstMap(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Make sure c is a map.
|
||||||
|
if c.Kind() != reflect.Map {
|
||||||
|
err = NewFatalError("which is not a map")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstPtr(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Create a description of e's type, e.g. "*int".
|
||||||
|
typeStr := fmt.Sprintf("*%v", e.Type().Elem())
|
||||||
|
|
||||||
|
// Make sure c is a pointer of the correct type.
|
||||||
|
if c.Kind() != reflect.Ptr ||
|
||||||
|
c.Type().Elem() != e.Type().Elem() {
|
||||||
|
err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstSlice(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Create a description of e's type, e.g. "[]int".
|
||||||
|
typeStr := fmt.Sprintf("[]%v", e.Type().Elem())
|
||||||
|
|
||||||
|
// Make sure c is a slice of the correct type.
|
||||||
|
if c.Kind() != reflect.Slice ||
|
||||||
|
c.Type().Elem() != e.Type().Elem() {
|
||||||
|
err = NewFatalError(fmt.Sprintf("which is not a %s", typeStr))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAgainstString(e reflect.Value, c reflect.Value) (err error) {
|
||||||
|
// Make sure c is a string.
|
||||||
|
if c.Kind() != reflect.String {
|
||||||
|
err = NewFatalError("which is not a string")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.String() == e.String() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func 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 {
|
||||||
|
err = NewFatalError("which is not a unsafe.Pointer")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
if c.Pointer() == e.Pointer() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkForNil(c reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
// Make sure it is legal to call IsNil.
|
||||||
|
switch c.Kind() {
|
||||||
|
case reflect.Invalid:
|
||||||
|
case reflect.Chan:
|
||||||
|
case reflect.Func:
|
||||||
|
case reflect.Interface:
|
||||||
|
case reflect.Map:
|
||||||
|
case reflect.Ptr:
|
||||||
|
case reflect.Slice:
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = NewFatalError("which cannot be compared to nil")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ask whether the value is nil. Handle a nil literal (kind Invalid)
|
||||||
|
// specially, since it's not legal to call IsNil there.
|
||||||
|
if c.Kind() == reflect.Invalid || c.IsNil() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
// Public implementation
|
||||||
|
////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
func (m *equalsMatcher) Matches(candidate interface{}) error {
|
||||||
|
e := m.expectedValue
|
||||||
|
c := reflect.ValueOf(candidate)
|
||||||
|
ek := e.Kind()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case ek == reflect.Bool:
|
||||||
|
return checkAgainstBool(e.Bool(), c)
|
||||||
|
|
||||||
|
case isSignedInteger(e):
|
||||||
|
return checkAgainstInt64(e.Int(), c)
|
||||||
|
|
||||||
|
case isUnsignedInteger(e):
|
||||||
|
return checkAgainstUint64(e.Uint(), c)
|
||||||
|
|
||||||
|
case ek == reflect.Float32:
|
||||||
|
return checkAgainstFloat32(float32(e.Float()), c)
|
||||||
|
|
||||||
|
case ek == reflect.Float64:
|
||||||
|
return checkAgainstFloat64(e.Float(), c)
|
||||||
|
|
||||||
|
case ek == reflect.Complex64:
|
||||||
|
return checkAgainstComplex64(complex64(e.Complex()), c)
|
||||||
|
|
||||||
|
case ek == reflect.Complex128:
|
||||||
|
return checkAgainstComplex128(complex128(e.Complex()), c)
|
||||||
|
|
||||||
|
case ek == reflect.Chan:
|
||||||
|
return checkAgainstChan(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Func:
|
||||||
|
return checkAgainstFunc(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Map:
|
||||||
|
return checkAgainstMap(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Ptr:
|
||||||
|
return checkAgainstPtr(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Slice:
|
||||||
|
return checkAgainstSlice(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.String:
|
||||||
|
return checkAgainstString(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Array:
|
||||||
|
return checkAgainstArray(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.UnsafePointer:
|
||||||
|
return checkAgainstUnsafePointer(e, c)
|
||||||
|
|
||||||
|
case ek == reflect.Invalid:
|
||||||
|
return checkForNil(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
panic(fmt.Sprintf("equalsMatcher.Matches: unexpected kind: %v", ek))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *equalsMatcher) Description() string {
|
||||||
|
// Special case: handle nil.
|
||||||
|
if !m.expectedValue.IsValid() {
|
||||||
|
return "is nil"
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%v", m.expectedValue.Interface())
|
||||||
|
}
|
39
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go
generated
vendored
Normal file
39
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal.go
generated
vendored
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GreaterOrEqual returns a matcher that matches integer, floating point, or
|
||||||
|
// strings values v such that v >= x. Comparison is not defined between numeric
|
||||||
|
// and string types, but is defined between all integer and floating point
|
||||||
|
// types.
|
||||||
|
//
|
||||||
|
// x must itself be an integer, floating point, or string type; otherwise,
|
||||||
|
// GreaterOrEqual will panic.
|
||||||
|
func GreaterOrEqual(x interface{}) Matcher {
|
||||||
|
desc := fmt.Sprintf("greater than or equal to %v", x)
|
||||||
|
|
||||||
|
// Special case: make it clear that strings are strings.
|
||||||
|
if reflect.TypeOf(x).Kind() == reflect.String {
|
||||||
|
desc = fmt.Sprintf("greater than or equal to \"%s\"", x)
|
||||||
|
}
|
||||||
|
|
||||||
|
return transformDescription(Not(LessThan(x)), desc)
|
||||||
|
}
|
39
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go
generated
vendored
Normal file
39
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_than.go
generated
vendored
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GreaterThan returns a matcher that matches integer, floating point, or
|
||||||
|
// strings values v such that v > x. Comparison is not defined between numeric
|
||||||
|
// and string types, but is defined between all integer and floating point
|
||||||
|
// types.
|
||||||
|
//
|
||||||
|
// x must itself be an integer, floating point, or string type; otherwise,
|
||||||
|
// GreaterThan will panic.
|
||||||
|
func GreaterThan(x interface{}) Matcher {
|
||||||
|
desc := fmt.Sprintf("greater than %v", x)
|
||||||
|
|
||||||
|
// Special case: make it clear that strings are strings.
|
||||||
|
if reflect.TypeOf(x).Kind() == reflect.String {
|
||||||
|
desc = fmt.Sprintf("greater than \"%s\"", x)
|
||||||
|
}
|
||||||
|
|
||||||
|
return transformDescription(Not(LessOrEqual(x)), desc)
|
||||||
|
}
|
41
vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go
generated
vendored
Normal file
41
vendor/github.com/smartystreets/assertions/internal/oglematchers/less_or_equal.go
generated
vendored
Normal file
|
@ -0,0 +1,41 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LessOrEqual returns a matcher that matches integer, floating point, or
|
||||||
|
// strings values v such that v <= x. Comparison is not defined between numeric
|
||||||
|
// and string types, but is defined between all integer and floating point
|
||||||
|
// types.
|
||||||
|
//
|
||||||
|
// x must itself be an integer, floating point, or string type; otherwise,
|
||||||
|
// LessOrEqual will panic.
|
||||||
|
func LessOrEqual(x interface{}) Matcher {
|
||||||
|
desc := fmt.Sprintf("less than or equal to %v", x)
|
||||||
|
|
||||||
|
// Special case: make it clear that strings are strings.
|
||||||
|
if reflect.TypeOf(x).Kind() == reflect.String {
|
||||||
|
desc = fmt.Sprintf("less than or equal to \"%s\"", x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put LessThan last so that its error messages will be used in the event of
|
||||||
|
// failure.
|
||||||
|
return transformDescription(AnyOf(Equals(x), LessThan(x)), desc)
|
||||||
|
}
|
152
vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go
generated
vendored
Normal file
152
vendor/github.com/smartystreets/assertions/internal/oglematchers/less_than.go
generated
vendored
Normal file
|
@ -0,0 +1,152 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LessThan returns a matcher that matches integer, floating point, or strings
|
||||||
|
// values v such that v < x. Comparison is not defined between numeric and
|
||||||
|
// string types, but is defined between all integer and floating point types.
|
||||||
|
//
|
||||||
|
// x must itself be an integer, floating point, or string type; otherwise,
|
||||||
|
// LessThan will panic.
|
||||||
|
func LessThan(x interface{}) Matcher {
|
||||||
|
v := reflect.ValueOf(x)
|
||||||
|
kind := v.Kind()
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isInteger(v):
|
||||||
|
case isFloat(v):
|
||||||
|
case kind == reflect.String:
|
||||||
|
|
||||||
|
default:
|
||||||
|
panic(fmt.Sprintf("LessThan: unexpected kind %v", kind))
|
||||||
|
}
|
||||||
|
|
||||||
|
return &lessThanMatcher{v}
|
||||||
|
}
|
||||||
|
|
||||||
|
type lessThanMatcher struct {
|
||||||
|
limit reflect.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *lessThanMatcher) Description() string {
|
||||||
|
// Special case: make it clear that strings are strings.
|
||||||
|
if m.limit.Kind() == reflect.String {
|
||||||
|
return fmt.Sprintf("less than \"%s\"", m.limit.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("less than %v", m.limit.Interface())
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareIntegers(v1, v2 reflect.Value) (err error) {
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(v1) && isSignedInteger(v2):
|
||||||
|
if v1.Int() < v2.Int() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
case isSignedInteger(v1) && isUnsignedInteger(v2):
|
||||||
|
if v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
case isUnsignedInteger(v1) && isSignedInteger(v2):
|
||||||
|
if v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
case isUnsignedInteger(v1) && isUnsignedInteger(v2):
|
||||||
|
if v1.Uint() < v2.Uint() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
panic(fmt.Sprintf("compareIntegers: %v %v", v1, v2))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFloat(v reflect.Value) float64 {
|
||||||
|
switch {
|
||||||
|
case isSignedInteger(v):
|
||||||
|
return float64(v.Int())
|
||||||
|
|
||||||
|
case isUnsignedInteger(v):
|
||||||
|
return float64(v.Uint())
|
||||||
|
|
||||||
|
case isFloat(v):
|
||||||
|
return v.Float()
|
||||||
|
}
|
||||||
|
|
||||||
|
panic(fmt.Sprintf("getFloat: %v", v))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *lessThanMatcher) Matches(c interface{}) (err error) {
|
||||||
|
v1 := reflect.ValueOf(c)
|
||||||
|
v2 := m.limit
|
||||||
|
|
||||||
|
err = errors.New("")
|
||||||
|
|
||||||
|
// Handle strings as a special case.
|
||||||
|
if v1.Kind() == reflect.String && v2.Kind() == reflect.String {
|
||||||
|
if v1.String() < v2.String() {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we get here, we require that we are dealing with integers or floats.
|
||||||
|
v1Legal := isInteger(v1) || isFloat(v1)
|
||||||
|
v2Legal := isInteger(v2) || isFloat(v2)
|
||||||
|
if !v1Legal || !v2Legal {
|
||||||
|
err = NewFatalError("which is not comparable")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle the various comparison cases.
|
||||||
|
switch {
|
||||||
|
// Both integers
|
||||||
|
case isInteger(v1) && isInteger(v2):
|
||||||
|
return compareIntegers(v1, v2)
|
||||||
|
|
||||||
|
// At least one float32
|
||||||
|
case v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32:
|
||||||
|
if float32(getFloat(v1)) < float32(getFloat(v2)) {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
// At least one float64
|
||||||
|
case v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64:
|
||||||
|
if getFloat(v1) < getFloat(v2) {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// We shouldn't get here.
|
||||||
|
panic(fmt.Sprintf("lessThanMatcher.Matches: Shouldn't get here: %v %v", v1, v2))
|
||||||
|
}
|
86
vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go
generated
vendored
Normal file
86
vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go
generated
vendored
Normal file
|
@ -0,0 +1,86 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
// Package oglematchers provides a set of matchers useful in a testing or
|
||||||
|
// mocking framework. These matchers are inspired by and mostly compatible with
|
||||||
|
// Google Test for C++ and Google JS Test.
|
||||||
|
//
|
||||||
|
// This package is used by github.com/smartystreets/assertions/internal/ogletest and
|
||||||
|
// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not
|
||||||
|
// writing your own testing package or defining your own matchers.
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
// A Matcher is some predicate implicitly defining a set of values that it
|
||||||
|
// matches. For example, GreaterThan(17) matches all numeric values greater
|
||||||
|
// than 17, and HasSubstr("taco") matches all strings with the substring
|
||||||
|
// "taco".
|
||||||
|
//
|
||||||
|
// 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.
|
||||||
|
//
|
||||||
|
// The error describes why the value doesn't match. The error text is a
|
||||||
|
// relative clause that is suitable for being placed after the value. For
|
||||||
|
// example, a predicate that matches strings with a particular substring may,
|
||||||
|
// when presented with a numerical value, return the following error text:
|
||||||
|
//
|
||||||
|
// "which is not a string"
|
||||||
|
//
|
||||||
|
// Then the failure message may look like:
|
||||||
|
//
|
||||||
|
// Expected: has substring "taco"
|
||||||
|
// Actual: 17, which is not a string
|
||||||
|
//
|
||||||
|
// If the error is self-apparent based on the description of the matcher, the
|
||||||
|
// error text may be empty (but the error still non-nil). For example:
|
||||||
|
//
|
||||||
|
// Expected: 17
|
||||||
|
// Actual: 19
|
||||||
|
//
|
||||||
|
// If you are implementing a new matcher, see also the documentation on
|
||||||
|
// FatalError.
|
||||||
|
Matches(candidate interface{}) error
|
||||||
|
|
||||||
|
// Description returns a string describing the property that values matching
|
||||||
|
// this matcher have, as a verb phrase where the subject is the value. For
|
||||||
|
// example, "is greather than 17" or "has substring "taco"".
|
||||||
|
Description() string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FatalError is an implementation of the error interface that may be returned
|
||||||
|
// from matchers, indicating the error should be propagated. Returning a
|
||||||
|
// *FatalError indicates that the matcher doesn't process values of the
|
||||||
|
// supplied type, or otherwise doesn't know how to handle the value.
|
||||||
|
//
|
||||||
|
// For example, if GreaterThan(17) returned false for the value "taco" without
|
||||||
|
// a fatal error, then Not(GreaterThan(17)) would return true. This is
|
||||||
|
// technically correct, but is surprising and may mask failures where the wrong
|
||||||
|
// sort of matcher is accidentally used. Instead, GreaterThan(17) can return a
|
||||||
|
// fatal error, which will be propagated by Not().
|
||||||
|
type FatalError struct {
|
||||||
|
errorText string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFatalError creates a FatalError struct with the supplied error text.
|
||||||
|
func NewFatalError(s string) *FatalError {
|
||||||
|
return &FatalError{s}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *FatalError) Error() string {
|
||||||
|
return e.errorText
|
||||||
|
}
|
53
vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go
generated
vendored
Normal file
53
vendor/github.com/smartystreets/assertions/internal/oglematchers/not.go
generated
vendored
Normal file
|
@ -0,0 +1,53 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Not returns a matcher that inverts the set of values matched by the wrapped
|
||||||
|
// matcher. It does not transform the result for values for which the wrapped
|
||||||
|
// matcher returns a fatal error.
|
||||||
|
func Not(m Matcher) Matcher {
|
||||||
|
return ¬Matcher{m}
|
||||||
|
}
|
||||||
|
|
||||||
|
type notMatcher struct {
|
||||||
|
wrapped Matcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *notMatcher) Matches(c interface{}) (err error) {
|
||||||
|
err = m.wrapped.Matches(c)
|
||||||
|
|
||||||
|
// Did the wrapped matcher say yes?
|
||||||
|
if err == nil {
|
||||||
|
return errors.New("")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Did the wrapped matcher return a fatal error?
|
||||||
|
if _, isFatal := err.(*FatalError); isFatal {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// The wrapped matcher returned a non-fatal error.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *notMatcher) Description() string {
|
||||||
|
return fmt.Sprintf("not(%s)", m.wrapped.Description())
|
||||||
|
}
|
36
vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go
generated
vendored
Normal file
36
vendor/github.com/smartystreets/assertions/internal/oglematchers/transform_description.go
generated
vendored
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
|
||||||
|
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package oglematchers
|
||||||
|
|
||||||
|
// transformDescription returns a matcher that is equivalent to the supplied
|
||||||
|
// one, except that it has the supplied description instead of the one attached
|
||||||
|
// to the existing matcher.
|
||||||
|
func transformDescription(m Matcher, newDesc string) Matcher {
|
||||||
|
return &transformDescriptionMatcher{newDesc, m}
|
||||||
|
}
|
||||||
|
|
||||||
|
type transformDescriptionMatcher struct {
|
||||||
|
desc string
|
||||||
|
wrappedMatcher Matcher
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *transformDescriptionMatcher) Description() string {
|
||||||
|
return m.desc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *transformDescriptionMatcher) Matches(c interface{}) error {
|
||||||
|
return m.wrappedMatcher.Matches(c)
|
||||||
|
}
|
93
vendor/github.com/smartystreets/assertions/messages.go
generated
vendored
Normal file
93
vendor/github.com/smartystreets/assertions/messages.go
generated
vendored
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
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: '%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)!"
|
||||||
|
shouldHavePointedTo = "Expected '%+v' (address: '%v') and '%+v' (address: '%v') to be the same address (but their weren't)!"
|
||||||
|
shouldNotHavePointedTo = "Expected '%+v' and '%+v' to be different references (but they matched: '%v')!"
|
||||||
|
shouldHaveBeenNil = "Expected: nil\nActual: '%v'"
|
||||||
|
shouldNotHaveBeenNil = "Expected '%+v' to NOT be nil (but it was)!"
|
||||||
|
shouldHaveBeenTrue = "Expected: true\nActual: %v"
|
||||||
|
shouldHaveBeenFalse = "Expected: false\nActual: %v"
|
||||||
|
shouldHaveBeenZeroValue = "'%+v' should have been the zero value" //"Expected: (zero value)\nActual: %v"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ( // quantity comparisons
|
||||||
|
shouldHaveBeenGreater = "Expected '%v' to be greater than '%v' (but it wasn't)!"
|
||||||
|
shouldHaveBeenGreaterOrEqual = "Expected '%v' to be greater than or equal to '%v' (but it wasn't)!"
|
||||||
|
shouldHaveBeenLess = "Expected '%v' to be less than '%v' (but it wasn't)!"
|
||||||
|
shouldHaveBeenLessOrEqual = "Expected '%v' to be less than or equal to '%v' (but it wasn't)!"
|
||||||
|
shouldHaveBeenBetween = "Expected '%v' to be between '%v' and '%v' (but it wasn't)!"
|
||||||
|
shouldNotHaveBeenBetween = "Expected '%v' NOT to be between '%v' and '%v' (but it was)!"
|
||||||
|
shouldHaveDifferentUpperAndLower = "The lower and upper bounds must be different values (they were both '%v')."
|
||||||
|
shouldHaveBeenBetweenOrEqual = "Expected '%v' to be between '%v' and '%v' or equal to one of them (but it wasn't)!"
|
||||||
|
shouldNotHaveBeenBetweenOrEqual = "Expected '%v' NOT to be between '%v' and '%v' or equal to one of them (but it was)!"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ( // collections
|
||||||
|
shouldHaveContained = "Expected the container (%v) to contain: '%v' (but it didn't)!"
|
||||||
|
shouldNotHaveContained = "Expected the container (%v) NOT to contain: '%v' (but it did)!"
|
||||||
|
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
|
||||||
|
shouldHaveStartedWith = "Expected '%v'\nto start with '%v'\n(but it didn't)!"
|
||||||
|
shouldNotHaveStartedWith = "Expected '%v'\nNOT to start with '%v'\n(but it did)!"
|
||||||
|
shouldHaveEndedWith = "Expected '%v'\nto end with '%v'\n(but it didn't)!"
|
||||||
|
shouldNotHaveEndedWith = "Expected '%v'\nNOT to end with '%v'\n(but it did)!"
|
||||||
|
shouldAllBeStrings = "All arguments to this assertion must be strings (you provided: %v)."
|
||||||
|
shouldBothBeStrings = "Both arguments to this assertion must be strings (you provided %v and %v)."
|
||||||
|
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 did)!"
|
||||||
|
shouldHaveBeenBlank = "Expected '%s' to be blank (but it wasn't)!"
|
||||||
|
shouldNotHaveBeenBlank = "Expected value to NOT be blank (but it was)!"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ( // panics
|
||||||
|
shouldUseVoidNiladicFunction = "You must provide a void, niladic function as the first argument!"
|
||||||
|
shouldHavePanickedWith = "Expected func() to panic with '%v' (but it panicked with '%v')!"
|
||||||
|
shouldHavePanicked = "Expected func() to panic (but it didn't)!"
|
||||||
|
shouldNotHavePanicked = "Expected func() NOT to panic (error: '%+v')!"
|
||||||
|
shouldNotHavePanickedWith = "Expected func() NOT to panic with '%v' (but it did)!"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ( // type checking
|
||||||
|
shouldHaveBeenA = "Expected '%v' to be: '%v' (but was: '%v')!"
|
||||||
|
shouldNotHaveBeenA = "Expected '%v' to NOT be: '%v' (but it was)!"
|
||||||
|
|
||||||
|
shouldHaveImplemented = "Expected: '%v interface support'\nActual: '%v' does not implement the interface!"
|
||||||
|
shouldNotHaveImplemented = "Expected '%v'\nto NOT implement '%v'\n(but it did)!"
|
||||||
|
shouldCompareWithInterfacePointer = "The expected value must be a pointer to an interface type (eg. *fmt.Stringer)"
|
||||||
|
shouldNotBeNilActual = "The actual value was 'nil' and should be a value or a pointer to a value!"
|
||||||
|
)
|
||||||
|
|
||||||
|
const ( // time comparisons
|
||||||
|
shouldUseTimes = "You must provide time instances as arguments to this assertion."
|
||||||
|
shouldUseTimeSlice = "You must provide a slice of time instances as the first argument to this assertion."
|
||||||
|
shouldUseDurationAndTime = "You must provide a duration and a time as arguments to this assertion."
|
||||||
|
shouldHaveHappenedBefore = "Expected '%v' to happen before '%v' (it happened '%v' after)!"
|
||||||
|
shouldHaveHappenedAfter = "Expected '%v' to happen after '%v' (it happened '%v' before)!"
|
||||||
|
shouldHaveHappenedBetween = "Expected '%v' to happen between '%v' and '%v' (it happened '%v' outside threshold)!"
|
||||||
|
shouldNotHaveHappenedOnOrBetween = "Expected '%v' to NOT happen on or between '%v' and '%v' (but it did)!"
|
||||||
|
|
||||||
|
// format params: incorrect-index, previous-index, previous-time, incorrect-index, incorrect-time
|
||||||
|
shouldHaveBeenChronological = "The 'Time' at index [%d] should have happened after the previous one (but it didn't!):\n [%d]: %s\n [%d]: %s (see, it happened before!)"
|
||||||
|
)
|
115
vendor/github.com/smartystreets/assertions/panic.go
generated
vendored
Normal file
115
vendor/github.com/smartystreets/assertions/panic.go
generated
vendored
Normal file
|
@ -0,0 +1,115 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
// ShouldPanic receives a void, niladic function and expects to recover a panic.
|
||||||
|
func ShouldPanic(actual interface{}, expected ...interface{}) (message string) {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
action, _ := actual.(func())
|
||||||
|
|
||||||
|
if action == nil {
|
||||||
|
message = shouldUseVoidNiladicFunction
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
recovered := recover()
|
||||||
|
if recovered == nil {
|
||||||
|
message = shouldHavePanicked
|
||||||
|
} else {
|
||||||
|
message = success
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
action()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotPanic receives a void, niladic function and expects to execute the function without any panic.
|
||||||
|
func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
action, _ := actual.(func())
|
||||||
|
|
||||||
|
if action == nil {
|
||||||
|
message = shouldUseVoidNiladicFunction
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
recovered := recover()
|
||||||
|
if recovered != nil {
|
||||||
|
message = fmt.Sprintf(shouldNotHavePanicked, recovered)
|
||||||
|
} else {
|
||||||
|
message = success
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
action()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldPanicWith receives a void, niladic function and expects to recover a panic with the second argument as the content.
|
||||||
|
func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
action, _ := actual.(func())
|
||||||
|
|
||||||
|
if action == nil {
|
||||||
|
message = shouldUseVoidNiladicFunction
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
recovered := recover()
|
||||||
|
if recovered == nil {
|
||||||
|
message = shouldHavePanicked
|
||||||
|
} else {
|
||||||
|
if equal := ShouldEqual(recovered, expected[0]); equal != success {
|
||||||
|
message = serializer.serialize(expected[0], recovered, fmt.Sprintf(shouldHavePanickedWith, expected[0], recovered))
|
||||||
|
} else {
|
||||||
|
message = success
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
action()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotPanicWith receives a void, niladic function and expects to recover a panic whose content differs from the second argument.
|
||||||
|
func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
action, _ := actual.(func())
|
||||||
|
|
||||||
|
if action == nil {
|
||||||
|
message = shouldUseVoidNiladicFunction
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
recovered := recover()
|
||||||
|
if recovered == nil {
|
||||||
|
message = success
|
||||||
|
} else {
|
||||||
|
if equal := ShouldEqual(recovered, expected[0]); equal == success {
|
||||||
|
message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0])
|
||||||
|
} else {
|
||||||
|
message = success
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
action()
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
141
vendor/github.com/smartystreets/assertions/quantity.go
generated
vendored
Normal file
141
vendor/github.com/smartystreets/assertions/quantity.go
generated
vendored
Normal file
|
@ -0,0 +1,141 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/smartystreets/assertions/internal/oglematchers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ShouldBeGreaterThan receives exactly two parameters and ensures that the first is greater than the second.
|
||||||
|
func ShouldBeGreaterThan(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
if matchError := oglematchers.GreaterThan(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenGreater, actual, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeGreaterThanOrEqualTo receives exactly two parameters and ensures that the first is greater than or equal to the second.
|
||||||
|
func ShouldBeGreaterThanOrEqualTo(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if matchError := oglematchers.GreaterOrEqual(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenGreaterOrEqual, actual, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than the second.
|
||||||
|
func ShouldBeLessThan(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if matchError := oglematchers.LessThan(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenLess, actual, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeLessThan receives exactly two parameters and ensures that the first is less than or equal to the second.
|
||||||
|
func ShouldBeLessThanOrEqualTo(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
} else if matchError := oglematchers.LessOrEqual(expected[0]).Matches(actual); matchError != nil {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenLessOrEqual, actual, expected[0])
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound.
|
||||||
|
// It ensures that the actual value is between both bounds (but not equal to either of them).
|
||||||
|
func ShouldBeBetween(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
lower, upper, fail := deriveBounds(expected)
|
||||||
|
|
||||||
|
if fail != success {
|
||||||
|
return fail
|
||||||
|
} else if !isBetween(actual, lower, upper) {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenBetween, actual, lower, upper)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeBetween receives exactly three parameters: an actual value, a lower bound, and an upper bound.
|
||||||
|
// It ensures that the actual value is NOT between both bounds.
|
||||||
|
func ShouldNotBeBetween(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
lower, upper, fail := deriveBounds(expected)
|
||||||
|
|
||||||
|
if fail != success {
|
||||||
|
return fail
|
||||||
|
} else if isBetween(actual, lower, upper) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenBetween, actual, lower, upper)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
func deriveBounds(values []interface{}) (lower interface{}, upper interface{}, fail string) {
|
||||||
|
lower = values[0]
|
||||||
|
upper = values[1]
|
||||||
|
|
||||||
|
if ShouldNotEqual(lower, upper) != success {
|
||||||
|
return nil, nil, fmt.Sprintf(shouldHaveDifferentUpperAndLower, lower)
|
||||||
|
} else if ShouldBeLessThan(lower, upper) != success {
|
||||||
|
lower, upper = upper, lower
|
||||||
|
}
|
||||||
|
return lower, upper, success
|
||||||
|
}
|
||||||
|
func isBetween(value, lower, upper interface{}) bool {
|
||||||
|
if ShouldBeGreaterThan(value, lower) != success {
|
||||||
|
return false
|
||||||
|
} else if ShouldBeLessThan(value, upper) != success {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound.
|
||||||
|
// It ensures that the actual value is between both bounds or equal to one of them.
|
||||||
|
func ShouldBeBetweenOrEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
lower, upper, fail := deriveBounds(expected)
|
||||||
|
|
||||||
|
if fail != success {
|
||||||
|
return fail
|
||||||
|
} else if !isBetweenOrEqual(actual, lower, upper) {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenBetweenOrEqual, actual, lower, upper)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeBetweenOrEqual receives exactly three parameters: an actual value, a lower bound, and an upper bound.
|
||||||
|
// It ensures that the actual value is nopt between the bounds nor equal to either of them.
|
||||||
|
func ShouldNotBeBetweenOrEqual(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
lower, upper, fail := deriveBounds(expected)
|
||||||
|
|
||||||
|
if fail != success {
|
||||||
|
return fail
|
||||||
|
} else if isBetweenOrEqual(actual, lower, upper) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenBetweenOrEqual, actual, lower, upper)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
func isBetweenOrEqual(value, lower, upper interface{}) bool {
|
||||||
|
if ShouldBeGreaterThanOrEqualTo(value, lower) != success {
|
||||||
|
return false
|
||||||
|
} else if ShouldBeLessThanOrEqualTo(value, upper) != success {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
69
vendor/github.com/smartystreets/assertions/serializer.go
generated
vendored
Normal file
69
vendor/github.com/smartystreets/assertions/serializer.go
generated
vendored
Normal file
|
@ -0,0 +1,69 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/smartystreets/assertions/internal/go-render/render"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Serializer interface {
|
||||||
|
serialize(expected, actual interface{}, message string) string
|
||||||
|
serializeDetailed(expected, actual interface{}, message string) string
|
||||||
|
}
|
||||||
|
|
||||||
|
type failureSerializer struct{}
|
||||||
|
|
||||||
|
func (self *failureSerializer) serializeDetailed(expected, actual interface{}, message string) string {
|
||||||
|
view := FailureView{
|
||||||
|
Message: message,
|
||||||
|
Expected: render.Render(expected),
|
||||||
|
Actual: render.Render(actual),
|
||||||
|
}
|
||||||
|
serialized, err := json.Marshal(view)
|
||||||
|
if err != nil {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
return string(serialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *failureSerializer) serialize(expected, actual interface{}, message string) string {
|
||||||
|
view := FailureView{
|
||||||
|
Message: message,
|
||||||
|
Expected: fmt.Sprintf("%+v", expected),
|
||||||
|
Actual: fmt.Sprintf("%+v", actual),
|
||||||
|
}
|
||||||
|
serialized, err := json.Marshal(view)
|
||||||
|
if err != nil {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
return string(serialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
// the assertions from a context other than the GoConvey Web UI, that requires the JSON
|
||||||
|
// structure provided by the failureSerializer.
|
||||||
|
type noopSerializer struct{}
|
||||||
|
|
||||||
|
func (self *noopSerializer) serialize(expected, actual interface{}, message string) string {
|
||||||
|
return message
|
||||||
|
}
|
||||||
|
func (self *noopSerializer) serializeDetailed(expected, actual interface{}, message string) string {
|
||||||
|
return message
|
||||||
|
}
|
227
vendor/github.com/smartystreets/assertions/strings.go
generated
vendored
Normal file
227
vendor/github.com/smartystreets/assertions/strings.go
generated
vendored
Normal file
|
@ -0,0 +1,227 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ShouldStartWith receives exactly 2 string parameters and ensures that the first starts with the second.
|
||||||
|
func ShouldStartWith(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
value, valueIsString := actual.(string)
|
||||||
|
prefix, prefixIsString := expected[0].(string)
|
||||||
|
|
||||||
|
if !valueIsString || !prefixIsString {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return shouldStartWith(value, prefix)
|
||||||
|
}
|
||||||
|
func shouldStartWith(value, prefix string) string {
|
||||||
|
if !strings.HasPrefix(value, prefix) {
|
||||||
|
shortval := value
|
||||||
|
if len(shortval) > len(prefix) {
|
||||||
|
shortval = shortval[:len(prefix)] + "..."
|
||||||
|
}
|
||||||
|
return serializer.serialize(prefix, shortval, fmt.Sprintf(shouldHaveStartedWith, value, prefix))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotStartWith receives exactly 2 string parameters and ensures that the first does not start with the second.
|
||||||
|
func ShouldNotStartWith(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
value, valueIsString := actual.(string)
|
||||||
|
prefix, prefixIsString := expected[0].(string)
|
||||||
|
|
||||||
|
if !valueIsString || !prefixIsString {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return shouldNotStartWith(value, prefix)
|
||||||
|
}
|
||||||
|
func shouldNotStartWith(value, prefix string) string {
|
||||||
|
if strings.HasPrefix(value, prefix) {
|
||||||
|
if value == "" {
|
||||||
|
value = "<empty>"
|
||||||
|
}
|
||||||
|
if prefix == "" {
|
||||||
|
prefix = "<empty>"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldNotHaveStartedWith, value, prefix)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldEndWith receives exactly 2 string parameters and ensures that the first ends with the second.
|
||||||
|
func ShouldEndWith(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
value, valueIsString := actual.(string)
|
||||||
|
suffix, suffixIsString := expected[0].(string)
|
||||||
|
|
||||||
|
if !valueIsString || !suffixIsString {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return shouldEndWith(value, suffix)
|
||||||
|
}
|
||||||
|
func shouldEndWith(value, suffix string) string {
|
||||||
|
if !strings.HasSuffix(value, suffix) {
|
||||||
|
shortval := value
|
||||||
|
if len(shortval) > len(suffix) {
|
||||||
|
shortval = "..." + shortval[len(shortval)-len(suffix):]
|
||||||
|
}
|
||||||
|
return serializer.serialize(suffix, shortval, fmt.Sprintf(shouldHaveEndedWith, value, suffix))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldEndWith receives exactly 2 string parameters and ensures that the first does not end with the second.
|
||||||
|
func ShouldNotEndWith(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
value, valueIsString := actual.(string)
|
||||||
|
suffix, suffixIsString := expected[0].(string)
|
||||||
|
|
||||||
|
if !valueIsString || !suffixIsString {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return shouldNotEndWith(value, suffix)
|
||||||
|
}
|
||||||
|
func shouldNotEndWith(value, suffix string) string {
|
||||||
|
if strings.HasSuffix(value, suffix) {
|
||||||
|
if value == "" {
|
||||||
|
value = "<empty>"
|
||||||
|
}
|
||||||
|
if suffix == "" {
|
||||||
|
suffix = "<empty>"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf(shouldNotHaveEndedWith, value, suffix)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldContainSubstring receives exactly 2 string parameters and ensures that the first contains the second as a substring.
|
||||||
|
func ShouldContainSubstring(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
long, longOk := actual.(string)
|
||||||
|
short, shortOk := expected[0].(string)
|
||||||
|
|
||||||
|
if !longOk || !shortOk {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(long, short) {
|
||||||
|
return serializer.serialize(expected[0], actual, fmt.Sprintf(shouldHaveContainedSubstring, long, short))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotContainSubstring receives exactly 2 string parameters and ensures that the first does NOT contain the second as a substring.
|
||||||
|
func ShouldNotContainSubstring(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
long, longOk := actual.(string)
|
||||||
|
short, shortOk := expected[0].(string)
|
||||||
|
|
||||||
|
if !longOk || !shortOk {
|
||||||
|
return fmt.Sprintf(shouldBothBeStrings, reflect.TypeOf(actual), reflect.TypeOf(expected[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(long, short) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveContainedSubstring, long, short)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeBlank receives exactly 1 string parameter and ensures that it is equal to "".
|
||||||
|
func ShouldBeBlank(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
value, ok := actual.(string)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual))
|
||||||
|
}
|
||||||
|
if value != "" {
|
||||||
|
return serializer.serialize("", value, fmt.Sprintf(shouldHaveBeenBlank, value))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotBeBlank receives exactly 1 string parameter and ensures that it is equal to "".
|
||||||
|
func ShouldNotBeBlank(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
value, ok := actual.(string)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Sprintf(shouldBeString, reflect.TypeOf(actual))
|
||||||
|
}
|
||||||
|
if value == "" {
|
||||||
|
return shouldNotHaveBeenBlank
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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])
|
||||||
|
}
|
202
vendor/github.com/smartystreets/assertions/time.go
generated
vendored
Normal file
202
vendor/github.com/smartystreets/assertions/time.go
generated
vendored
Normal file
|
@ -0,0 +1,202 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ShouldHappenBefore receives exactly 2 time.Time arguments and asserts that the first happens before the second.
|
||||||
|
func ShouldHappenBefore(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
expectedTime, secondOk := expected[0].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
|
||||||
|
if !actualTime.Before(expectedTime) {
|
||||||
|
return fmt.Sprintf(shouldHaveHappenedBefore, actualTime, expectedTime, actualTime.Sub(expectedTime))
|
||||||
|
}
|
||||||
|
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenOnOrBefore receives exactly 2 time.Time arguments and asserts that the first happens on or before the second.
|
||||||
|
func ShouldHappenOnOrBefore(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
expectedTime, secondOk := expected[0].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
|
||||||
|
if actualTime.Equal(expectedTime) {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return ShouldHappenBefore(actualTime, expectedTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenAfter receives exactly 2 time.Time arguments and asserts that the first happens after the second.
|
||||||
|
func ShouldHappenAfter(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
expectedTime, secondOk := expected[0].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
if !actualTime.After(expectedTime) {
|
||||||
|
return fmt.Sprintf(shouldHaveHappenedAfter, actualTime, expectedTime, expectedTime.Sub(actualTime))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenOnOrAfter receives exactly 2 time.Time arguments and asserts that the first happens on or after the second.
|
||||||
|
func ShouldHappenOnOrAfter(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
expectedTime, secondOk := expected[0].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
if actualTime.Equal(expectedTime) {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return ShouldHappenAfter(actualTime, expectedTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenBetween receives exactly 3 time.Time arguments and asserts that the first happens between (not on) the second and third.
|
||||||
|
func ShouldHappenBetween(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
min, secondOk := expected[0].(time.Time)
|
||||||
|
max, thirdOk := expected[1].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk || !thirdOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
|
||||||
|
if !actualTime.After(min) {
|
||||||
|
return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, min.Sub(actualTime))
|
||||||
|
}
|
||||||
|
if !actualTime.Before(max) {
|
||||||
|
return fmt.Sprintf(shouldHaveHappenedBetween, actualTime, min, max, actualTime.Sub(max))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first happens between or on the second and third.
|
||||||
|
func ShouldHappenOnOrBetween(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
min, secondOk := expected[0].(time.Time)
|
||||||
|
max, thirdOk := expected[1].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk || !thirdOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
if actualTime.Equal(min) || actualTime.Equal(max) {
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
return ShouldHappenBetween(actualTime, min, max)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotHappenOnOrBetween receives exactly 3 time.Time arguments and asserts that the first
|
||||||
|
// does NOT happen between or on the second or third.
|
||||||
|
func ShouldNotHappenOnOrBetween(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
min, secondOk := expected[0].(time.Time)
|
||||||
|
max, thirdOk := expected[1].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk || !thirdOk {
|
||||||
|
return shouldUseTimes
|
||||||
|
}
|
||||||
|
if actualTime.Equal(min) || actualTime.Equal(max) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max)
|
||||||
|
}
|
||||||
|
if actualTime.After(min) && actualTime.Before(max) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveHappenedOnOrBetween, actualTime, min, max)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments)
|
||||||
|
// and asserts that the first time.Time happens within or on the duration specified relative to
|
||||||
|
// the other time.Time.
|
||||||
|
func ShouldHappenWithin(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
tolerance, secondOk := expected[0].(time.Duration)
|
||||||
|
threshold, thirdOk := expected[1].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk || !thirdOk {
|
||||||
|
return shouldUseDurationAndTime
|
||||||
|
}
|
||||||
|
|
||||||
|
min := threshold.Add(-tolerance)
|
||||||
|
max := threshold.Add(tolerance)
|
||||||
|
return ShouldHappenOnOrBetween(actualTime, min, max)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotHappenWithin receives a time.Time, a time.Duration, and a time.Time (3 arguments)
|
||||||
|
// and asserts that the first time.Time does NOT happen within or on the duration specified relative to
|
||||||
|
// the other time.Time.
|
||||||
|
func ShouldNotHappenWithin(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(2, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
actualTime, firstOk := actual.(time.Time)
|
||||||
|
tolerance, secondOk := expected[0].(time.Duration)
|
||||||
|
threshold, thirdOk := expected[1].(time.Time)
|
||||||
|
|
||||||
|
if !firstOk || !secondOk || !thirdOk {
|
||||||
|
return shouldUseDurationAndTime
|
||||||
|
}
|
||||||
|
|
||||||
|
min := threshold.Add(-tolerance)
|
||||||
|
max := threshold.Add(tolerance)
|
||||||
|
return ShouldNotHappenOnOrBetween(actualTime, min, max)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldBeChronological receives a []time.Time slice and asserts that the are
|
||||||
|
// in chronological order starting with the first time.Time as the earliest.
|
||||||
|
func ShouldBeChronological(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(0, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
times, ok := actual.([]time.Time)
|
||||||
|
if !ok {
|
||||||
|
return shouldUseTimeSlice
|
||||||
|
}
|
||||||
|
|
||||||
|
var previous time.Time
|
||||||
|
for i, current := range times {
|
||||||
|
if i > 0 && current.Before(previous) {
|
||||||
|
return fmt.Sprintf(shouldHaveBeenChronological,
|
||||||
|
i, i-1, previous.String(), i, current.String())
|
||||||
|
}
|
||||||
|
previous = current
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
112
vendor/github.com/smartystreets/assertions/type.go
generated
vendored
Normal file
112
vendor/github.com/smartystreets/assertions/type.go
generated
vendored
Normal file
|
@ -0,0 +1,112 @@
|
||||||
|
package assertions
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ShouldHaveSameTypeAs receives exactly two parameters and compares their underlying types for equality.
|
||||||
|
func ShouldHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
first := reflect.TypeOf(actual)
|
||||||
|
second := reflect.TypeOf(expected[0])
|
||||||
|
|
||||||
|
if equal := ShouldEqual(first, second); equal != success {
|
||||||
|
return serializer.serialize(second, first, fmt.Sprintf(shouldHaveBeenA, actual, second, first))
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotHaveSameTypeAs receives exactly two parameters and compares their underlying types for inequality.
|
||||||
|
func ShouldNotHaveSameTypeAs(actual interface{}, expected ...interface{}) string {
|
||||||
|
if fail := need(1, expected); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
first := reflect.TypeOf(actual)
|
||||||
|
second := reflect.TypeOf(expected[0])
|
||||||
|
|
||||||
|
if equal := ShouldEqual(first, second); equal == success {
|
||||||
|
return fmt.Sprintf(shouldNotHaveBeenA, actual, second)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldImplement receives exactly two parameters and ensures
|
||||||
|
// that the first implements the interface type of the second.
|
||||||
|
func ShouldImplement(actual interface{}, expectedList ...interface{}) string {
|
||||||
|
if fail := need(1, expectedList); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := expectedList[0]
|
||||||
|
if fail := ShouldBeNil(expected); fail != success {
|
||||||
|
return shouldCompareWithInterfacePointer
|
||||||
|
}
|
||||||
|
|
||||||
|
if fail := ShouldNotBeNil(actual); fail != success {
|
||||||
|
return shouldNotBeNilActual
|
||||||
|
}
|
||||||
|
|
||||||
|
var actualType reflect.Type
|
||||||
|
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
|
||||||
|
actualType = reflect.PtrTo(reflect.TypeOf(actual))
|
||||||
|
} else {
|
||||||
|
actualType = reflect.TypeOf(actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedType := reflect.TypeOf(expected)
|
||||||
|
if fail := ShouldNotBeNil(expectedType); fail != success {
|
||||||
|
return shouldCompareWithInterfacePointer
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedInterface := expectedType.Elem()
|
||||||
|
|
||||||
|
if actualType == nil {
|
||||||
|
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !actualType.Implements(expectedInterface) {
|
||||||
|
return fmt.Sprintf(shouldHaveImplemented, expectedInterface, actualType)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShouldNotImplement receives exactly two parameters and ensures
|
||||||
|
// that the first does NOT implement the interface type of the second.
|
||||||
|
func ShouldNotImplement(actual interface{}, expectedList ...interface{}) string {
|
||||||
|
if fail := need(1, expectedList); fail != success {
|
||||||
|
return fail
|
||||||
|
}
|
||||||
|
|
||||||
|
expected := expectedList[0]
|
||||||
|
if fail := ShouldBeNil(expected); fail != success {
|
||||||
|
return shouldCompareWithInterfacePointer
|
||||||
|
}
|
||||||
|
|
||||||
|
if fail := ShouldNotBeNil(actual); fail != success {
|
||||||
|
return shouldNotBeNilActual
|
||||||
|
}
|
||||||
|
|
||||||
|
var actualType reflect.Type
|
||||||
|
if reflect.TypeOf(actual).Kind() != reflect.Ptr {
|
||||||
|
actualType = reflect.PtrTo(reflect.TypeOf(actual))
|
||||||
|
} else {
|
||||||
|
actualType = reflect.TypeOf(actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedType := reflect.TypeOf(expected)
|
||||||
|
if fail := ShouldNotBeNil(expectedType); fail != success {
|
||||||
|
return shouldCompareWithInterfacePointer
|
||||||
|
}
|
||||||
|
|
||||||
|
expectedInterface := expectedType.Elem()
|
||||||
|
|
||||||
|
if actualType.Implements(expectedInterface) {
|
||||||
|
return fmt.Sprintf(shouldNotHaveImplemented, actualType, expectedInterface)
|
||||||
|
}
|
||||||
|
return success
|
||||||
|
}
|
|
@ -1,6 +1,4 @@
|
||||||
The MIT License (MIT)
|
Copyright (c) 2016 SmartyStreets, LLC
|
||||||
|
|
||||||
Copyright (c) 2014 - 2016 Ian Kent
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
@ -19,3 +17,7 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
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
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
SOFTWARE.
|
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.
|
68
vendor/github.com/smartystreets/goconvey/convey/assertions.go
generated
vendored
Normal file
68
vendor/github.com/smartystreets/goconvey/convey/assertions.go
generated
vendored
Normal file
|
@ -0,0 +1,68 @@
|
||||||
|
package convey
|
||||||
|
|
||||||
|
import "github.com/smartystreets/assertions"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ShouldEqual = assertions.ShouldEqual
|
||||||
|
ShouldNotEqual = assertions.ShouldNotEqual
|
||||||
|
ShouldAlmostEqual = assertions.ShouldAlmostEqual
|
||||||
|
ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual
|
||||||
|
ShouldResemble = assertions.ShouldResemble
|
||||||
|
ShouldNotResemble = assertions.ShouldNotResemble
|
||||||
|
ShouldPointTo = assertions.ShouldPointTo
|
||||||
|
ShouldNotPointTo = assertions.ShouldNotPointTo
|
||||||
|
ShouldBeNil = assertions.ShouldBeNil
|
||||||
|
ShouldNotBeNil = assertions.ShouldNotBeNil
|
||||||
|
ShouldBeTrue = assertions.ShouldBeTrue
|
||||||
|
ShouldBeFalse = assertions.ShouldBeFalse
|
||||||
|
ShouldBeZeroValue = assertions.ShouldBeZeroValue
|
||||||
|
|
||||||
|
ShouldBeGreaterThan = assertions.ShouldBeGreaterThan
|
||||||
|
ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo
|
||||||
|
ShouldBeLessThan = assertions.ShouldBeLessThan
|
||||||
|
ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo
|
||||||
|
ShouldBeBetween = assertions.ShouldBeBetween
|
||||||
|
ShouldNotBeBetween = assertions.ShouldNotBeBetween
|
||||||
|
ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual
|
||||||
|
ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual
|
||||||
|
|
||||||
|
ShouldContain = assertions.ShouldContain
|
||||||
|
ShouldNotContain = assertions.ShouldNotContain
|
||||||
|
ShouldContainKey = assertions.ShouldContainKey
|
||||||
|
ShouldNotContainKey = assertions.ShouldNotContainKey
|
||||||
|
ShouldBeIn = assertions.ShouldBeIn
|
||||||
|
ShouldNotBeIn = assertions.ShouldNotBeIn
|
||||||
|
ShouldBeEmpty = assertions.ShouldBeEmpty
|
||||||
|
ShouldNotBeEmpty = assertions.ShouldNotBeEmpty
|
||||||
|
ShouldHaveLength = assertions.ShouldHaveLength
|
||||||
|
|
||||||
|
ShouldStartWith = assertions.ShouldStartWith
|
||||||
|
ShouldNotStartWith = assertions.ShouldNotStartWith
|
||||||
|
ShouldEndWith = assertions.ShouldEndWith
|
||||||
|
ShouldNotEndWith = assertions.ShouldNotEndWith
|
||||||
|
ShouldBeBlank = assertions.ShouldBeBlank
|
||||||
|
ShouldNotBeBlank = assertions.ShouldNotBeBlank
|
||||||
|
ShouldContainSubstring = assertions.ShouldContainSubstring
|
||||||
|
ShouldNotContainSubstring = assertions.ShouldNotContainSubstring
|
||||||
|
|
||||||
|
ShouldPanic = assertions.ShouldPanic
|
||||||
|
ShouldNotPanic = assertions.ShouldNotPanic
|
||||||
|
ShouldPanicWith = assertions.ShouldPanicWith
|
||||||
|
ShouldNotPanicWith = assertions.ShouldNotPanicWith
|
||||||
|
|
||||||
|
ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs
|
||||||
|
ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs
|
||||||
|
ShouldImplement = assertions.ShouldImplement
|
||||||
|
ShouldNotImplement = assertions.ShouldNotImplement
|
||||||
|
|
||||||
|
ShouldHappenBefore = assertions.ShouldHappenBefore
|
||||||
|
ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore
|
||||||
|
ShouldHappenAfter = assertions.ShouldHappenAfter
|
||||||
|
ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter
|
||||||
|
ShouldHappenBetween = assertions.ShouldHappenBetween
|
||||||
|
ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween
|
||||||
|
ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween
|
||||||
|
ShouldHappenWithin = assertions.ShouldHappenWithin
|
||||||
|
ShouldNotHappenWithin = assertions.ShouldNotHappenWithin
|
||||||
|
ShouldBeChronological = assertions.ShouldBeChronological
|
||||||
|
)
|
272
vendor/github.com/smartystreets/goconvey/convey/context.go
generated
vendored
Normal file
272
vendor/github.com/smartystreets/goconvey/convey/context.go
generated
vendored
Normal file
|
@ -0,0 +1,272 @@
|
||||||
|
package convey
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jtolds/gls"
|
||||||
|
"github.com/smartystreets/goconvey/convey/reporting"
|
||||||
|
)
|
||||||
|
|
||||||
|
type conveyErr struct {
|
||||||
|
fmt string
|
||||||
|
params []interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *conveyErr) Error() string {
|
||||||
|
return fmt.Sprintf(e.fmt, e.params...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func conveyPanic(fmt string, params ...interface{}) {
|
||||||
|
panic(&conveyErr{fmt, params})
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
missingGoTest = `Top-level calls to Convey(...) need a reference to the *testing.T.
|
||||||
|
Hint: Convey("description here", t, func() { /* notice that the second argument was the *testing.T (t)! */ }) `
|
||||||
|
extraGoTest = `Only the top-level call to Convey(...) needs a reference to the *testing.T.`
|
||||||
|
noStackContext = "Convey operation made without context on goroutine stack.\n" +
|
||||||
|
"Hint: Perhaps you meant to use `Convey(..., func(c C){...})` ?"
|
||||||
|
differentConveySituations = "Different set of Convey statements on subsequent pass!\nDid not expect %#v."
|
||||||
|
multipleIdenticalConvey = "Multiple convey suites with identical names: %#v"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
failureHalt = "___FAILURE_HALT___"
|
||||||
|
|
||||||
|
nodeKey = "node"
|
||||||
|
)
|
||||||
|
|
||||||
|
///////////////////////////////// Stack Context /////////////////////////////////
|
||||||
|
|
||||||
|
func getCurrentContext() *context {
|
||||||
|
ctx, ok := ctxMgr.GetValue(nodeKey)
|
||||||
|
if ok {
|
||||||
|
return ctx.(*context)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustGetCurrentContext() *context {
|
||||||
|
ctx := getCurrentContext()
|
||||||
|
if ctx == nil {
|
||||||
|
conveyPanic(noStackContext)
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////// Context ////////////////////////////////////
|
||||||
|
|
||||||
|
// context magically handles all coordination of Convey's and So assertions.
|
||||||
|
//
|
||||||
|
// It is tracked on the stack as goroutine-local-storage with the gls package,
|
||||||
|
// or explicitly if the user decides to call convey like:
|
||||||
|
//
|
||||||
|
// Convey(..., func(c C) {
|
||||||
|
// c.So(...)
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// This implements the `C` interface.
|
||||||
|
type context struct {
|
||||||
|
reporter reporting.Reporter
|
||||||
|
|
||||||
|
children map[string]*context
|
||||||
|
|
||||||
|
resets []func()
|
||||||
|
|
||||||
|
executedOnce bool
|
||||||
|
expectChildRun *bool
|
||||||
|
complete bool
|
||||||
|
|
||||||
|
focus bool
|
||||||
|
failureMode FailureMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// rootConvey is the main entry point to a test suite. This is called when
|
||||||
|
// there's no context in the stack already, and items must contain a `t` object,
|
||||||
|
// or this panics.
|
||||||
|
func rootConvey(items ...interface{}) {
|
||||||
|
entry := discover(items)
|
||||||
|
|
||||||
|
if entry.Test == nil {
|
||||||
|
conveyPanic(missingGoTest)
|
||||||
|
}
|
||||||
|
|
||||||
|
expectChildRun := true
|
||||||
|
ctx := &context{
|
||||||
|
reporter: buildReporter(),
|
||||||
|
|
||||||
|
children: make(map[string]*context),
|
||||||
|
|
||||||
|
expectChildRun: &expectChildRun,
|
||||||
|
|
||||||
|
focus: entry.Focus,
|
||||||
|
failureMode: defaultFailureMode.combine(entry.FailMode),
|
||||||
|
}
|
||||||
|
ctxMgr.SetValues(gls.Values{nodeKey: ctx}, func() {
|
||||||
|
ctx.reporter.BeginStory(reporting.NewStoryReport(entry.Test))
|
||||||
|
defer ctx.reporter.EndStory()
|
||||||
|
|
||||||
|
for ctx.shouldVisit() {
|
||||||
|
ctx.conveyInner(entry.Situation, entry.Func)
|
||||||
|
expectChildRun = true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////// Methods ////////////////////////////////////
|
||||||
|
|
||||||
|
func (ctx *context) SkipConvey(items ...interface{}) {
|
||||||
|
ctx.Convey(items, skipConvey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) FocusConvey(items ...interface{}) {
|
||||||
|
ctx.Convey(items, focusConvey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) Convey(items ...interface{}) {
|
||||||
|
entry := discover(items)
|
||||||
|
|
||||||
|
// we're a branch, or leaf (on the wind)
|
||||||
|
if entry.Test != nil {
|
||||||
|
conveyPanic(extraGoTest)
|
||||||
|
}
|
||||||
|
if ctx.focus && !entry.Focus {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var inner_ctx *context
|
||||||
|
if ctx.executedOnce {
|
||||||
|
var ok bool
|
||||||
|
inner_ctx, ok = ctx.children[entry.Situation]
|
||||||
|
if !ok {
|
||||||
|
conveyPanic(differentConveySituations, entry.Situation)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if _, ok := ctx.children[entry.Situation]; ok {
|
||||||
|
conveyPanic(multipleIdenticalConvey, entry.Situation)
|
||||||
|
}
|
||||||
|
inner_ctx = &context{
|
||||||
|
reporter: ctx.reporter,
|
||||||
|
|
||||||
|
children: make(map[string]*context),
|
||||||
|
|
||||||
|
expectChildRun: ctx.expectChildRun,
|
||||||
|
|
||||||
|
focus: entry.Focus,
|
||||||
|
failureMode: ctx.failureMode.combine(entry.FailMode),
|
||||||
|
}
|
||||||
|
ctx.children[entry.Situation] = inner_ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
if inner_ctx.shouldVisit() {
|
||||||
|
ctxMgr.SetValues(gls.Values{nodeKey: inner_ctx}, func() {
|
||||||
|
inner_ctx.conveyInner(entry.Situation, entry.Func)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) SkipSo(stuff ...interface{}) {
|
||||||
|
ctx.assertionReport(reporting.NewSkipReport())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) So(actual interface{}, assert assertion, expected ...interface{}) {
|
||||||
|
if result := assert(actual, expected...); result == assertionSuccess {
|
||||||
|
ctx.assertionReport(reporting.NewSuccessReport())
|
||||||
|
} else {
|
||||||
|
ctx.assertionReport(reporting.NewFailureReport(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) Reset(action func()) {
|
||||||
|
/* TODO: Failure mode configuration */
|
||||||
|
ctx.resets = append(ctx.resets, action)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) Print(items ...interface{}) (int, error) {
|
||||||
|
fmt.Fprint(ctx.reporter, items...)
|
||||||
|
return fmt.Print(items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) Println(items ...interface{}) (int, error) {
|
||||||
|
fmt.Fprintln(ctx.reporter, items...)
|
||||||
|
return fmt.Println(items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ctx *context) Printf(format string, items ...interface{}) (int, error) {
|
||||||
|
fmt.Fprintf(ctx.reporter, format, items...)
|
||||||
|
return fmt.Printf(format, items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////// Private ////////////////////////////////////
|
||||||
|
|
||||||
|
// shouldVisit returns true iff we should traverse down into a Convey. Note
|
||||||
|
// that just because we don't traverse a Convey this time, doesn't mean that
|
||||||
|
// we may not traverse it on a subsequent pass.
|
||||||
|
func (c *context) shouldVisit() bool {
|
||||||
|
return !c.complete && *c.expectChildRun
|
||||||
|
}
|
||||||
|
|
||||||
|
// conveyInner is the function which actually executes the user's anonymous test
|
||||||
|
// function body. At this point, Convey or RootConvey has decided that this
|
||||||
|
// function should actually run.
|
||||||
|
func (ctx *context) conveyInner(situation string, f func(C)) {
|
||||||
|
// Record/Reset state for next time.
|
||||||
|
defer func() {
|
||||||
|
ctx.executedOnce = true
|
||||||
|
|
||||||
|
// This is only needed at the leaves, but there's no harm in also setting it
|
||||||
|
// when returning from branch Convey's
|
||||||
|
*ctx.expectChildRun = false
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Set up+tear down our scope for the reporter
|
||||||
|
ctx.reporter.Enter(reporting.NewScopeReport(situation))
|
||||||
|
defer ctx.reporter.Exit()
|
||||||
|
|
||||||
|
// Recover from any panics in f, and assign the `complete` status for this
|
||||||
|
// node of the tree.
|
||||||
|
defer func() {
|
||||||
|
ctx.complete = true
|
||||||
|
if problem := recover(); problem != nil {
|
||||||
|
if problem, ok := problem.(*conveyErr); ok {
|
||||||
|
panic(problem)
|
||||||
|
}
|
||||||
|
if problem != failureHalt {
|
||||||
|
ctx.reporter.Report(reporting.NewErrorReport(problem))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for _, child := range ctx.children {
|
||||||
|
if !child.complete {
|
||||||
|
ctx.complete = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Resets are registered as the `f` function executes, so nil them here.
|
||||||
|
// All resets are run in registration order (FIFO).
|
||||||
|
ctx.resets = []func(){}
|
||||||
|
defer func() {
|
||||||
|
for _, r := range ctx.resets {
|
||||||
|
// panics handled by the previous defer
|
||||||
|
r()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if f == nil {
|
||||||
|
// if f is nil, this was either a Convey(..., nil), or a SkipConvey
|
||||||
|
ctx.reporter.Report(reporting.NewSkipReport())
|
||||||
|
} else {
|
||||||
|
f(ctx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// assertionReport is a helper for So and SkipSo which makes the report and
|
||||||
|
// then possibly panics, depending on the current context's failureMode.
|
||||||
|
func (ctx *context) assertionReport(r *reporting.AssertionResult) {
|
||||||
|
ctx.reporter.Report(r)
|
||||||
|
if r.Failure != "" && ctx.failureMode == FailureHalts {
|
||||||
|
panic(failureHalt)
|
||||||
|
}
|
||||||
|
}
|
4
vendor/github.com/smartystreets/goconvey/convey/convey.goconvey
generated
vendored
Normal file
4
vendor/github.com/smartystreets/goconvey/convey/convey.goconvey
generated
vendored
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
#ignore
|
||||||
|
-timeout=1s
|
||||||
|
#-covermode=count
|
||||||
|
#-coverpkg=github.com/smartystreets/goconvey/convey,github.com/smartystreets/goconvey/convey/gotest,github.com/smartystreets/goconvey/convey/reporting
|
103
vendor/github.com/smartystreets/goconvey/convey/discovery.go
generated
vendored
Normal file
103
vendor/github.com/smartystreets/goconvey/convey/discovery.go
generated
vendored
Normal file
|
@ -0,0 +1,103 @@
|
||||||
|
package convey
|
||||||
|
|
||||||
|
type actionSpecifier uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
noSpecifier actionSpecifier = iota
|
||||||
|
skipConvey
|
||||||
|
focusConvey
|
||||||
|
)
|
||||||
|
|
||||||
|
type suite struct {
|
||||||
|
Situation string
|
||||||
|
Test t
|
||||||
|
Focus bool
|
||||||
|
Func func(C) // nil means skipped
|
||||||
|
FailMode FailureMode
|
||||||
|
}
|
||||||
|
|
||||||
|
func newSuite(situation string, failureMode FailureMode, f func(C), test t, specifier actionSpecifier) *suite {
|
||||||
|
ret := &suite{
|
||||||
|
Situation: situation,
|
||||||
|
Test: test,
|
||||||
|
Func: f,
|
||||||
|
FailMode: failureMode,
|
||||||
|
}
|
||||||
|
switch specifier {
|
||||||
|
case skipConvey:
|
||||||
|
ret.Func = nil
|
||||||
|
case focusConvey:
|
||||||
|
ret.Focus = true
|
||||||
|
}
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func discover(items []interface{}) *suite {
|
||||||
|
name, items := parseName(items)
|
||||||
|
test, items := parseGoTest(items)
|
||||||
|
failure, items := parseFailureMode(items)
|
||||||
|
action, items := parseAction(items)
|
||||||
|
specifier, items := parseSpecifier(items)
|
||||||
|
|
||||||
|
if len(items) != 0 {
|
||||||
|
conveyPanic(parseError)
|
||||||
|
}
|
||||||
|
|
||||||
|
return newSuite(name, failure, action, test, specifier)
|
||||||
|
}
|
||||||
|
func item(items []interface{}) interface{} {
|
||||||
|
if len(items) == 0 {
|
||||||
|
conveyPanic(parseError)
|
||||||
|
}
|
||||||
|
return items[0]
|
||||||
|
}
|
||||||
|
func parseName(items []interface{}) (string, []interface{}) {
|
||||||
|
if name, parsed := item(items).(string); parsed {
|
||||||
|
return name, items[1:]
|
||||||
|
}
|
||||||
|
conveyPanic(parseError)
|
||||||
|
panic("never get here")
|
||||||
|
}
|
||||||
|
func parseGoTest(items []interface{}) (t, []interface{}) {
|
||||||
|
if test, parsed := item(items).(t); parsed {
|
||||||
|
return test, items[1:]
|
||||||
|
}
|
||||||
|
return nil, items
|
||||||
|
}
|
||||||
|
func parseFailureMode(items []interface{}) (FailureMode, []interface{}) {
|
||||||
|
if mode, parsed := item(items).(FailureMode); parsed {
|
||||||
|
return mode, items[1:]
|
||||||
|
}
|
||||||
|
return FailureInherits, items
|
||||||
|
}
|
||||||
|
func parseAction(items []interface{}) (func(C), []interface{}) {
|
||||||
|
switch x := item(items).(type) {
|
||||||
|
case nil:
|
||||||
|
return nil, items[1:]
|
||||||
|
case func(C):
|
||||||
|
return x, items[1:]
|
||||||
|
case func():
|
||||||
|
return func(C) { x() }, items[1:]
|
||||||
|
}
|
||||||
|
conveyPanic(parseError)
|
||||||
|
panic("never get here")
|
||||||
|
}
|
||||||
|
func parseSpecifier(items []interface{}) (actionSpecifier, []interface{}) {
|
||||||
|
if len(items) == 0 {
|
||||||
|
return noSpecifier, items
|
||||||
|
}
|
||||||
|
if spec, ok := items[0].(actionSpecifier); ok {
|
||||||
|
return spec, items[1:]
|
||||||
|
}
|
||||||
|
conveyPanic(parseError)
|
||||||
|
panic("never get here")
|
||||||
|
}
|
||||||
|
|
||||||
|
// This interface allows us to pass the *testing.T struct
|
||||||
|
// throughout the internals of this package without ever
|
||||||
|
// having to import the "testing" package.
|
||||||
|
type t interface {
|
||||||
|
Fail()
|
||||||
|
}
|
||||||
|
|
||||||
|
const parseError = "You must provide a name (string), then a *testing.T (if in outermost scope), an optional FailureMode, and then an action (func())."
|
218
vendor/github.com/smartystreets/goconvey/convey/doc.go
generated
vendored
Normal file
218
vendor/github.com/smartystreets/goconvey/convey/doc.go
generated
vendored
Normal file
|
@ -0,0 +1,218 @@
|
||||||
|
// Package convey contains all of the public-facing entry points to this project.
|
||||||
|
// This means that it should never be required of the user to import any other
|
||||||
|
// packages from this project as they serve internal purposes.
|
||||||
|
package convey
|
||||||
|
|
||||||
|
import "github.com/smartystreets/goconvey/convey/reporting"
|
||||||
|
|
||||||
|
////////////////////////////////// suite //////////////////////////////////
|
||||||
|
|
||||||
|
// C is the Convey context which you can optionally obtain in your action
|
||||||
|
// by calling Convey like:
|
||||||
|
//
|
||||||
|
// Convey(..., func(c C) {
|
||||||
|
// ...
|
||||||
|
// })
|
||||||
|
//
|
||||||
|
// See the documentation on Convey for more details.
|
||||||
|
//
|
||||||
|
// All methods in this context behave identically to the global functions of the
|
||||||
|
// same name in this package.
|
||||||
|
type C interface {
|
||||||
|
Convey(items ...interface{})
|
||||||
|
SkipConvey(items ...interface{})
|
||||||
|
FocusConvey(items ...interface{})
|
||||||
|
|
||||||
|
So(actual interface{}, assert assertion, expected ...interface{})
|
||||||
|
SkipSo(stuff ...interface{})
|
||||||
|
|
||||||
|
Reset(action func())
|
||||||
|
|
||||||
|
Println(items ...interface{}) (int, error)
|
||||||
|
Print(items ...interface{}) (int, error)
|
||||||
|
Printf(format string, items ...interface{}) (int, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convey is the method intended for use when declaring the scopes of
|
||||||
|
// a specification. Each scope has a description and a func() which may contain
|
||||||
|
// other calls to Convey(), Reset() or Should-style assertions. Convey calls can
|
||||||
|
// be nested as far as you see fit.
|
||||||
|
//
|
||||||
|
// IMPORTANT NOTE: The top-level Convey() within a Test method
|
||||||
|
// must conform to the following signature:
|
||||||
|
//
|
||||||
|
// Convey(description string, t *testing.T, action func())
|
||||||
|
//
|
||||||
|
// All other calls should look like this (no need to pass in *testing.T):
|
||||||
|
//
|
||||||
|
// Convey(description string, action func())
|
||||||
|
//
|
||||||
|
// Don't worry, goconvey will panic if you get it wrong so you can fix it.
|
||||||
|
//
|
||||||
|
// Additionally, you may explicitly obtain access to the Convey context by doing:
|
||||||
|
//
|
||||||
|
// Convey(description string, action func(c C))
|
||||||
|
//
|
||||||
|
// You may need to do this if you want to pass the context through to a
|
||||||
|
// goroutine, or to close over the context in a handler to a library which
|
||||||
|
// calls your handler in a goroutine (httptest comes to mind).
|
||||||
|
//
|
||||||
|
// All Convey()-blocks also accept an optional parameter of FailureMode which sets
|
||||||
|
// how goconvey should treat failures for So()-assertions in the block and
|
||||||
|
// nested blocks. See the constants in this file for the available options.
|
||||||
|
//
|
||||||
|
// By default it will inherit from its parent block and the top-level blocks
|
||||||
|
// default to the FailureHalts setting.
|
||||||
|
//
|
||||||
|
// This parameter is inserted before the block itself:
|
||||||
|
//
|
||||||
|
// Convey(description string, t *testing.T, mode FailureMode, action func())
|
||||||
|
// Convey(description string, mode FailureMode, action func())
|
||||||
|
//
|
||||||
|
// See the examples package for, well, examples.
|
||||||
|
func Convey(items ...interface{}) {
|
||||||
|
if ctx := getCurrentContext(); ctx == nil {
|
||||||
|
rootConvey(items...)
|
||||||
|
} else {
|
||||||
|
ctx.Convey(items...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SkipConvey is analagous to Convey except that the scope is not executed
|
||||||
|
// (which means that child scopes defined within this scope are not run either).
|
||||||
|
// The reporter will be notified that this step was skipped.
|
||||||
|
func SkipConvey(items ...interface{}) {
|
||||||
|
Convey(append(items, skipConvey)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FocusConvey is has the inverse effect of SkipConvey. If the top-level
|
||||||
|
// Convey is changed to `FocusConvey`, only nested scopes that are defined
|
||||||
|
// with FocusConvey will be run. The rest will be ignored completely. This
|
||||||
|
// is handy when debugging a large suite that runs a misbehaving function
|
||||||
|
// repeatedly as you can disable all but one of that function
|
||||||
|
// without swaths of `SkipConvey` calls, just a targeted chain of calls
|
||||||
|
// to FocusConvey.
|
||||||
|
func FocusConvey(items ...interface{}) {
|
||||||
|
Convey(append(items, focusConvey)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset registers a cleanup function to be run after each Convey()
|
||||||
|
// in the same scope. See the examples package for a simple use case.
|
||||||
|
func Reset(action func()) {
|
||||||
|
mustGetCurrentContext().Reset(action)
|
||||||
|
}
|
||||||
|
|
||||||
|
/////////////////////////////////// Assertions ///////////////////////////////////
|
||||||
|
|
||||||
|
// assertion is an alias for a function with a signature that the convey.So()
|
||||||
|
// method can handle. Any future or custom assertions should conform to this
|
||||||
|
// method signature. The return value should be an empty string if the assertion
|
||||||
|
// passes and a well-formed failure message if not.
|
||||||
|
type assertion func(actual interface{}, expected ...interface{}) string
|
||||||
|
|
||||||
|
const assertionSuccess = ""
|
||||||
|
|
||||||
|
// So is the means by which assertions are made against the system under test.
|
||||||
|
// The majority of exported names in the assertions package begin with the word
|
||||||
|
// 'Should' and describe how the first argument (actual) should compare with any
|
||||||
|
// of the final (expected) arguments. How many final arguments are accepted
|
||||||
|
// depends on the particular assertion that is passed in as the assert argument.
|
||||||
|
// See the examples package for use cases and the assertions package for
|
||||||
|
// documentation on specific assertion methods. A failing assertion will
|
||||||
|
// cause t.Fail() to be invoked--you should never call this method (or other
|
||||||
|
// failure-inducing methods) in your test code. Leave that to GoConvey.
|
||||||
|
func So(actual interface{}, assert assertion, expected ...interface{}) {
|
||||||
|
mustGetCurrentContext().So(actual, assert, expected...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SkipSo is analagous to So except that the assertion that would have been passed
|
||||||
|
// to So is not executed and the reporter is notified that the assertion was skipped.
|
||||||
|
func SkipSo(stuff ...interface{}) {
|
||||||
|
mustGetCurrentContext().SkipSo()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailureMode is a type which determines how the So() blocks should fail
|
||||||
|
// if their assertion fails. See constants further down for acceptable values
|
||||||
|
type FailureMode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
|
||||||
|
// FailureContinues is a failure mode which prevents failing
|
||||||
|
// So()-assertions from halting Convey-block execution, instead
|
||||||
|
// allowing the test to continue past failing So()-assertions.
|
||||||
|
FailureContinues FailureMode = "continue"
|
||||||
|
|
||||||
|
// FailureHalts is the default setting for a top-level Convey()-block
|
||||||
|
// and will cause all failing So()-assertions to halt further execution
|
||||||
|
// in that test-arm and continue on to the next arm.
|
||||||
|
FailureHalts FailureMode = "halt"
|
||||||
|
|
||||||
|
// FailureInherits is the default setting for failure-mode, it will
|
||||||
|
// default to the failure-mode of the parent block. You should never
|
||||||
|
// need to specify this mode in your tests..
|
||||||
|
FailureInherits FailureMode = "inherits"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (f FailureMode) combine(other FailureMode) FailureMode {
|
||||||
|
if other == FailureInherits {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
return other
|
||||||
|
}
|
||||||
|
|
||||||
|
var defaultFailureMode FailureMode = FailureHalts
|
||||||
|
|
||||||
|
// SetDefaultFailureMode allows you to specify the default failure mode
|
||||||
|
// for all Convey blocks. It is meant to be used in an init function to
|
||||||
|
// allow the default mode to be changdd across all tests for an entire packgae
|
||||||
|
// but it can be used anywhere.
|
||||||
|
func SetDefaultFailureMode(mode FailureMode) {
|
||||||
|
if mode == FailureContinues || mode == FailureHalts {
|
||||||
|
defaultFailureMode = mode
|
||||||
|
} else {
|
||||||
|
panic("You may only use the constants named 'FailureContinues' and 'FailureHalts' as default failure modes.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////// Print functions ////////////////////////////////////
|
||||||
|
|
||||||
|
// Print is analogous to fmt.Print (and it even calls fmt.Print). It ensures that
|
||||||
|
// output is aligned with the corresponding scopes in the web UI.
|
||||||
|
func Print(items ...interface{}) (written int, err error) {
|
||||||
|
return mustGetCurrentContext().Print(items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print is analogous to fmt.Println (and it even calls fmt.Println). It ensures that
|
||||||
|
// output is aligned with the corresponding scopes in the web UI.
|
||||||
|
func Println(items ...interface{}) (written int, err error) {
|
||||||
|
return mustGetCurrentContext().Println(items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print is analogous to fmt.Printf (and it even calls fmt.Printf). It ensures that
|
||||||
|
// output is aligned with the corresponding scopes in the web UI.
|
||||||
|
func Printf(format string, items ...interface{}) (written int, err error) {
|
||||||
|
return mustGetCurrentContext().Printf(format, items...)
|
||||||
|
}
|
||||||
|
|
||||||
|
///////////////////////////////////////////////////////////////////////////////
|
||||||
|
|
||||||
|
// SuppressConsoleStatistics prevents automatic printing of console statistics.
|
||||||
|
// Calling PrintConsoleStatistics explicitly will force printing of statistics.
|
||||||
|
func SuppressConsoleStatistics() {
|
||||||
|
reporting.SuppressConsoleStatistics()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsoleStatistics may be called at any time to print assertion statistics.
|
||||||
|
// Generally, the best place to do this would be in a TestMain function,
|
||||||
|
// after all tests have been run. Something like this:
|
||||||
|
//
|
||||||
|
// func TestMain(m *testing.M) {
|
||||||
|
// convey.SuppressConsoleStatistics()
|
||||||
|
// result := m.Run()
|
||||||
|
// convey.PrintConsoleStatistics()
|
||||||
|
// os.Exit(result)
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
func PrintConsoleStatistics() {
|
||||||
|
reporting.PrintConsoleStatistics()
|
||||||
|
}
|
28
vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go
generated
vendored
Normal file
28
vendor/github.com/smartystreets/goconvey/convey/gotest/utils.go
generated
vendored
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
// Package gotest contains internal functionality. Although this package
|
||||||
|
// contains one or more exported names it is not intended for public
|
||||||
|
// consumption. See the examples package for how to use this project.
|
||||||
|
package gotest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ResolveExternalCaller() (file string, line int, name string) {
|
||||||
|
var caller_id uintptr
|
||||||
|
callers := runtime.Callers(0, callStack)
|
||||||
|
|
||||||
|
for x := 0; x < callers; x++ {
|
||||||
|
caller_id, file, line, _ = runtime.Caller(x)
|
||||||
|
if strings.HasSuffix(file, "_test.go") || strings.HasSuffix(file, "_tests.go") {
|
||||||
|
name = runtime.FuncForPC(caller_id).Name()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file, line, name = "<unkown file>", -1, "<unknown name>"
|
||||||
|
return // panic?
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxStackDepth = 100 // This had better be enough...
|
||||||
|
|
||||||
|
var callStack []uintptr = make([]uintptr, maxStackDepth, maxStackDepth)
|
81
vendor/github.com/smartystreets/goconvey/convey/init.go
generated
vendored
Normal file
81
vendor/github.com/smartystreets/goconvey/convey/init.go
generated
vendored
Normal file
|
@ -0,0 +1,81 @@
|
||||||
|
package convey
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/jtolds/gls"
|
||||||
|
"github.com/smartystreets/assertions"
|
||||||
|
"github.com/smartystreets/goconvey/convey/reporting"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
assertions.GoConveyMode(true)
|
||||||
|
|
||||||
|
declareFlags()
|
||||||
|
|
||||||
|
ctxMgr = gls.NewContextManager()
|
||||||
|
}
|
||||||
|
|
||||||
|
func declareFlags() {
|
||||||
|
flag.BoolVar(&json, "convey-json", false, "When true, emits results in JSON blocks. Default: 'false'")
|
||||||
|
flag.BoolVar(&silent, "convey-silent", false, "When true, all output from GoConvey is suppressed.")
|
||||||
|
flag.BoolVar(&story, "convey-story", false, "When true, emits story output, otherwise emits dot output. When not provided, this flag mirros the value of the '-test.v' flag")
|
||||||
|
|
||||||
|
if noStoryFlagProvided() {
|
||||||
|
story = verboseEnabled
|
||||||
|
}
|
||||||
|
|
||||||
|
// FYI: flag.Parse() is called from the testing package.
|
||||||
|
}
|
||||||
|
|
||||||
|
func noStoryFlagProvided() bool {
|
||||||
|
return !story && !storyDisabled
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildReporter() reporting.Reporter {
|
||||||
|
selectReporter := os.Getenv("GOCONVEY_REPORTER")
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case testReporter != nil:
|
||||||
|
return testReporter
|
||||||
|
case json || selectReporter == "json":
|
||||||
|
return reporting.BuildJsonReporter()
|
||||||
|
case silent || selectReporter == "silent":
|
||||||
|
return reporting.BuildSilentReporter()
|
||||||
|
case selectReporter == "dot":
|
||||||
|
// Story is turned on when verbose is set, so we need to check for dot reporter first.
|
||||||
|
return reporting.BuildDotReporter()
|
||||||
|
case story || selectReporter == "story":
|
||||||
|
return reporting.BuildStoryReporter()
|
||||||
|
default:
|
||||||
|
return reporting.BuildDotReporter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ctxMgr *gls.ContextManager
|
||||||
|
|
||||||
|
// only set by internal tests
|
||||||
|
testReporter reporting.Reporter
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
json bool
|
||||||
|
silent bool
|
||||||
|
story bool
|
||||||
|
|
||||||
|
verboseEnabled = flagFound("-test.v=true")
|
||||||
|
storyDisabled = flagFound("-story=false")
|
||||||
|
)
|
||||||
|
|
||||||
|
// flagFound parses the command line args manually for flags defined in other
|
||||||
|
// packages. Like the '-v' flag from the "testing" package, for instance.
|
||||||
|
func flagFound(flagValue string) bool {
|
||||||
|
for _, arg := range os.Args {
|
||||||
|
if arg == flagValue {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
15
vendor/github.com/smartystreets/goconvey/convey/nilReporter.go
generated
vendored
Normal file
15
vendor/github.com/smartystreets/goconvey/convey/nilReporter.go
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
package convey
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/smartystreets/goconvey/convey/reporting"
|
||||||
|
)
|
||||||
|
|
||||||
|
type nilReporter struct{}
|
||||||
|
|
||||||
|
func (self *nilReporter) BeginStory(story *reporting.StoryReport) {}
|
||||||
|
func (self *nilReporter) Enter(scope *reporting.ScopeReport) {}
|
||||||
|
func (self *nilReporter) Report(report *reporting.AssertionResult) {}
|
||||||
|
func (self *nilReporter) Exit() {}
|
||||||
|
func (self *nilReporter) EndStory() {}
|
||||||
|
func (self *nilReporter) Write(p []byte) (int, error) { return len(p), nil }
|
||||||
|
func newNilReporter() *nilReporter { return &nilReporter{} }
|
16
vendor/github.com/smartystreets/goconvey/convey/reporting/console.go
generated
vendored
Normal file
16
vendor/github.com/smartystreets/goconvey/convey/reporting/console.go
generated
vendored
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type console struct{}
|
||||||
|
|
||||||
|
func (self *console) Write(p []byte) (n int, err error) {
|
||||||
|
return fmt.Print(string(p))
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConsole() io.Writer {
|
||||||
|
return new(console)
|
||||||
|
}
|
5
vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go
generated
vendored
Normal file
5
vendor/github.com/smartystreets/goconvey/convey/reporting/doc.go
generated
vendored
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
// Package reporting contains internal functionality related
|
||||||
|
// to console reporting and output. Although this package has
|
||||||
|
// exported names is not intended for public consumption. See the
|
||||||
|
// examples package for how to use this project.
|
||||||
|
package reporting
|
40
vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go
generated
vendored
Normal file
40
vendor/github.com/smartystreets/goconvey/convey/reporting/dot.go
generated
vendored
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type dot struct{ out *Printer }
|
||||||
|
|
||||||
|
func (self *dot) BeginStory(story *StoryReport) {}
|
||||||
|
|
||||||
|
func (self *dot) Enter(scope *ScopeReport) {}
|
||||||
|
|
||||||
|
func (self *dot) Report(report *AssertionResult) {
|
||||||
|
if report.Error != nil {
|
||||||
|
fmt.Print(redColor)
|
||||||
|
self.out.Insert(dotError)
|
||||||
|
} else if report.Failure != "" {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
self.out.Insert(dotFailure)
|
||||||
|
} else if report.Skipped {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
self.out.Insert(dotSkip)
|
||||||
|
} else {
|
||||||
|
fmt.Print(greenColor)
|
||||||
|
self.out.Insert(dotSuccess)
|
||||||
|
}
|
||||||
|
fmt.Print(resetColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *dot) Exit() {}
|
||||||
|
|
||||||
|
func (self *dot) EndStory() {}
|
||||||
|
|
||||||
|
func (self *dot) Write(content []byte) (written int, err error) {
|
||||||
|
return len(content), nil // no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDotReporter(out *Printer) *dot {
|
||||||
|
self := new(dot)
|
||||||
|
self.out = out
|
||||||
|
return self
|
||||||
|
}
|
33
vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go
generated
vendored
Normal file
33
vendor/github.com/smartystreets/goconvey/convey/reporting/gotest.go
generated
vendored
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
type gotestReporter struct{ test T }
|
||||||
|
|
||||||
|
func (self *gotestReporter) BeginStory(story *StoryReport) {
|
||||||
|
self.test = story.Test
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *gotestReporter) Enter(scope *ScopeReport) {}
|
||||||
|
|
||||||
|
func (self *gotestReporter) Report(r *AssertionResult) {
|
||||||
|
if !passed(r) {
|
||||||
|
self.test.Fail()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *gotestReporter) Exit() {}
|
||||||
|
|
||||||
|
func (self *gotestReporter) EndStory() {
|
||||||
|
self.test = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *gotestReporter) Write(content []byte) (written int, err error) {
|
||||||
|
return len(content), nil // no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewGoTestReporter() *gotestReporter {
|
||||||
|
return new(gotestReporter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func passed(r *AssertionResult) bool {
|
||||||
|
return r.Error == nil && r.Failure == ""
|
||||||
|
}
|
94
vendor/github.com/smartystreets/goconvey/convey/reporting/init.go
generated
vendored
Normal file
94
vendor/github.com/smartystreets/goconvey/convey/reporting/init.go
generated
vendored
Normal file
|
@ -0,0 +1,94 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if !isColorableTerminal() {
|
||||||
|
monochrome()
|
||||||
|
}
|
||||||
|
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
success, failure, error_ = dotSuccess, dotFailure, dotError
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BuildJsonReporter() Reporter {
|
||||||
|
out := NewPrinter(NewConsole())
|
||||||
|
return NewReporters(
|
||||||
|
NewGoTestReporter(),
|
||||||
|
NewJsonReporter(out))
|
||||||
|
}
|
||||||
|
func BuildDotReporter() Reporter {
|
||||||
|
out := NewPrinter(NewConsole())
|
||||||
|
return NewReporters(
|
||||||
|
NewGoTestReporter(),
|
||||||
|
NewDotReporter(out),
|
||||||
|
NewProblemReporter(out),
|
||||||
|
consoleStatistics)
|
||||||
|
}
|
||||||
|
func BuildStoryReporter() Reporter {
|
||||||
|
out := NewPrinter(NewConsole())
|
||||||
|
return NewReporters(
|
||||||
|
NewGoTestReporter(),
|
||||||
|
NewStoryReporter(out),
|
||||||
|
NewProblemReporter(out),
|
||||||
|
consoleStatistics)
|
||||||
|
}
|
||||||
|
func BuildSilentReporter() Reporter {
|
||||||
|
out := NewPrinter(NewConsole())
|
||||||
|
return NewReporters(
|
||||||
|
NewGoTestReporter(),
|
||||||
|
NewSilentProblemReporter(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
newline = "\n"
|
||||||
|
success = "✔"
|
||||||
|
failure = "✘"
|
||||||
|
error_ = "🔥"
|
||||||
|
skip = "⚠"
|
||||||
|
dotSuccess = "."
|
||||||
|
dotFailure = "x"
|
||||||
|
dotError = "E"
|
||||||
|
dotSkip = "S"
|
||||||
|
errorTemplate = "* %s \nLine %d: - %v \n%s\n"
|
||||||
|
failureTemplate = "* %s \nLine %d:\n%s\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
greenColor = "\033[32m"
|
||||||
|
yellowColor = "\033[33m"
|
||||||
|
redColor = "\033[31m"
|
||||||
|
resetColor = "\033[0m"
|
||||||
|
)
|
||||||
|
|
||||||
|
var consoleStatistics = NewStatisticsReporter(NewPrinter(NewConsole()))
|
||||||
|
|
||||||
|
func SuppressConsoleStatistics() { consoleStatistics.Suppress() }
|
||||||
|
func PrintConsoleStatistics() { consoleStatistics.PrintSummary() }
|
||||||
|
|
||||||
|
// QuiteMode disables all console output symbols. This is only meant to be used
|
||||||
|
// for tests that are internal to goconvey where the output is distracting or
|
||||||
|
// otherwise not needed in the test output.
|
||||||
|
func QuietMode() {
|
||||||
|
success, failure, error_, skip, dotSuccess, dotFailure, dotError, dotSkip = "", "", "", "", "", "", "", ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func monochrome() {
|
||||||
|
greenColor, yellowColor, redColor, resetColor = "", "", "", ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func isColorableTerminal() bool {
|
||||||
|
return strings.Contains(os.Getenv("TERM"), "color")
|
||||||
|
}
|
||||||
|
|
||||||
|
// This interface allows us to pass the *testing.T struct
|
||||||
|
// throughout the internals of this tool without ever
|
||||||
|
// having to import the "testing" package.
|
||||||
|
type T interface {
|
||||||
|
Fail()
|
||||||
|
}
|
88
vendor/github.com/smartystreets/goconvey/convey/reporting/json.go
generated
vendored
Normal file
88
vendor/github.com/smartystreets/goconvey/convey/reporting/json.go
generated
vendored
Normal file
|
@ -0,0 +1,88 @@
|
||||||
|
// TODO: under unit test
|
||||||
|
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JsonReporter struct {
|
||||||
|
out *Printer
|
||||||
|
currentKey []string
|
||||||
|
current *ScopeResult
|
||||||
|
index map[string]*ScopeResult
|
||||||
|
scopes []*ScopeResult
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *JsonReporter) depth() int { return len(self.currentKey) }
|
||||||
|
|
||||||
|
func (self *JsonReporter) BeginStory(story *StoryReport) {}
|
||||||
|
|
||||||
|
func (self *JsonReporter) Enter(scope *ScopeReport) {
|
||||||
|
self.currentKey = append(self.currentKey, scope.Title)
|
||||||
|
ID := strings.Join(self.currentKey, "|")
|
||||||
|
if _, found := self.index[ID]; !found {
|
||||||
|
next := newScopeResult(scope.Title, self.depth(), scope.File, scope.Line)
|
||||||
|
self.scopes = append(self.scopes, next)
|
||||||
|
self.index[ID] = next
|
||||||
|
}
|
||||||
|
self.current = self.index[ID]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *JsonReporter) Report(report *AssertionResult) {
|
||||||
|
self.current.Assertions = append(self.current.Assertions, report)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *JsonReporter) Exit() {
|
||||||
|
self.currentKey = self.currentKey[:len(self.currentKey)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *JsonReporter) EndStory() {
|
||||||
|
self.report()
|
||||||
|
self.reset()
|
||||||
|
}
|
||||||
|
func (self *JsonReporter) report() {
|
||||||
|
scopes := []string{}
|
||||||
|
for _, scope := range self.scopes {
|
||||||
|
serialized, err := json.Marshal(scope)
|
||||||
|
if err != nil {
|
||||||
|
self.out.Println(jsonMarshalFailure)
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
json.Indent(&buffer, serialized, "", " ")
|
||||||
|
scopes = append(scopes, buffer.String())
|
||||||
|
}
|
||||||
|
self.out.Print(fmt.Sprintf("%s\n%s,\n%s\n", OpenJson, strings.Join(scopes, ","), CloseJson))
|
||||||
|
}
|
||||||
|
func (self *JsonReporter) reset() {
|
||||||
|
self.scopes = []*ScopeResult{}
|
||||||
|
self.index = map[string]*ScopeResult{}
|
||||||
|
self.currentKey = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *JsonReporter) Write(content []byte) (written int, err error) {
|
||||||
|
self.current.Output += string(content)
|
||||||
|
return len(content), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewJsonReporter(out *Printer) *JsonReporter {
|
||||||
|
self := new(JsonReporter)
|
||||||
|
self.out = out
|
||||||
|
self.reset()
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
const OpenJson = ">->->OPEN-JSON->->->" // "⌦"
|
||||||
|
const CloseJson = "<-<-<-CLOSE-JSON<-<-<" // "⌫"
|
||||||
|
const jsonMarshalFailure = `
|
||||||
|
|
||||||
|
GOCONVEY_JSON_MARSHALL_FAILURE: There was an error when attempting to convert test results to JSON.
|
||||||
|
Please file a bug report and reference the code that caused this failure if possible.
|
||||||
|
|
||||||
|
Here's the panic:
|
||||||
|
|
||||||
|
`
|
57
vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go
generated
vendored
Normal file
57
vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go
generated
vendored
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Printer struct {
|
||||||
|
out io.Writer
|
||||||
|
prefix string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) Println(message string, values ...interface{}) {
|
||||||
|
formatted := self.format(message, values...) + newline
|
||||||
|
self.out.Write([]byte(formatted))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) Print(message string, values ...interface{}) {
|
||||||
|
formatted := self.format(message, values...)
|
||||||
|
self.out.Write([]byte(formatted))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) Insert(text string) {
|
||||||
|
self.out.Write([]byte(text))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) format(message string, values ...interface{}) string {
|
||||||
|
var formatted string
|
||||||
|
if len(values) == 0 {
|
||||||
|
formatted = self.prefix + message
|
||||||
|
} else {
|
||||||
|
formatted = self.prefix + fmt.Sprintf(message, values...)
|
||||||
|
}
|
||||||
|
indented := strings.Replace(formatted, newline, newline+self.prefix, -1)
|
||||||
|
return strings.TrimRight(indented, space)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) Indent() {
|
||||||
|
self.prefix += pad
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *Printer) Dedent() {
|
||||||
|
if len(self.prefix) >= padLength {
|
||||||
|
self.prefix = self.prefix[:len(self.prefix)-padLength]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPrinter(out io.Writer) *Printer {
|
||||||
|
self := new(Printer)
|
||||||
|
self.out = out
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
const space = " "
|
||||||
|
const pad = space + space
|
||||||
|
const padLength = len(pad)
|
80
vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go
generated
vendored
Normal file
80
vendor/github.com/smartystreets/goconvey/convey/reporting/problems.go
generated
vendored
Normal file
|
@ -0,0 +1,80 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
type problem struct {
|
||||||
|
silent bool
|
||||||
|
out *Printer
|
||||||
|
errors []*AssertionResult
|
||||||
|
failures []*AssertionResult
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *problem) BeginStory(story *StoryReport) {}
|
||||||
|
|
||||||
|
func (self *problem) Enter(scope *ScopeReport) {}
|
||||||
|
|
||||||
|
func (self *problem) Report(report *AssertionResult) {
|
||||||
|
if report.Error != nil {
|
||||||
|
self.errors = append(self.errors, report)
|
||||||
|
} else if report.Failure != "" {
|
||||||
|
self.failures = append(self.failures, report)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *problem) Exit() {}
|
||||||
|
|
||||||
|
func (self *problem) EndStory() {
|
||||||
|
self.show(self.showErrors, redColor)
|
||||||
|
self.show(self.showFailures, yellowColor)
|
||||||
|
self.prepareForNextStory()
|
||||||
|
}
|
||||||
|
func (self *problem) show(display func(), color string) {
|
||||||
|
if !self.silent {
|
||||||
|
fmt.Print(color)
|
||||||
|
}
|
||||||
|
display()
|
||||||
|
if !self.silent {
|
||||||
|
fmt.Print(resetColor)
|
||||||
|
}
|
||||||
|
self.out.Dedent()
|
||||||
|
}
|
||||||
|
func (self *problem) showErrors() {
|
||||||
|
for i, e := range self.errors {
|
||||||
|
if i == 0 {
|
||||||
|
self.out.Println("\nErrors:\n")
|
||||||
|
self.out.Indent()
|
||||||
|
}
|
||||||
|
self.out.Println(errorTemplate, e.File, e.Line, e.Error, e.StackTrace)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (self *problem) showFailures() {
|
||||||
|
for i, f := range self.failures {
|
||||||
|
if i == 0 {
|
||||||
|
self.out.Println("\nFailures:\n")
|
||||||
|
self.out.Indent()
|
||||||
|
}
|
||||||
|
self.out.Println(failureTemplate, f.File, f.Line, f.Failure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *problem) Write(content []byte) (written int, err error) {
|
||||||
|
return len(content), nil // no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProblemReporter(out *Printer) *problem {
|
||||||
|
self := new(problem)
|
||||||
|
self.out = out
|
||||||
|
self.prepareForNextStory()
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSilentProblemReporter(out *Printer) *problem {
|
||||||
|
self := NewProblemReporter(out)
|
||||||
|
self.silent = true
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *problem) prepareForNextStory() {
|
||||||
|
self.errors = []*AssertionResult{}
|
||||||
|
self.failures = []*AssertionResult{}
|
||||||
|
}
|
39
vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go
generated
vendored
Normal file
39
vendor/github.com/smartystreets/goconvey/convey/reporting/reporter.go
generated
vendored
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import "io"
|
||||||
|
|
||||||
|
type Reporter interface {
|
||||||
|
BeginStory(story *StoryReport)
|
||||||
|
Enter(scope *ScopeReport)
|
||||||
|
Report(r *AssertionResult)
|
||||||
|
Exit()
|
||||||
|
EndStory()
|
||||||
|
io.Writer
|
||||||
|
}
|
||||||
|
|
||||||
|
type reporters struct{ collection []Reporter }
|
||||||
|
|
||||||
|
func (self *reporters) BeginStory(s *StoryReport) { self.foreach(func(r Reporter) { r.BeginStory(s) }) }
|
||||||
|
func (self *reporters) Enter(s *ScopeReport) { self.foreach(func(r Reporter) { r.Enter(s) }) }
|
||||||
|
func (self *reporters) Report(a *AssertionResult) { self.foreach(func(r Reporter) { r.Report(a) }) }
|
||||||
|
func (self *reporters) Exit() { self.foreach(func(r Reporter) { r.Exit() }) }
|
||||||
|
func (self *reporters) EndStory() { self.foreach(func(r Reporter) { r.EndStory() }) }
|
||||||
|
|
||||||
|
func (self *reporters) Write(contents []byte) (written int, err error) {
|
||||||
|
self.foreach(func(r Reporter) {
|
||||||
|
written, err = r.Write(contents)
|
||||||
|
})
|
||||||
|
return written, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *reporters) foreach(action func(Reporter)) {
|
||||||
|
for _, r := range self.collection {
|
||||||
|
action(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewReporters(collection ...Reporter) *reporters {
|
||||||
|
self := new(reporters)
|
||||||
|
self.collection = collection
|
||||||
|
return self
|
||||||
|
}
|
2
vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey
generated
vendored
Normal file
2
vendor/github.com/smartystreets/goconvey/convey/reporting/reporting.goconvey
generated
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
#ignore
|
||||||
|
-timeout=1s
|
179
vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go
generated
vendored
Normal file
179
vendor/github.com/smartystreets/goconvey/convey/reporting/reports.go
generated
vendored
Normal file
|
@ -0,0 +1,179 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/smartystreets/goconvey/convey/gotest"
|
||||||
|
)
|
||||||
|
|
||||||
|
////////////////// ScopeReport ////////////////////
|
||||||
|
|
||||||
|
type ScopeReport struct {
|
||||||
|
Title string
|
||||||
|
File string
|
||||||
|
Line int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewScopeReport(title string) *ScopeReport {
|
||||||
|
file, line, _ := gotest.ResolveExternalCaller()
|
||||||
|
self := new(ScopeReport)
|
||||||
|
self.Title = title
|
||||||
|
self.File = file
|
||||||
|
self.Line = line
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////// ScopeResult ////////////////////
|
||||||
|
|
||||||
|
type ScopeResult struct {
|
||||||
|
Title string
|
||||||
|
File string
|
||||||
|
Line int
|
||||||
|
Depth int
|
||||||
|
Assertions []*AssertionResult
|
||||||
|
Output string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScopeResult(title string, depth int, file string, line int) *ScopeResult {
|
||||||
|
self := new(ScopeResult)
|
||||||
|
self.Title = title
|
||||||
|
self.Depth = depth
|
||||||
|
self.File = file
|
||||||
|
self.Line = line
|
||||||
|
self.Assertions = []*AssertionResult{}
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
/////////////////// StoryReport /////////////////////
|
||||||
|
|
||||||
|
type StoryReport struct {
|
||||||
|
Test T
|
||||||
|
Name string
|
||||||
|
File string
|
||||||
|
Line int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStoryReport(test T) *StoryReport {
|
||||||
|
file, line, name := gotest.ResolveExternalCaller()
|
||||||
|
name = removePackagePath(name)
|
||||||
|
self := new(StoryReport)
|
||||||
|
self.Test = test
|
||||||
|
self.Name = name
|
||||||
|
self.File = file
|
||||||
|
self.Line = line
|
||||||
|
return self
|
||||||
|
}
|
||||||
|
|
||||||
|
// name comes in looking like "github.com/smartystreets/goconvey/examples.TestName".
|
||||||
|
// We only want the stuff after the last '.', which is the name of the test function.
|
||||||
|
func removePackagePath(name string) string {
|
||||||
|
parts := strings.Split(name, ".")
|
||||||
|
return parts[len(parts)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
/////////////////// FailureView ////////////////////////
|
||||||
|
|
||||||
|
// This struct is also declared in github.com/smartystreets/assertions.
|
||||||
|
// 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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////AssertionResult //////////////////////
|
||||||
|
|
||||||
|
type AssertionResult struct {
|
||||||
|
File string
|
||||||
|
Line int
|
||||||
|
Expected string
|
||||||
|
Actual string
|
||||||
|
Failure string
|
||||||
|
Error interface{}
|
||||||
|
StackTrace string
|
||||||
|
Skipped bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFailureReport(failure string) *AssertionResult {
|
||||||
|
report := new(AssertionResult)
|
||||||
|
report.File, report.Line = caller()
|
||||||
|
report.StackTrace = stackTrace()
|
||||||
|
parseFailure(failure, report)
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
func parseFailure(failure string, report *AssertionResult) {
|
||||||
|
view := new(FailureView)
|
||||||
|
err := json.Unmarshal([]byte(failure), view)
|
||||||
|
if err == nil {
|
||||||
|
report.Failure = view.Message
|
||||||
|
report.Expected = view.Expected
|
||||||
|
report.Actual = view.Actual
|
||||||
|
} else {
|
||||||
|
report.Failure = failure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func NewErrorReport(err interface{}) *AssertionResult {
|
||||||
|
report := new(AssertionResult)
|
||||||
|
report.File, report.Line = caller()
|
||||||
|
report.StackTrace = fullStackTrace()
|
||||||
|
report.Error = fmt.Sprintf("%v", err)
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
func NewSuccessReport() *AssertionResult {
|
||||||
|
return new(AssertionResult)
|
||||||
|
}
|
||||||
|
func NewSkipReport() *AssertionResult {
|
||||||
|
report := new(AssertionResult)
|
||||||
|
report.File, report.Line = caller()
|
||||||
|
report.StackTrace = fullStackTrace()
|
||||||
|
report.Skipped = true
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
|
||||||
|
func caller() (file string, line int) {
|
||||||
|
file, line, _ = gotest.ResolveExternalCaller()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func stackTrace() string {
|
||||||
|
buffer := make([]byte, 1024*64)
|
||||||
|
n := runtime.Stack(buffer, false)
|
||||||
|
return removeInternalEntries(string(buffer[:n]))
|
||||||
|
}
|
||||||
|
func fullStackTrace() string {
|
||||||
|
buffer := make([]byte, 1024*64)
|
||||||
|
n := runtime.Stack(buffer, true)
|
||||||
|
return removeInternalEntries(string(buffer[:n]))
|
||||||
|
}
|
||||||
|
func removeInternalEntries(stack string) string {
|
||||||
|
lines := strings.Split(stack, newline)
|
||||||
|
filtered := []string{}
|
||||||
|
for _, line := range lines {
|
||||||
|
if !isExternal(line) {
|
||||||
|
filtered = append(filtered, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(filtered, newline)
|
||||||
|
}
|
||||||
|
func isExternal(line string) bool {
|
||||||
|
for _, p := range internalPackages {
|
||||||
|
if strings.Contains(line, p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: any new packages that host goconvey packages will need to be added here!
|
||||||
|
// An alternative is to scan the goconvey directory and then exclude stuff like
|
||||||
|
// the examples package but that's nasty too.
|
||||||
|
var internalPackages = []string{
|
||||||
|
"goconvey/assertions",
|
||||||
|
"goconvey/convey",
|
||||||
|
"goconvey/execution",
|
||||||
|
"goconvey/gotest",
|
||||||
|
"goconvey/reporting",
|
||||||
|
}
|
108
vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go
generated
vendored
Normal file
108
vendor/github.com/smartystreets/goconvey/convey/reporting/statistics.go
generated
vendored
Normal file
|
@ -0,0 +1,108 @@
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (self *statistics) BeginStory(story *StoryReport) {}
|
||||||
|
|
||||||
|
func (self *statistics) Enter(scope *ScopeReport) {}
|
||||||
|
|
||||||
|
func (self *statistics) Report(report *AssertionResult) {
|
||||||
|
self.Lock()
|
||||||
|
defer self.Unlock()
|
||||||
|
|
||||||
|
if !self.failing && report.Failure != "" {
|
||||||
|
self.failing = true
|
||||||
|
}
|
||||||
|
if !self.erroring && report.Error != nil {
|
||||||
|
self.erroring = true
|
||||||
|
}
|
||||||
|
if report.Skipped {
|
||||||
|
self.skipped += 1
|
||||||
|
} else {
|
||||||
|
self.total++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *statistics) Exit() {}
|
||||||
|
|
||||||
|
func (self *statistics) EndStory() {
|
||||||
|
self.Lock()
|
||||||
|
defer self.Unlock()
|
||||||
|
|
||||||
|
if !self.suppressed {
|
||||||
|
self.printSummaryLocked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *statistics) Suppress() {
|
||||||
|
self.Lock()
|
||||||
|
defer self.Unlock()
|
||||||
|
self.suppressed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *statistics) PrintSummary() {
|
||||||
|
self.Lock()
|
||||||
|
defer self.Unlock()
|
||||||
|
self.printSummaryLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *statistics) printSummaryLocked() {
|
||||||
|
self.reportAssertionsLocked()
|
||||||
|
self.reportSkippedSectionsLocked()
|
||||||
|
self.completeReportLocked()
|
||||||
|
}
|
||||||
|
func (self *statistics) reportAssertionsLocked() {
|
||||||
|
self.decideColorLocked()
|
||||||
|
self.out.Print("\n%d total %s", self.total, plural("assertion", self.total))
|
||||||
|
}
|
||||||
|
func (self *statistics) decideColorLocked() {
|
||||||
|
if self.failing && !self.erroring {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
} else if self.erroring {
|
||||||
|
fmt.Print(redColor)
|
||||||
|
} else {
|
||||||
|
fmt.Print(greenColor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (self *statistics) reportSkippedSectionsLocked() {
|
||||||
|
if self.skipped > 0 {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
self.out.Print(" (one or more sections skipped)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func (self *statistics) completeReportLocked() {
|
||||||
|
fmt.Print(resetColor)
|
||||||
|
self.out.Print("\n")
|
||||||
|
self.out.Print("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *statistics) Write(content []byte) (written int, err error) {
|
||||||
|
return len(content), nil // no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStatisticsReporter(out *Printer) *statistics {
|
||||||
|
self := statistics{}
|
||||||
|
self.out = out
|
||||||
|
return &self
|
||||||
|
}
|
||||||
|
|
||||||
|
type statistics struct {
|
||||||
|
sync.Mutex
|
||||||
|
|
||||||
|
out *Printer
|
||||||
|
total int
|
||||||
|
failing bool
|
||||||
|
erroring bool
|
||||||
|
skipped int
|
||||||
|
suppressed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func plural(word string, count int) string {
|
||||||
|
if count == 1 {
|
||||||
|
return word
|
||||||
|
}
|
||||||
|
return word + "s"
|
||||||
|
}
|
73
vendor/github.com/smartystreets/goconvey/convey/reporting/story.go
generated
vendored
Normal file
73
vendor/github.com/smartystreets/goconvey/convey/reporting/story.go
generated
vendored
Normal file
|
@ -0,0 +1,73 @@
|
||||||
|
// TODO: in order for this reporter to be completely honest
|
||||||
|
// we need to retrofit to be more like the json reporter such that:
|
||||||
|
// 1. it maintains ScopeResult collections, which count assertions
|
||||||
|
// 2. it reports only after EndStory(), so that all tick marks
|
||||||
|
// are placed near the appropriate title.
|
||||||
|
// 3. Under unit test
|
||||||
|
|
||||||
|
package reporting
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type story struct {
|
||||||
|
out *Printer
|
||||||
|
titlesById map[string]string
|
||||||
|
currentKey []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *story) BeginStory(story *StoryReport) {}
|
||||||
|
|
||||||
|
func (self *story) Enter(scope *ScopeReport) {
|
||||||
|
self.out.Indent()
|
||||||
|
|
||||||
|
self.currentKey = append(self.currentKey, scope.Title)
|
||||||
|
ID := strings.Join(self.currentKey, "|")
|
||||||
|
|
||||||
|
if _, found := self.titlesById[ID]; !found {
|
||||||
|
self.out.Println("")
|
||||||
|
self.out.Print(scope.Title)
|
||||||
|
self.out.Insert(" ")
|
||||||
|
self.titlesById[ID] = scope.Title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *story) Report(report *AssertionResult) {
|
||||||
|
if report.Error != nil {
|
||||||
|
fmt.Print(redColor)
|
||||||
|
self.out.Insert(error_)
|
||||||
|
} else if report.Failure != "" {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
self.out.Insert(failure)
|
||||||
|
} else if report.Skipped {
|
||||||
|
fmt.Print(yellowColor)
|
||||||
|
self.out.Insert(skip)
|
||||||
|
} else {
|
||||||
|
fmt.Print(greenColor)
|
||||||
|
self.out.Insert(success)
|
||||||
|
}
|
||||||
|
fmt.Print(resetColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *story) Exit() {
|
||||||
|
self.out.Dedent()
|
||||||
|
self.currentKey = self.currentKey[:len(self.currentKey)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *story) EndStory() {
|
||||||
|
self.titlesById = make(map[string]string)
|
||||||
|
self.out.Println("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (self *story) Write(content []byte) (written int, err error) {
|
||||||
|
return len(content), nil // no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStoryReporter(out *Printer) *story {
|
||||||
|
self := new(story)
|
||||||
|
self.out = out
|
||||||
|
self.titlesById = make(map[string]string)
|
||||||
|
return self
|
||||||
|
}
|
25
vendor/github.com/spf13/pflag/README.md
generated
vendored
25
vendor/github.com/spf13/pflag/README.md
generated
vendored
|
@ -1,6 +1,4 @@
|
||||||
[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag)
|
[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag)
|
||||||
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag)
|
|
||||||
[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag)
|
|
||||||
|
|
||||||
## Description
|
## Description
|
||||||
|
|
||||||
|
@ -108,9 +106,9 @@ that give one-letter shorthands for flags. You can use these by appending
|
||||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||||
var flagvar bool
|
var flagvar bool
|
||||||
func init() {
|
func init() {
|
||||||
flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
|
flag.BoolVarP("boolname", "b", true, "help message")
|
||||||
}
|
}
|
||||||
flag.VarP(&flagVal, "varname", "v", "help message")
|
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||||
```
|
```
|
||||||
|
|
||||||
Shorthand letters can be used with single dashes on the command line.
|
Shorthand letters can be used with single dashes on the command line.
|
||||||
|
@ -246,25 +244,6 @@ It is possible to mark a flag as hidden, meaning it will still function as norma
|
||||||
flags.MarkHidden("secretFlag")
|
flags.MarkHidden("secretFlag")
|
||||||
```
|
```
|
||||||
|
|
||||||
## Supporting Go flags when using pflag
|
|
||||||
In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
|
|
||||||
to support flags defined by third-party dependencies (e.g. `golang/glog`).
|
|
||||||
|
|
||||||
**Example**: You want to add the Go flags to the `CommandLine` flagset
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
goflag "flag"
|
|
||||||
flag "github.com/spf13/pflag"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
|
|
||||||
flag.Parse()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## More info
|
## More info
|
||||||
|
|
||||||
You can see the full reference documentation of the pflag package
|
You can see the full reference documentation of the pflag package
|
||||||
|
|
7
vendor/github.com/spf13/pflag/bool.go
generated
vendored
7
vendor/github.com/spf13/pflag/bool.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// optional interface to indicate boolean flags that can be
|
// optional interface to indicate boolean flags that can be
|
||||||
// supplied without "=value" text
|
// supplied without "=value" text
|
||||||
|
@ -27,7 +30,7 @@ func (b *boolValue) Type() string {
|
||||||
return "bool"
|
return "bool"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
|
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
|
||||||
|
|
||||||
func (b *boolValue) IsBoolFlag() bool { return true }
|
func (b *boolValue) IsBoolFlag() bool { return true }
|
||||||
|
|
||||||
|
|
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
|
@ -1,147 +0,0 @@
|
||||||
package pflag
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// -- boolSlice Value
|
|
||||||
type boolSliceValue struct {
|
|
||||||
value *[]bool
|
|
||||||
changed bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
|
|
||||||
bsv := new(boolSliceValue)
|
|
||||||
bsv.value = p
|
|
||||||
*bsv.value = val
|
|
||||||
return bsv
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
|
|
||||||
// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
|
|
||||||
func (s *boolSliceValue) Set(val string) error {
|
|
||||||
|
|
||||||
// remove all quote characters
|
|
||||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
|
||||||
|
|
||||||
// read flag arguments with CSV parser
|
|
||||||
boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
|
||||||
if err != nil && err != io.EOF {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse boolean values into slice
|
|
||||||
out := make([]bool, 0, len(boolStrSlice))
|
|
||||||
for _, boolStr := range boolStrSlice {
|
|
||||||
b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
out = append(out, b)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !s.changed {
|
|
||||||
*s.value = out
|
|
||||||
} else {
|
|
||||||
*s.value = append(*s.value, out...)
|
|
||||||
}
|
|
||||||
|
|
||||||
s.changed = true
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Type returns a string that uniquely represents this flag's type.
|
|
||||||
func (s *boolSliceValue) Type() string {
|
|
||||||
return "boolSlice"
|
|
||||||
}
|
|
||||||
|
|
||||||
// String defines a "native" format for this boolean slice flag value.
|
|
||||||
func (s *boolSliceValue) String() string {
|
|
||||||
|
|
||||||
boolStrSlice := make([]string, len(*s.value))
|
|
||||||
for i, b := range *s.value {
|
|
||||||
boolStrSlice[i] = strconv.FormatBool(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, _ := writeAsCSV(boolStrSlice)
|
|
||||||
|
|
||||||
return "[" + out + "]"
|
|
||||||
}
|
|
||||||
|
|
||||||
func boolSliceConv(val string) (interface{}, error) {
|
|
||||||
val = strings.Trim(val, "[]")
|
|
||||||
// Empty string would cause a slice with one (empty) entry
|
|
||||||
if len(val) == 0 {
|
|
||||||
return []bool{}, nil
|
|
||||||
}
|
|
||||||
ss := strings.Split(val, ",")
|
|
||||||
out := make([]bool, len(ss))
|
|
||||||
for i, t := range ss {
|
|
||||||
var err error
|
|
||||||
out[i], err = strconv.ParseBool(t)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetBoolSlice returns the []bool value of a flag with the given name.
|
|
||||||
func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
|
|
||||||
val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
|
|
||||||
if err != nil {
|
|
||||||
return []bool{}, err
|
|
||||||
}
|
|
||||||
return val.([]bool), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
|
||||||
func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
|
||||||
f.VarP(newBoolSliceValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
|
||||||
f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
|
||||||
func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
|
||||||
CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
|
||||||
CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
|
||||||
func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
|
|
||||||
p := []bool{}
|
|
||||||
f.BoolSliceVarP(&p, name, "", value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
|
||||||
p := []bool{}
|
|
||||||
f.BoolSliceVarP(&p, name, shorthand, value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
|
||||||
func BoolSlice(name string, value []bool, usage string) *[]bool {
|
|
||||||
return CommandLine.BoolSliceP(name, "", value, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
|
||||||
return CommandLine.BoolSliceP(name, shorthand, value, usage)
|
|
||||||
}
|
|
7
vendor/github.com/spf13/pflag/count.go
generated
vendored
7
vendor/github.com/spf13/pflag/count.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- count Value
|
// -- count Value
|
||||||
type countValue int
|
type countValue int
|
||||||
|
@ -25,7 +28,7 @@ func (i *countValue) Type() string {
|
||||||
return "count"
|
return "count"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
|
func (i *countValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func countConv(sval string) (interface{}, error) {
|
func countConv(sval string) (interface{}, error) {
|
||||||
i, err := strconv.Atoi(sval)
|
i, err := strconv.Atoi(sval)
|
||||||
|
|
197
vendor/github.com/spf13/pflag/flag.go
generated
vendored
197
vendor/github.com/spf13/pflag/flag.go
generated
vendored
|
@ -416,28 +416,13 @@ func Set(name, value string) error {
|
||||||
// otherwise, the default values of all defined flags in the set.
|
// otherwise, the default values of all defined flags in the set.
|
||||||
func (f *FlagSet) PrintDefaults() {
|
func (f *FlagSet) PrintDefaults() {
|
||||||
usages := f.FlagUsages()
|
usages := f.FlagUsages()
|
||||||
fmt.Fprint(f.out(), usages)
|
fmt.Fprintf(f.out(), "%s", usages)
|
||||||
}
|
}
|
||||||
|
|
||||||
// defaultIsZeroValue returns true if the default value for this flag represents
|
// isZeroValue guesses whether the string represents the zero
|
||||||
// a zero value.
|
// value for a flag. It is not accurate but in practice works OK.
|
||||||
func (f *Flag) defaultIsZeroValue() bool {
|
func isZeroValue(value string) bool {
|
||||||
switch f.Value.(type) {
|
switch value {
|
||||||
case boolFlag:
|
|
||||||
return f.DefValue == "false"
|
|
||||||
case *durationValue:
|
|
||||||
// Beginning in Go 1.7, duration zero values are "0s"
|
|
||||||
return f.DefValue == "0" || f.DefValue == "0s"
|
|
||||||
case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
|
|
||||||
return f.DefValue == "0"
|
|
||||||
case *stringValue:
|
|
||||||
return f.DefValue == ""
|
|
||||||
case *ipValue, *ipMaskValue, *ipNetValue:
|
|
||||||
return f.DefValue == "<nil>"
|
|
||||||
case *intSliceValue, *stringSliceValue, *stringArrayValue:
|
|
||||||
return f.DefValue == "[]"
|
|
||||||
default:
|
|
||||||
switch f.Value.String() {
|
|
||||||
case "false":
|
case "false":
|
||||||
return true
|
return true
|
||||||
case "<nil>":
|
case "<nil>":
|
||||||
|
@ -448,7 +433,6 @@ func (f *Flag) defaultIsZeroValue() bool {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// UnquoteUsage extracts a back-quoted name from the usage
|
// UnquoteUsage extracts a back-quoted name from the usage
|
||||||
|
@ -471,92 +455,28 @@ func UnquoteUsage(flag *Flag) (name string, usage string) {
|
||||||
break // Only one back quote; use type name.
|
break // Only one back quote; use type name.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// No explicit name, so use type if we can find one.
|
||||||
name = flag.Value.Type()
|
name = "value"
|
||||||
switch name {
|
switch flag.Value.(type) {
|
||||||
case "bool":
|
case boolFlag:
|
||||||
name = ""
|
name = ""
|
||||||
case "float64":
|
case *durationValue:
|
||||||
|
name = "duration"
|
||||||
|
case *float64Value:
|
||||||
name = "float"
|
name = "float"
|
||||||
case "int64":
|
case *intValue, *int64Value:
|
||||||
name = "int"
|
name = "int"
|
||||||
case "uint64":
|
case *stringValue:
|
||||||
|
name = "string"
|
||||||
|
case *uintValue, *uint64Value:
|
||||||
name = "uint"
|
name = "uint"
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Splits the string `s` on whitespace into an initial substring up to
|
// FlagUsages Returns a string containing the usage information for all flags in
|
||||||
// `i` runes in length and the remainder. Will go `slop` over `i` if
|
// the FlagSet
|
||||||
// that encompasses the entire string (which allows the caller to
|
func (f *FlagSet) FlagUsages() string {
|
||||||
// avoid short orphan words on the final line).
|
|
||||||
func wrapN(i, slop int, s string) (string, string) {
|
|
||||||
if i+slop > len(s) {
|
|
||||||
return s, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
w := strings.LastIndexAny(s[:i], " \t")
|
|
||||||
if w <= 0 {
|
|
||||||
return s, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
return s[:w], s[w+1:]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wraps the string `s` to a maximum width `w` with leading indent
|
|
||||||
// `i`. The first line is not indented (this is assumed to be done by
|
|
||||||
// caller). Pass `w` == 0 to do no wrapping
|
|
||||||
func wrap(i, w int, s string) string {
|
|
||||||
if w == 0 {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// space between indent i and end of line width w into which
|
|
||||||
// we should wrap the text.
|
|
||||||
wrap := w - i
|
|
||||||
|
|
||||||
var r, l string
|
|
||||||
|
|
||||||
// Not enough space for sensible wrapping. Wrap as a block on
|
|
||||||
// the next line instead.
|
|
||||||
if wrap < 24 {
|
|
||||||
i = 16
|
|
||||||
wrap = w - i
|
|
||||||
r += "\n" + strings.Repeat(" ", i)
|
|
||||||
}
|
|
||||||
// If still not enough space then don't even try to wrap.
|
|
||||||
if wrap < 24 {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to avoid short orphan words on the final line, by
|
|
||||||
// allowing wrapN to go a bit over if that would fit in the
|
|
||||||
// remainder of the line.
|
|
||||||
slop := 5
|
|
||||||
wrap = wrap - slop
|
|
||||||
|
|
||||||
// Handle first line, which is indented by the caller (or the
|
|
||||||
// special case above)
|
|
||||||
l, s = wrapN(wrap, slop, s)
|
|
||||||
r = r + l
|
|
||||||
|
|
||||||
// Now wrap the rest
|
|
||||||
for s != "" {
|
|
||||||
var t string
|
|
||||||
|
|
||||||
t, s = wrapN(wrap, slop, s)
|
|
||||||
r = r + "\n" + strings.Repeat(" ", i) + t
|
|
||||||
}
|
|
||||||
|
|
||||||
return r
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// FlagUsagesWrapped returns a string containing the usage information
|
|
||||||
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
|
|
||||||
// wrapping)
|
|
||||||
func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
|
||||||
x := new(bytes.Buffer)
|
x := new(bytes.Buffer)
|
||||||
|
|
||||||
lines := make([]string, 0, len(f.formal))
|
lines := make([]string, 0, len(f.formal))
|
||||||
|
@ -581,7 +501,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||||
if len(flag.NoOptDefVal) > 0 {
|
if len(flag.NoOptDefVal) > 0 {
|
||||||
switch flag.Value.Type() {
|
switch flag.Value.Type() {
|
||||||
case "string":
|
case "string":
|
||||||
line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
|
line += fmt.Sprintf("[=%q]", flag.NoOptDefVal)
|
||||||
case "bool":
|
case "bool":
|
||||||
if flag.NoOptDefVal != "true" {
|
if flag.NoOptDefVal != "true" {
|
||||||
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
|
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
|
||||||
|
@ -599,9 +519,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
line += usage
|
line += usage
|
||||||
if !flag.defaultIsZeroValue() {
|
if !isZeroValue(flag.DefValue) {
|
||||||
if flag.Value.Type() == "string" {
|
if flag.Value.Type() == "string" {
|
||||||
line += fmt.Sprintf(" (default \"%s\")", flag.DefValue)
|
line += fmt.Sprintf(" (default %q)", flag.DefValue)
|
||||||
} else {
|
} else {
|
||||||
line += fmt.Sprintf(" (default %s)", flag.DefValue)
|
line += fmt.Sprintf(" (default %s)", flag.DefValue)
|
||||||
}
|
}
|
||||||
|
@ -613,19 +533,12 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||||
for _, line := range lines {
|
for _, line := range lines {
|
||||||
sidx := strings.Index(line, "\x00")
|
sidx := strings.Index(line, "\x00")
|
||||||
spacing := strings.Repeat(" ", maxlen-sidx)
|
spacing := strings.Repeat(" ", maxlen-sidx)
|
||||||
// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
|
fmt.Fprintln(x, line[:sidx], spacing, line[sidx+1:])
|
||||||
fmt.Fprintln(x, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return x.String()
|
return x.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// FlagUsages returns a string containing the usage information for all flags in
|
|
||||||
// the FlagSet
|
|
||||||
func (f *FlagSet) FlagUsages() string {
|
|
||||||
return f.FlagUsagesWrapped(0)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||||
func PrintDefaults() {
|
func PrintDefaults() {
|
||||||
CommandLine.PrintDefaults()
|
CommandLine.PrintDefaults()
|
||||||
|
@ -709,7 +622,7 @@ func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
|
||||||
|
|
||||||
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
|
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||||
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
|
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
|
||||||
f.VarPF(value, name, shorthand, usage)
|
_ = f.VarPF(value, name, shorthand, usage)
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddFlag will add the flag to the FlagSet
|
// AddFlag will add the flag to the FlagSet
|
||||||
|
@ -826,7 +739,7 @@ func containsShorthand(arg, shorthand string) bool {
|
||||||
return strings.Contains(arg, shorthand)
|
return strings.Contains(arg, shorthand)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
|
||||||
a = args
|
a = args
|
||||||
name := s[2:]
|
name := s[2:]
|
||||||
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
||||||
|
@ -860,11 +773,11 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
|
||||||
err = f.failf("flag needs an argument: %s", s)
|
err = f.failf("flag needs an argument: %s", s)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = fn(flag, value, s)
|
err = f.setFlag(flag, value, s)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
|
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
|
||||||
if strings.HasPrefix(shorthands, "test.") {
|
if strings.HasPrefix(shorthands, "test.") {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -899,16 +812,16 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse
|
||||||
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = fn(flag, value, shorthands)
|
err = f.setFlag(flag, value, shorthands)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
|
||||||
a = args
|
a = args
|
||||||
shorthands := s[1:]
|
shorthands := s[1:]
|
||||||
|
|
||||||
for len(shorthands) > 0 {
|
for len(shorthands) > 0 {
|
||||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
|
shorthands, a, err = f.parseSingleShortArg(shorthands, args)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
@ -917,7 +830,7 @@ func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []stri
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
func (f *FlagSet) parseArgs(args []string) (err error) {
|
||||||
for len(args) > 0 {
|
for len(args) > 0 {
|
||||||
s := args[0]
|
s := args[0]
|
||||||
args = args[1:]
|
args = args[1:]
|
||||||
|
@ -937,9 +850,9 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||||
f.args = append(f.args, args...)
|
f.args = append(f.args, args...)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
args, err = f.parseLongArg(s, args, fn)
|
args, err = f.parseLongArg(s, args)
|
||||||
} else {
|
} else {
|
||||||
args, err = f.parseShortArg(s, args, fn)
|
args, err = f.parseShortArg(s, args)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
|
@ -955,41 +868,7 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||||
func (f *FlagSet) Parse(arguments []string) error {
|
func (f *FlagSet) Parse(arguments []string) error {
|
||||||
f.parsed = true
|
f.parsed = true
|
||||||
f.args = make([]string, 0, len(arguments))
|
f.args = make([]string, 0, len(arguments))
|
||||||
|
err := f.parseArgs(arguments)
|
||||||
assign := func(flag *Flag, value, origArg string) error {
|
|
||||||
return f.setFlag(flag, value, origArg)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := f.parseArgs(arguments, assign)
|
|
||||||
if err != nil {
|
|
||||||
switch f.errorHandling {
|
|
||||||
case ContinueOnError:
|
|
||||||
return err
|
|
||||||
case ExitOnError:
|
|
||||||
os.Exit(2)
|
|
||||||
case PanicOnError:
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type parseFunc func(flag *Flag, value, origArg string) error
|
|
||||||
|
|
||||||
// ParseAll parses flag definitions from the argument list, which should not
|
|
||||||
// include the command name. The arguments for fn are flag and value. Must be
|
|
||||||
// called after all flags in the FlagSet are defined and before flags are
|
|
||||||
// accessed by the program. The return value will be ErrHelp if -help was set
|
|
||||||
// but not defined.
|
|
||||||
func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
|
|
||||||
f.parsed = true
|
|
||||||
f.args = make([]string, 0, len(arguments))
|
|
||||||
|
|
||||||
assign := func(flag *Flag, value, origArg string) error {
|
|
||||||
return fn(flag, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := f.parseArgs(arguments, assign)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch f.errorHandling {
|
switch f.errorHandling {
|
||||||
case ContinueOnError:
|
case ContinueOnError:
|
||||||
|
@ -1015,14 +894,6 @@ func Parse() {
|
||||||
CommandLine.Parse(os.Args[1:])
|
CommandLine.Parse(os.Args[1:])
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
|
|
||||||
// The arguments for fn are flag and value. Must be called after all flags are
|
|
||||||
// defined and before flags are accessed by the program.
|
|
||||||
func ParseAll(fn func(flag *Flag, value string) error) {
|
|
||||||
// Ignore errors; CommandLine is set for ExitOnError.
|
|
||||||
CommandLine.ParseAll(os.Args[1:], fn)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetInterspersed sets whether to support interspersed option/non-option arguments.
|
// SetInterspersed sets whether to support interspersed option/non-option arguments.
|
||||||
func SetInterspersed(interspersed bool) {
|
func SetInterspersed(interspersed bool) {
|
||||||
CommandLine.SetInterspersed(interspersed)
|
CommandLine.SetInterspersed(interspersed)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/float32.go
generated
vendored
7
vendor/github.com/spf13/pflag/float32.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- float32 Value
|
// -- float32 Value
|
||||||
type float32Value float32
|
type float32Value float32
|
||||||
|
@ -20,7 +23,7 @@ func (f *float32Value) Type() string {
|
||||||
return "float32"
|
return "float32"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
|
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||||
|
|
||||||
func float32Conv(sval string) (interface{}, error) {
|
func float32Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseFloat(sval, 32)
|
v, err := strconv.ParseFloat(sval, 32)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/float64.go
generated
vendored
7
vendor/github.com/spf13/pflag/float64.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- float64 Value
|
// -- float64 Value
|
||||||
type float64Value float64
|
type float64Value float64
|
||||||
|
@ -20,7 +23,7 @@ func (f *float64Value) Type() string {
|
||||||
return "float64"
|
return "float64"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
|
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||||
|
|
||||||
func float64Conv(sval string) (interface{}, error) {
|
func float64Conv(sval string) (interface{}, error) {
|
||||||
return strconv.ParseFloat(sval, 64)
|
return strconv.ParseFloat(sval, 64)
|
||||||
|
|
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
|
@ -6,10 +6,13 @@ package pflag
|
||||||
|
|
||||||
import (
|
import (
|
||||||
goflag "flag"
|
goflag "flag"
|
||||||
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ = fmt.Print
|
||||||
|
|
||||||
// flagValueWrapper implements pflag.Value around a flag.Value. The main
|
// flagValueWrapper implements pflag.Value around a flag.Value. The main
|
||||||
// difference here is the addition of the Type method that returns a string
|
// difference here is the addition of the Type method that returns a string
|
||||||
// name of the type. As this is generally unknown, we approximate that with
|
// name of the type. As this is generally unknown, we approximate that with
|
||||||
|
|
7
vendor/github.com/spf13/pflag/int.go
generated
vendored
7
vendor/github.com/spf13/pflag/int.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- int Value
|
// -- int Value
|
||||||
type intValue int
|
type intValue int
|
||||||
|
@ -20,7 +23,7 @@ func (i *intValue) Type() string {
|
||||||
return "int"
|
return "int"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
|
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func intConv(sval string) (interface{}, error) {
|
func intConv(sval string) (interface{}, error) {
|
||||||
return strconv.Atoi(sval)
|
return strconv.Atoi(sval)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/int32.go
generated
vendored
7
vendor/github.com/spf13/pflag/int32.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- int32 Value
|
// -- int32 Value
|
||||||
type int32Value int32
|
type int32Value int32
|
||||||
|
@ -20,7 +23,7 @@ func (i *int32Value) Type() string {
|
||||||
return "int32"
|
return "int32"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func int32Conv(sval string) (interface{}, error) {
|
func int32Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseInt(sval, 0, 32)
|
v, err := strconv.ParseInt(sval, 0, 32)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/int64.go
generated
vendored
7
vendor/github.com/spf13/pflag/int64.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- int64 Value
|
// -- int64 Value
|
||||||
type int64Value int64
|
type int64Value int64
|
||||||
|
@ -20,7 +23,7 @@ func (i *int64Value) Type() string {
|
||||||
return "int64"
|
return "int64"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func int64Conv(sval string) (interface{}, error) {
|
func int64Conv(sval string) (interface{}, error) {
|
||||||
return strconv.ParseInt(sval, 0, 64)
|
return strconv.ParseInt(sval, 0, 64)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/int8.go
generated
vendored
7
vendor/github.com/spf13/pflag/int8.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- int8 Value
|
// -- int8 Value
|
||||||
type int8Value int8
|
type int8Value int8
|
||||||
|
@ -20,7 +23,7 @@ func (i *int8Value) Type() string {
|
||||||
return "int8"
|
return "int8"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func int8Conv(sval string) (interface{}, error) {
|
func int8Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseInt(sval, 0, 8)
|
v, err := strconv.ParseInt(sval, 0, 8)
|
||||||
|
|
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
|
@ -6,6 +6,8 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ = strings.TrimSpace
|
||||||
|
|
||||||
// -- net.IP value
|
// -- net.IP value
|
||||||
type ipValue net.IP
|
type ipValue net.IP
|
||||||
|
|
||||||
|
|
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
|
@ -1,148 +0,0 @@
|
||||||
package pflag
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// -- ipSlice Value
|
|
||||||
type ipSliceValue struct {
|
|
||||||
value *[]net.IP
|
|
||||||
changed bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
|
|
||||||
ipsv := new(ipSliceValue)
|
|
||||||
ipsv.value = p
|
|
||||||
*ipsv.value = val
|
|
||||||
return ipsv
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
|
|
||||||
// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
|
|
||||||
func (s *ipSliceValue) Set(val string) error {
|
|
||||||
|
|
||||||
// remove all quote characters
|
|
||||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
|
||||||
|
|
||||||
// read flag arguments with CSV parser
|
|
||||||
ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
|
||||||
if err != nil && err != io.EOF {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse ip values into slice
|
|
||||||
out := make([]net.IP, 0, len(ipStrSlice))
|
|
||||||
for _, ipStr := range ipStrSlice {
|
|
||||||
ip := net.ParseIP(strings.TrimSpace(ipStr))
|
|
||||||
if ip == nil {
|
|
||||||
return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
|
|
||||||
}
|
|
||||||
out = append(out, ip)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !s.changed {
|
|
||||||
*s.value = out
|
|
||||||
} else {
|
|
||||||
*s.value = append(*s.value, out...)
|
|
||||||
}
|
|
||||||
|
|
||||||
s.changed = true
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Type returns a string that uniquely represents this flag's type.
|
|
||||||
func (s *ipSliceValue) Type() string {
|
|
||||||
return "ipSlice"
|
|
||||||
}
|
|
||||||
|
|
||||||
// String defines a "native" format for this net.IP slice flag value.
|
|
||||||
func (s *ipSliceValue) String() string {
|
|
||||||
|
|
||||||
ipStrSlice := make([]string, len(*s.value))
|
|
||||||
for i, ip := range *s.value {
|
|
||||||
ipStrSlice[i] = ip.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
out, _ := writeAsCSV(ipStrSlice)
|
|
||||||
|
|
||||||
return "[" + out + "]"
|
|
||||||
}
|
|
||||||
|
|
||||||
func ipSliceConv(val string) (interface{}, error) {
|
|
||||||
val = strings.Trim(val, "[]")
|
|
||||||
// Emtpy string would cause a slice with one (empty) entry
|
|
||||||
if len(val) == 0 {
|
|
||||||
return []net.IP{}, nil
|
|
||||||
}
|
|
||||||
ss := strings.Split(val, ",")
|
|
||||||
out := make([]net.IP, len(ss))
|
|
||||||
for i, sval := range ss {
|
|
||||||
ip := net.ParseIP(strings.TrimSpace(sval))
|
|
||||||
if ip == nil {
|
|
||||||
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
|
|
||||||
}
|
|
||||||
out[i] = ip
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetIPSlice returns the []net.IP value of a flag with the given name
|
|
||||||
func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
|
|
||||||
val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
|
|
||||||
if err != nil {
|
|
||||||
return []net.IP{}, err
|
|
||||||
}
|
|
||||||
return val.([]net.IP), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
|
||||||
func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
|
||||||
f.VarP(newIPSliceValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
|
||||||
f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
|
||||||
func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
|
||||||
CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
|
||||||
CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []net.IP variable that stores the value of that flag.
|
|
||||||
func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
|
||||||
p := []net.IP{}
|
|
||||||
f.IPSliceVarP(&p, name, "", value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
|
||||||
p := []net.IP{}
|
|
||||||
f.IPSliceVarP(&p, name, shorthand, value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []net.IP variable that stores the value of the flag.
|
|
||||||
func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
|
||||||
return CommandLine.IPSliceP(name, "", value, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
|
||||||
return CommandLine.IPSliceP(name, shorthand, value, usage)
|
|
||||||
}
|
|
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
|
@ -27,6 +27,8 @@ func (*ipNetValue) Type() string {
|
||||||
return "ipNet"
|
return "ipNet"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ = strings.TrimSpace
|
||||||
|
|
||||||
func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
|
func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
|
||||||
*p = val
|
*p = val
|
||||||
return (*ipNetValue)(p)
|
return (*ipNetValue)(p)
|
||||||
|
|
4
vendor/github.com/spf13/pflag/string.go
generated
vendored
4
vendor/github.com/spf13/pflag/string.go
generated
vendored
|
@ -1,5 +1,7 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
// -- string Value
|
// -- string Value
|
||||||
type stringValue string
|
type stringValue string
|
||||||
|
|
||||||
|
@ -16,7 +18,7 @@ func (s *stringValue) Type() string {
|
||||||
return "string"
|
return "string"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *stringValue) String() string { return string(*s) }
|
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
|
||||||
|
|
||||||
func stringConv(sval string) (interface{}, error) {
|
func stringConv(sval string) (interface{}, error) {
|
||||||
return sval, nil
|
return sval, nil
|
||||||
|
|
103
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
103
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
|
@ -1,103 +0,0 @@
|
||||||
package pflag
|
|
||||||
|
|
||||||
// -- stringArray Value
|
|
||||||
type stringArrayValue struct {
|
|
||||||
value *[]string
|
|
||||||
changed bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
|
|
||||||
ssv := new(stringArrayValue)
|
|
||||||
ssv.value = p
|
|
||||||
*ssv.value = val
|
|
||||||
return ssv
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *stringArrayValue) Set(val string) error {
|
|
||||||
if !s.changed {
|
|
||||||
*s.value = []string{val}
|
|
||||||
s.changed = true
|
|
||||||
} else {
|
|
||||||
*s.value = append(*s.value, val)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *stringArrayValue) Type() string {
|
|
||||||
return "stringArray"
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *stringArrayValue) String() string {
|
|
||||||
str, _ := writeAsCSV(*s.value)
|
|
||||||
return "[" + str + "]"
|
|
||||||
}
|
|
||||||
|
|
||||||
func stringArrayConv(sval string) (interface{}, error) {
|
|
||||||
sval = sval[1 : len(sval)-1]
|
|
||||||
// An empty string would cause a array with one (empty) string
|
|
||||||
if len(sval) == 0 {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
return readAsCSV(sval)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetStringArray return the []string value of a flag with the given name
|
|
||||||
func (f *FlagSet) GetStringArray(name string) ([]string, error) {
|
|
||||||
val, err := f.getFlagType(name, "stringArray", stringArrayConv)
|
|
||||||
if err != nil {
|
|
||||||
return []string{}, err
|
|
||||||
}
|
|
||||||
return val.([]string), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayVar defines a string flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []string variable in which to store the values of the multiple flags.
|
|
||||||
// The value of each argument will not try to be separated by comma
|
|
||||||
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
|
|
||||||
f.VarP(newStringArrayValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
|
|
||||||
f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayVar defines a string flag with specified name, default value, and usage string.
|
|
||||||
// The argument p points to a []string variable in which to store the value of the flag.
|
|
||||||
// The value of each argument will not try to be separated by comma
|
|
||||||
func StringArrayVar(p *[]string, name string, value []string, usage string) {
|
|
||||||
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
|
|
||||||
CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArray defines a string flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []string variable that stores the value of the flag.
|
|
||||||
// The value of each argument will not try to be separated by comma
|
|
||||||
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
|
|
||||||
p := []string{}
|
|
||||||
f.StringArrayVarP(&p, name, "", value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
|
|
||||||
p := []string{}
|
|
||||||
f.StringArrayVarP(&p, name, shorthand, value, usage)
|
|
||||||
return &p
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArray defines a string flag with specified name, default value, and usage string.
|
|
||||||
// The return value is the address of a []string variable that stores the value of the flag.
|
|
||||||
// The value of each argument will not try to be separated by comma
|
|
||||||
func StringArray(name string, value []string, usage string) *[]string {
|
|
||||||
return CommandLine.StringArrayP(name, "", value, usage)
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
|
|
||||||
func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
|
|
||||||
return CommandLine.StringArrayP(name, shorthand, value, usage)
|
|
||||||
}
|
|
36
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
36
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
|
@ -1,11 +1,13 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/csv"
|
"encoding/csv"
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var _ = fmt.Fprint
|
||||||
|
|
||||||
// -- stringSlice Value
|
// -- stringSlice Value
|
||||||
type stringSliceValue struct {
|
type stringSliceValue struct {
|
||||||
value *[]string
|
value *[]string
|
||||||
|
@ -19,28 +21,10 @@ func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
|
||||||
return ssv
|
return ssv
|
||||||
}
|
}
|
||||||
|
|
||||||
func readAsCSV(val string) ([]string, error) {
|
func (s *stringSliceValue) Set(val string) error {
|
||||||
if val == "" {
|
|
||||||
return []string{}, nil
|
|
||||||
}
|
|
||||||
stringReader := strings.NewReader(val)
|
stringReader := strings.NewReader(val)
|
||||||
csvReader := csv.NewReader(stringReader)
|
csvReader := csv.NewReader(stringReader)
|
||||||
return csvReader.Read()
|
v, err := csvReader.Read()
|
||||||
}
|
|
||||||
|
|
||||||
func writeAsCSV(vals []string) (string, error) {
|
|
||||||
b := &bytes.Buffer{}
|
|
||||||
w := csv.NewWriter(b)
|
|
||||||
err := w.Write(vals)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
w.Flush()
|
|
||||||
return strings.TrimSuffix(b.String(), "\n"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *stringSliceValue) Set(val string) error {
|
|
||||||
v, err := readAsCSV(val)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -57,18 +41,16 @@ func (s *stringSliceValue) Type() string {
|
||||||
return "stringSlice"
|
return "stringSlice"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *stringSliceValue) String() string {
|
func (s *stringSliceValue) String() string { return "[" + strings.Join(*s.value, ",") + "]" }
|
||||||
str, _ := writeAsCSV(*s.value)
|
|
||||||
return "[" + str + "]"
|
|
||||||
}
|
|
||||||
|
|
||||||
func stringSliceConv(sval string) (interface{}, error) {
|
func stringSliceConv(sval string) (interface{}, error) {
|
||||||
sval = sval[1 : len(sval)-1]
|
sval = strings.Trim(sval, "[]")
|
||||||
// An empty string would cause a slice with one (empty) string
|
// An empty string would cause a slice with one (empty) string
|
||||||
if len(sval) == 0 {
|
if len(sval) == 0 {
|
||||||
return []string{}, nil
|
return []string{}, nil
|
||||||
}
|
}
|
||||||
return readAsCSV(sval)
|
v := strings.Split(sval, ",")
|
||||||
|
return v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetStringSlice return the []string value of a flag with the given name
|
// GetStringSlice return the []string value of a flag with the given name
|
||||||
|
|
7
vendor/github.com/spf13/pflag/uint.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- uint Value
|
// -- uint Value
|
||||||
type uintValue uint
|
type uintValue uint
|
||||||
|
@ -20,7 +23,7 @@ func (i *uintValue) Type() string {
|
||||||
return "uint"
|
return "uint"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func uintConv(sval string) (interface{}, error) {
|
func uintConv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseUint(sval, 0, 0)
|
v, err := strconv.ParseUint(sval, 0, 0)
|
||||||
|
|
9
vendor/github.com/spf13/pflag/uint16.go
generated
vendored
9
vendor/github.com/spf13/pflag/uint16.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- uint16 value
|
// -- uint16 value
|
||||||
type uint16Value uint16
|
type uint16Value uint16
|
||||||
|
@ -9,7 +12,7 @@ func newUint16Value(val uint16, p *uint16) *uint16Value {
|
||||||
*p = val
|
*p = val
|
||||||
return (*uint16Value)(p)
|
return (*uint16Value)(p)
|
||||||
}
|
}
|
||||||
|
func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||||
func (i *uint16Value) Set(s string) error {
|
func (i *uint16Value) Set(s string) error {
|
||||||
v, err := strconv.ParseUint(s, 0, 16)
|
v, err := strconv.ParseUint(s, 0, 16)
|
||||||
*i = uint16Value(v)
|
*i = uint16Value(v)
|
||||||
|
@ -20,8 +23,6 @@ func (i *uint16Value) Type() string {
|
||||||
return "uint16"
|
return "uint16"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
|
||||||
|
|
||||||
func uint16Conv(sval string) (interface{}, error) {
|
func uint16Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseUint(sval, 0, 16)
|
v, err := strconv.ParseUint(sval, 0, 16)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
11
vendor/github.com/spf13/pflag/uint32.go
generated
vendored
11
vendor/github.com/spf13/pflag/uint32.go
generated
vendored
|
@ -1,15 +1,18 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- uint32 value
|
// -- uint16 value
|
||||||
type uint32Value uint32
|
type uint32Value uint32
|
||||||
|
|
||||||
func newUint32Value(val uint32, p *uint32) *uint32Value {
|
func newUint32Value(val uint32, p *uint32) *uint32Value {
|
||||||
*p = val
|
*p = val
|
||||||
return (*uint32Value)(p)
|
return (*uint32Value)(p)
|
||||||
}
|
}
|
||||||
|
func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||||
func (i *uint32Value) Set(s string) error {
|
func (i *uint32Value) Set(s string) error {
|
||||||
v, err := strconv.ParseUint(s, 0, 32)
|
v, err := strconv.ParseUint(s, 0, 32)
|
||||||
*i = uint32Value(v)
|
*i = uint32Value(v)
|
||||||
|
@ -20,8 +23,6 @@ func (i *uint32Value) Type() string {
|
||||||
return "uint32"
|
return "uint32"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
|
||||||
|
|
||||||
func uint32Conv(sval string) (interface{}, error) {
|
func uint32Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseUint(sval, 0, 32)
|
v, err := strconv.ParseUint(sval, 0, 32)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
7
vendor/github.com/spf13/pflag/uint64.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint64.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- uint64 Value
|
// -- uint64 Value
|
||||||
type uint64Value uint64
|
type uint64Value uint64
|
||||||
|
@ -20,7 +23,7 @@ func (i *uint64Value) Type() string {
|
||||||
return "uint64"
|
return "uint64"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func uint64Conv(sval string) (interface{}, error) {
|
func uint64Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseUint(sval, 0, 64)
|
v, err := strconv.ParseUint(sval, 0, 64)
|
||||||
|
|
7
vendor/github.com/spf13/pflag/uint8.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint8.go
generated
vendored
|
@ -1,6 +1,9 @@
|
||||||
package pflag
|
package pflag
|
||||||
|
|
||||||
import "strconv"
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
// -- uint8 Value
|
// -- uint8 Value
|
||||||
type uint8Value uint8
|
type uint8Value uint8
|
||||||
|
@ -20,7 +23,7 @@ func (i *uint8Value) Type() string {
|
||||||
return "uint8"
|
return "uint8"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||||
|
|
||||||
func uint8Conv(sval string) (interface{}, error) {
|
func uint8Conv(sval string) (interface{}, error) {
|
||||||
v, err := strconv.ParseUint(sval, 0, 8)
|
v, err := strconv.ParseUint(sval, 0, 8)
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue