mirror of
https://github.com/moby/moby.git
synced 2022-11-09 12:21:53 -05:00
Replace gotestyourself by gotest.tools
github.com/gotestyourself/gotestyourself moved to gotest.tools with version 2.0.0. Moving to that one, bumping it to v2.1.0. Signed-off-by: Vincent Demeester <vincent@sbr.pm>
This commit is contained in:
parent
c752b0991e
commit
c147e9e1a4
28 changed files with 1021 additions and 520 deletions
202
vendor/gotest.tools/LICENSE
vendored
Normal file
202
vendor/gotest.tools/LICENSE
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.
|
||||
31
vendor/gotest.tools/README.md
vendored
Normal file
31
vendor/gotest.tools/README.md
vendored
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
# gotest.tools
|
||||
|
||||
A collection of packages to augment `testing` and support common patterns.
|
||||
|
||||
[](https://godoc.org/gotest.tools)
|
||||
[](https://circleci.com/gh/gotestyourself/gotestyourself/tree/master)
|
||||
[](https://goreportcard.com/report/gotest.tools)
|
||||
|
||||
|
||||
## Packages
|
||||
|
||||
* [assert](http://godoc.org/gotest.tools/assert) -
|
||||
compare values and fail the test when a comparison fails
|
||||
* [env](http://godoc.org/gotest.tools/env) -
|
||||
test code which uses environment variables
|
||||
* [fs](http://godoc.org/gotest.tools/fs) -
|
||||
create temporary files and compare a filesystem tree to an expected value
|
||||
* [golden](http://godoc.org/gotest.tools/golden) -
|
||||
compare large multi-line strings against values frozen in golden files
|
||||
* [icmd](http://godoc.org/gotest.tools/icmd) -
|
||||
execute binaries and test the output
|
||||
* [poll](http://godoc.org/gotest.tools/poll) -
|
||||
test asynchronous code by polling until a desired state is reached
|
||||
* [skip](http://godoc.org/gotest.tools/skip) -
|
||||
skip a test and print the source code of the condition used to skip the test
|
||||
|
||||
## Related
|
||||
|
||||
* [gotest.tools/gotestsum](https://github.com/gotestyourself/gotestsum) - go test runner with custom output
|
||||
* [maxbrunsfeld/counterfeiter](https://github.com/maxbrunsfeld/counterfeiter) - generate fakes for interfaces
|
||||
* [jonboulle/clockwork](https://github.com/jonboulle/clockwork) - a fake clock for testing code that uses `time`
|
||||
311
vendor/gotest.tools/assert/assert.go
vendored
Normal file
311
vendor/gotest.tools/assert/assert.go
vendored
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
/*Package assert provides assertions for comparing expected values to actual
|
||||
values. When an assertion fails a helpful error message is printed.
|
||||
|
||||
Assert and Check
|
||||
|
||||
Assert() and Check() both accept a Comparison, and fail the test when the
|
||||
comparison fails. The one difference is that Assert() will end the test execution
|
||||
immediately (using t.FailNow()) whereas Check() will fail the test (using t.Fail()),
|
||||
return the value of the comparison, then proceed with the rest of the test case.
|
||||
|
||||
Example usage
|
||||
|
||||
The example below shows assert used with some common types.
|
||||
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gotest.tools/assert"
|
||||
is "gotest.tools/assert/cmp"
|
||||
)
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
// booleans
|
||||
assert.Assert(t, ok)
|
||||
assert.Assert(t, !missing)
|
||||
|
||||
// primitives
|
||||
assert.Equal(t, count, 1)
|
||||
assert.Equal(t, msg, "the message")
|
||||
assert.Assert(t, total != 10) // NotEqual
|
||||
|
||||
// errors
|
||||
assert.NilError(t, closer.Close())
|
||||
assert.Error(t, err, "the exact error message")
|
||||
assert.ErrorContains(t, err, "includes this")
|
||||
assert.ErrorType(t, err, os.IsNotExist)
|
||||
|
||||
// complex types
|
||||
assert.DeepEqual(t, result, myStruct{Name: "title"})
|
||||
assert.Assert(t, is.Len(items, 3))
|
||||
assert.Assert(t, len(sequence) != 0) // NotEmpty
|
||||
assert.Assert(t, is.Contains(mapping, "key"))
|
||||
|
||||
// pointers and interface
|
||||
assert.Assert(t, is.Nil(ref))
|
||||
assert.Assert(t, ref != nil) // NotNil
|
||||
}
|
||||
|
||||
Comparisons
|
||||
|
||||
Package https://godoc.org/gotest.tools/assert/cmp provides
|
||||
many common comparisons. Additional comparisons can be written to compare
|
||||
values in other ways. See the example Assert (CustomComparison).
|
||||
|
||||
Automated migration from testify
|
||||
|
||||
gty-migrate-from-testify is a binary which can update source code which uses
|
||||
testify assertions to use the assertions provided by this package.
|
||||
|
||||
See http://bit.do/cmd-gty-migrate-from-testify.
|
||||
|
||||
|
||||
*/
|
||||
package assert // import "gotest.tools/assert"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
gocmp "github.com/google/go-cmp/cmp"
|
||||
"gotest.tools/assert/cmp"
|
||||
"gotest.tools/internal/format"
|
||||
"gotest.tools/internal/source"
|
||||
)
|
||||
|
||||
// BoolOrComparison can be a bool, or cmp.Comparison. See Assert() for usage.
|
||||
type BoolOrComparison interface{}
|
||||
|
||||
// TestingT is the subset of testing.T used by the assert package.
|
||||
type TestingT interface {
|
||||
FailNow()
|
||||
Fail()
|
||||
Log(args ...interface{})
|
||||
}
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
const failureMessage = "assertion failed: "
|
||||
|
||||
// nolint: gocyclo
|
||||
func assert(
|
||||
t TestingT,
|
||||
failer func(),
|
||||
argSelector argSelector,
|
||||
comparison BoolOrComparison,
|
||||
msgAndArgs ...interface{},
|
||||
) bool {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
var success bool
|
||||
switch check := comparison.(type) {
|
||||
case bool:
|
||||
if check {
|
||||
return true
|
||||
}
|
||||
logFailureFromBool(t, msgAndArgs...)
|
||||
|
||||
// Undocumented legacy comparison without Result type
|
||||
case func() (success bool, message string):
|
||||
success = runCompareFunc(t, check, msgAndArgs...)
|
||||
|
||||
case nil:
|
||||
return true
|
||||
|
||||
case error:
|
||||
msg := "error is not nil: "
|
||||
t.Log(format.WithCustomMessage(failureMessage+msg+check.Error(), msgAndArgs...))
|
||||
|
||||
case cmp.Comparison:
|
||||
success = runComparison(t, argSelector, check, msgAndArgs...)
|
||||
|
||||
case func() cmp.Result:
|
||||
success = runComparison(t, argSelector, check, msgAndArgs...)
|
||||
|
||||
default:
|
||||
t.Log(fmt.Sprintf("invalid Comparison: %v (%T)", check, check))
|
||||
}
|
||||
|
||||
if success {
|
||||
return true
|
||||
}
|
||||
failer()
|
||||
return false
|
||||
}
|
||||
|
||||
func runCompareFunc(
|
||||
t TestingT,
|
||||
f func() (success bool, message string),
|
||||
msgAndArgs ...interface{},
|
||||
) bool {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
if success, message := f(); !success {
|
||||
t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func logFailureFromBool(t TestingT, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
const stackIndex = 3 // Assert()/Check(), assert(), formatFailureFromBool()
|
||||
const comparisonArgPos = 1
|
||||
args, err := source.CallExprArgs(stackIndex)
|
||||
if err != nil {
|
||||
t.Log(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
msg, err := boolFailureMessage(args[comparisonArgPos])
|
||||
if err != nil {
|
||||
t.Log(err.Error())
|
||||
msg = "expression is false"
|
||||
}
|
||||
|
||||
t.Log(format.WithCustomMessage(failureMessage+msg, msgAndArgs...))
|
||||
}
|
||||
|
||||
func boolFailureMessage(expr ast.Expr) (string, error) {
|
||||
if binaryExpr, ok := expr.(*ast.BinaryExpr); ok && binaryExpr.Op == token.NEQ {
|
||||
x, err := source.FormatNode(binaryExpr.X)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
y, err := source.FormatNode(binaryExpr.Y)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return x + " is " + y, nil
|
||||
}
|
||||
|
||||
if unaryExpr, ok := expr.(*ast.UnaryExpr); ok && unaryExpr.Op == token.NOT {
|
||||
x, err := source.FormatNode(unaryExpr.X)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return x + " is true", nil
|
||||
}
|
||||
|
||||
formatted, err := source.FormatNode(expr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "expression is false: " + formatted, nil
|
||||
}
|
||||
|
||||
// Assert performs a comparison. If the comparison fails the test is marked as
|
||||
// failed, a failure message is logged, and execution is stopped immediately.
|
||||
//
|
||||
// The comparison argument may be one of three types: bool, cmp.Comparison or
|
||||
// error.
|
||||
// When called with a bool the failure message will contain the literal source
|
||||
// code of the expression.
|
||||
// When called with a cmp.Comparison the comparison is responsible for producing
|
||||
// a helpful failure message.
|
||||
// When called with an error a nil value is considered success. A non-nil error
|
||||
// is a failure, and Error() is used as the failure message.
|
||||
func Assert(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsFromComparisonCall, comparison, msgAndArgs...)
|
||||
}
|
||||
|
||||
// Check performs a comparison. If the comparison fails the test is marked as
|
||||
// failed, a failure message is logged, and Check returns false. Otherwise returns
|
||||
// true.
|
||||
//
|
||||
// See Assert for details about the comparison arg and failure messages.
|
||||
func Check(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) bool {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
return assert(t, t.Fail, argsFromComparisonCall, comparison, msgAndArgs...)
|
||||
}
|
||||
|
||||
// NilError fails the test immediately if err is not nil.
|
||||
// This is equivalent to Assert(t, err)
|
||||
func NilError(t TestingT, err error, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, err, msgAndArgs...)
|
||||
}
|
||||
|
||||
// Equal uses the == operator to assert two values are equal and fails the test
|
||||
// if they are not equal.
|
||||
//
|
||||
// If the comparison fails Equal will use the variable names for x and y as part
|
||||
// of the failure message to identify the actual and expected values.
|
||||
//
|
||||
// If either x or y are a multi-line string the failure message will include a
|
||||
// unified diff of the two values. If the values only differ by whitespace
|
||||
// the unified diff will be augmented by replacing whitespace characters with
|
||||
// visible characters to identify the whitespace difference.
|
||||
//
|
||||
// This is equivalent to Assert(t, cmp.Equal(x, y)).
|
||||
func Equal(t TestingT, x, y interface{}, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, cmp.Equal(x, y), msgAndArgs...)
|
||||
}
|
||||
|
||||
// DeepEqual uses google/go-cmp (http://bit.do/go-cmp) to assert two values are
|
||||
// equal and fails the test if they are not equal.
|
||||
//
|
||||
// Package https://godoc.org/gotest.tools/assert/opt provides some additional
|
||||
// commonly used Options.
|
||||
//
|
||||
// This is equivalent to Assert(t, cmp.DeepEqual(x, y)).
|
||||
func DeepEqual(t TestingT, x, y interface{}, opts ...gocmp.Option) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, cmp.DeepEqual(x, y, opts...))
|
||||
}
|
||||
|
||||
// Error fails the test if err is nil, or the error message is not the expected
|
||||
// message.
|
||||
// Equivalent to Assert(t, cmp.Error(err, message)).
|
||||
func Error(t TestingT, err error, message string, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, cmp.Error(err, message), msgAndArgs...)
|
||||
}
|
||||
|
||||
// ErrorContains fails the test if err is nil, or the error message does not
|
||||
// contain the expected substring.
|
||||
// Equivalent to Assert(t, cmp.ErrorContains(err, substring)).
|
||||
func ErrorContains(t TestingT, err error, substring string, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, cmp.ErrorContains(err, substring), msgAndArgs...)
|
||||
}
|
||||
|
||||
// ErrorType fails the test if err is nil, or err is not the expected type.
|
||||
//
|
||||
// Expected can be one of:
|
||||
// a func(error) bool which returns true if the error is the expected type,
|
||||
// an instance of (or a pointer to) a struct of the expected type,
|
||||
// a pointer to an interface the error is expected to implement,
|
||||
// a reflect.Type of the expected struct or interface.
|
||||
//
|
||||
// Equivalent to Assert(t, cmp.ErrorType(err, expected)).
|
||||
func ErrorType(t TestingT, err error, expected interface{}, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert(t, t.FailNow, argsAfterT, cmp.ErrorType(err, expected), msgAndArgs...)
|
||||
}
|
||||
312
vendor/gotest.tools/assert/cmp/compare.go
vendored
Normal file
312
vendor/gotest.tools/assert/cmp/compare.go
vendored
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
/*Package cmp provides Comparisons for Assert and Check*/
|
||||
package cmp // import "gotest.tools/assert/cmp"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"gotest.tools/internal/format"
|
||||
)
|
||||
|
||||
// Comparison is a function which compares values and returns ResultSuccess if
|
||||
// the actual value matches the expected value. If the values do not match the
|
||||
// Result will contain a message about why it failed.
|
||||
type Comparison func() Result
|
||||
|
||||
// DeepEqual compares two values using google/go-cmp (http://bit.do/go-cmp)
|
||||
// and succeeds if the values are equal.
|
||||
//
|
||||
// The comparison can be customized using comparison Options.
|
||||
// Package https://godoc.org/gotest.tools/assert/opt provides some additional
|
||||
// commonly used Options.
|
||||
func DeepEqual(x, y interface{}, opts ...cmp.Option) Comparison {
|
||||
return func() (result Result) {
|
||||
defer func() {
|
||||
if panicmsg, handled := handleCmpPanic(recover()); handled {
|
||||
result = ResultFailure(panicmsg)
|
||||
}
|
||||
}()
|
||||
diff := cmp.Diff(x, y, opts...)
|
||||
if diff == "" {
|
||||
return ResultSuccess
|
||||
}
|
||||
return multiLineDiffResult(diff)
|
||||
}
|
||||
}
|
||||
|
||||
func handleCmpPanic(r interface{}) (string, bool) {
|
||||
if r == nil {
|
||||
return "", false
|
||||
}
|
||||
panicmsg, ok := r.(string)
|
||||
if !ok {
|
||||
panic(r)
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(panicmsg, "cannot handle unexported field"):
|
||||
return panicmsg, true
|
||||
}
|
||||
panic(r)
|
||||
}
|
||||
|
||||
func toResult(success bool, msg string) Result {
|
||||
if success {
|
||||
return ResultSuccess
|
||||
}
|
||||
return ResultFailure(msg)
|
||||
}
|
||||
|
||||
// Equal succeeds if x == y. See assert.Equal for full documentation.
|
||||
func Equal(x, y interface{}) Comparison {
|
||||
return func() Result {
|
||||
switch {
|
||||
case x == y:
|
||||
return ResultSuccess
|
||||
case isMultiLineStringCompare(x, y):
|
||||
diff := format.UnifiedDiff(format.DiffConfig{A: x.(string), B: y.(string)})
|
||||
return multiLineDiffResult(diff)
|
||||
}
|
||||
return ResultFailureTemplate(`
|
||||
{{- .Data.x}} (
|
||||
{{- with callArg 0 }}{{ formatNode . }} {{end -}}
|
||||
{{- printf "%T" .Data.x -}}
|
||||
) != {{ .Data.y}} (
|
||||
{{- with callArg 1 }}{{ formatNode . }} {{end -}}
|
||||
{{- printf "%T" .Data.y -}}
|
||||
)`,
|
||||
map[string]interface{}{"x": x, "y": y})
|
||||
}
|
||||
}
|
||||
|
||||
func isMultiLineStringCompare(x, y interface{}) bool {
|
||||
strX, ok := x.(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
strY, ok := y.(string)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return strings.Contains(strX, "\n") || strings.Contains(strY, "\n")
|
||||
}
|
||||
|
||||
func multiLineDiffResult(diff string) Result {
|
||||
return ResultFailureTemplate(`
|
||||
--- {{ with callArg 0 }}{{ formatNode . }}{{else}}←{{end}}
|
||||
+++ {{ with callArg 1 }}{{ formatNode . }}{{else}}→{{end}}
|
||||
{{ .Data.diff }}`,
|
||||
map[string]interface{}{"diff": diff})
|
||||
}
|
||||
|
||||
// Len succeeds if the sequence has the expected length.
|
||||
func Len(seq interface{}, expected int) Comparison {
|
||||
return func() (result Result) {
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
result = ResultFailure(fmt.Sprintf("type %T does not have a length", seq))
|
||||
}
|
||||
}()
|
||||
value := reflect.ValueOf(seq)
|
||||
length := value.Len()
|
||||
if length == expected {
|
||||
return ResultSuccess
|
||||
}
|
||||
msg := fmt.Sprintf("expected %s (length %d) to have length %d", seq, length, expected)
|
||||
return ResultFailure(msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Contains succeeds if item is in collection. Collection may be a string, map,
|
||||
// slice, or array.
|
||||
//
|
||||
// If collection is a string, item must also be a string, and is compared using
|
||||
// strings.Contains().
|
||||
// If collection is a Map, contains will succeed if item is a key in the map.
|
||||
// If collection is a slice or array, item is compared to each item in the
|
||||
// sequence using reflect.DeepEqual().
|
||||
func Contains(collection interface{}, item interface{}) Comparison {
|
||||
return func() Result {
|
||||
colValue := reflect.ValueOf(collection)
|
||||
if !colValue.IsValid() {
|
||||
return ResultFailure(fmt.Sprintf("nil does not contain items"))
|
||||
}
|
||||
msg := fmt.Sprintf("%v does not contain %v", collection, item)
|
||||
|
||||
itemValue := reflect.ValueOf(item)
|
||||
switch colValue.Type().Kind() {
|
||||
case reflect.String:
|
||||
if itemValue.Type().Kind() != reflect.String {
|
||||
return ResultFailure("string may only contain strings")
|
||||
}
|
||||
return toResult(
|
||||
strings.Contains(colValue.String(), itemValue.String()),
|
||||
fmt.Sprintf("string %q does not contain %q", collection, item))
|
||||
|
||||
case reflect.Map:
|
||||
if itemValue.Type() != colValue.Type().Key() {
|
||||
return ResultFailure(fmt.Sprintf(
|
||||
"%v can not contain a %v key", colValue.Type(), itemValue.Type()))
|
||||
}
|
||||
return toResult(colValue.MapIndex(itemValue).IsValid(), msg)
|
||||
|
||||
case reflect.Slice, reflect.Array:
|
||||
for i := 0; i < colValue.Len(); i++ {
|
||||
if reflect.DeepEqual(colValue.Index(i).Interface(), item) {
|
||||
return ResultSuccess
|
||||
}
|
||||
}
|
||||
return ResultFailure(msg)
|
||||
default:
|
||||
return ResultFailure(fmt.Sprintf("type %T does not contain items", collection))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Panics succeeds if f() panics.
|
||||
func Panics(f func()) Comparison {
|
||||
return func() (result Result) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
result = ResultSuccess
|
||||
}
|
||||
}()
|
||||
f()
|
||||
return ResultFailure("did not panic")
|
||||
}
|
||||
}
|
||||
|
||||
// Error succeeds if err is a non-nil error, and the error message equals the
|
||||
// expected message.
|
||||
func Error(err error, message string) Comparison {
|
||||
return func() Result {
|
||||
switch {
|
||||
case err == nil:
|
||||
return ResultFailure("expected an error, got nil")
|
||||
case err.Error() != message:
|
||||
return ResultFailure(fmt.Sprintf(
|
||||
"expected error %q, got %+v", message, err))
|
||||
}
|
||||
return ResultSuccess
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorContains succeeds if err is a non-nil error, and the error message contains
|
||||
// the expected substring.
|
||||
func ErrorContains(err error, substring string) Comparison {
|
||||
return func() Result {
|
||||
switch {
|
||||
case err == nil:
|
||||
return ResultFailure("expected an error, got nil")
|
||||
case !strings.Contains(err.Error(), substring):
|
||||
return ResultFailure(fmt.Sprintf(
|
||||
"expected error to contain %q, got %+v", substring, err))
|
||||
}
|
||||
return ResultSuccess
|
||||
}
|
||||
}
|
||||
|
||||
// Nil succeeds if obj is a nil interface, pointer, or function.
|
||||
//
|
||||
// Use NilError() for comparing errors. Use Len(obj, 0) for comparing slices,
|
||||
// maps, and channels.
|
||||
func Nil(obj interface{}) Comparison {
|
||||
msgFunc := func(value reflect.Value) string {
|
||||
return fmt.Sprintf("%v (type %s) is not nil", reflect.Indirect(value), value.Type())
|
||||
}
|
||||
return isNil(obj, msgFunc)
|
||||
}
|
||||
|
||||
func isNil(obj interface{}, msgFunc func(reflect.Value) string) Comparison {
|
||||
return func() Result {
|
||||
if obj == nil {
|
||||
return ResultSuccess
|
||||
}
|
||||
value := reflect.ValueOf(obj)
|
||||
kind := value.Type().Kind()
|
||||
if kind >= reflect.Chan && kind <= reflect.Slice {
|
||||
if value.IsNil() {
|
||||
return ResultSuccess
|
||||
}
|
||||
return ResultFailure(msgFunc(value))
|
||||
}
|
||||
|
||||
return ResultFailure(fmt.Sprintf("%v (type %s) can not be nil", value, value.Type()))
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorType succeeds if err is not nil and is of the expected type.
|
||||
//
|
||||
// Expected can be one of:
|
||||
// a func(error) bool which returns true if the error is the expected type,
|
||||
// an instance of (or a pointer to) a struct of the expected type,
|
||||
// a pointer to an interface the error is expected to implement,
|
||||
// a reflect.Type of the expected struct or interface.
|
||||
func ErrorType(err error, expected interface{}) Comparison {
|
||||
return func() Result {
|
||||
switch expectedType := expected.(type) {
|
||||
case func(error) bool:
|
||||
return cmpErrorTypeFunc(err, expectedType)
|
||||
case reflect.Type:
|
||||
if expectedType.Kind() == reflect.Interface {
|
||||
return cmpErrorTypeImplementsType(err, expectedType)
|
||||
}
|
||||
return cmpErrorTypeEqualType(err, expectedType)
|
||||
case nil:
|
||||
return ResultFailure(fmt.Sprintf("invalid type for expected: nil"))
|
||||
}
|
||||
|
||||
expectedType := reflect.TypeOf(expected)
|
||||
switch {
|
||||
case expectedType.Kind() == reflect.Struct, isPtrToStruct(expectedType):
|
||||
return cmpErrorTypeEqualType(err, expectedType)
|
||||
case isPtrToInterface(expectedType):
|
||||
return cmpErrorTypeImplementsType(err, expectedType.Elem())
|
||||
}
|
||||
return ResultFailure(fmt.Sprintf("invalid type for expected: %T", expected))
|
||||
}
|
||||
}
|
||||
|
||||
func cmpErrorTypeFunc(err error, f func(error) bool) Result {
|
||||
if f(err) {
|
||||
return ResultSuccess
|
||||
}
|
||||
actual := "nil"
|
||||
if err != nil {
|
||||
actual = fmt.Sprintf("%s (%T)", err, err)
|
||||
}
|
||||
return ResultFailureTemplate(`error is {{ .Data.actual }}
|
||||
{{- with callArg 1 }}, not {{ formatNode . }}{{end -}}`,
|
||||
map[string]interface{}{"actual": actual})
|
||||
}
|
||||
|
||||
func cmpErrorTypeEqualType(err error, expectedType reflect.Type) Result {
|
||||
if err == nil {
|
||||
return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
|
||||
}
|
||||
errValue := reflect.ValueOf(err)
|
||||
if errValue.Type() == expectedType {
|
||||
return ResultSuccess
|
||||
}
|
||||
return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
|
||||
}
|
||||
|
||||
func cmpErrorTypeImplementsType(err error, expectedType reflect.Type) Result {
|
||||
if err == nil {
|
||||
return ResultFailure(fmt.Sprintf("error is nil, not %s", expectedType))
|
||||
}
|
||||
errValue := reflect.ValueOf(err)
|
||||
if errValue.Type().Implements(expectedType) {
|
||||
return ResultSuccess
|
||||
}
|
||||
return ResultFailure(fmt.Sprintf("error is %s (%T), not %s", err, err, expectedType))
|
||||
}
|
||||
|
||||
func isPtrToInterface(typ reflect.Type) bool {
|
||||
return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Interface
|
||||
}
|
||||
|
||||
func isPtrToStruct(typ reflect.Type) bool {
|
||||
return typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct
|
||||
}
|
||||
94
vendor/gotest.tools/assert/cmp/result.go
vendored
Normal file
94
vendor/gotest.tools/assert/cmp/result.go
vendored
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
package cmp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"text/template"
|
||||
|
||||
"gotest.tools/internal/source"
|
||||
)
|
||||
|
||||
// Result of a Comparison.
|
||||
type Result interface {
|
||||
Success() bool
|
||||
}
|
||||
|
||||
type result struct {
|
||||
success bool
|
||||
message string
|
||||
}
|
||||
|
||||
func (r result) Success() bool {
|
||||
return r.success
|
||||
}
|
||||
|
||||
func (r result) FailureMessage() string {
|
||||
return r.message
|
||||
}
|
||||
|
||||
// ResultSuccess is a constant which is returned by a ComparisonWithResult to
|
||||
// indicate success.
|
||||
var ResultSuccess = result{success: true}
|
||||
|
||||
// ResultFailure returns a failed Result with a failure message.
|
||||
func ResultFailure(message string) Result {
|
||||
return result{message: message}
|
||||
}
|
||||
|
||||
// ResultFromError returns ResultSuccess if err is nil. Otherwise ResultFailure
|
||||
// is returned with the error message as the failure message.
|
||||
func ResultFromError(err error) Result {
|
||||
if err == nil {
|
||||
return ResultSuccess
|
||||
}
|
||||
return ResultFailure(err.Error())
|
||||
}
|
||||
|
||||
type templatedResult struct {
|
||||
success bool
|
||||
template string
|
||||
data map[string]interface{}
|
||||
}
|
||||
|
||||
func (r templatedResult) Success() bool {
|
||||
return r.success
|
||||
}
|
||||
|
||||
func (r templatedResult) FailureMessage(args []ast.Expr) string {
|
||||
msg, err := renderMessage(r, args)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("failed to render failure message: %s", err)
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
// ResultFailureTemplate returns a Result with a template string and data which
|
||||
// can be used to format a failure message. The template may access data from .Data,
|
||||
// the comparison args with the callArg function, and the formatNode function may
|
||||
// be used to format the call args.
|
||||
func ResultFailureTemplate(template string, data map[string]interface{}) Result {
|
||||
return templatedResult{template: template, data: data}
|
||||
}
|
||||
|
||||
func renderMessage(result templatedResult, args []ast.Expr) (string, error) {
|
||||
tmpl := template.New("failure").Funcs(template.FuncMap{
|
||||
"formatNode": source.FormatNode,
|
||||
"callArg": func(index int) ast.Expr {
|
||||
if index >= len(args) {
|
||||
return nil
|
||||
}
|
||||
return args[index]
|
||||
},
|
||||
})
|
||||
var err error
|
||||
tmpl, err = tmpl.Parse(result.template)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
err = tmpl.Execute(buf, map[string]interface{}{
|
||||
"Data": result.data,
|
||||
})
|
||||
return buf.String(), err
|
||||
}
|
||||
107
vendor/gotest.tools/assert/result.go
vendored
Normal file
107
vendor/gotest.tools/assert/result.go
vendored
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
package assert
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
|
||||
"gotest.tools/assert/cmp"
|
||||
"gotest.tools/internal/format"
|
||||
"gotest.tools/internal/source"
|
||||
)
|
||||
|
||||
func runComparison(
|
||||
t TestingT,
|
||||
argSelector argSelector,
|
||||
f cmp.Comparison,
|
||||
msgAndArgs ...interface{},
|
||||
) bool {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
result := f()
|
||||
if result.Success() {
|
||||
return true
|
||||
}
|
||||
|
||||
var message string
|
||||
switch typed := result.(type) {
|
||||
case resultWithComparisonArgs:
|
||||
const stackIndex = 3 // Assert/Check, assert, runComparison
|
||||
args, err := source.CallExprArgs(stackIndex)
|
||||
if err != nil {
|
||||
t.Log(err.Error())
|
||||
}
|
||||
message = typed.FailureMessage(filterPrintableExpr(argSelector(args)))
|
||||
case resultBasic:
|
||||
message = typed.FailureMessage()
|
||||
default:
|
||||
message = fmt.Sprintf("comparison returned invalid Result type: %T", result)
|
||||
}
|
||||
|
||||
t.Log(format.WithCustomMessage(failureMessage+message, msgAndArgs...))
|
||||
return false
|
||||
}
|
||||
|
||||
type resultWithComparisonArgs interface {
|
||||
FailureMessage(args []ast.Expr) string
|
||||
}
|
||||
|
||||
type resultBasic interface {
|
||||
FailureMessage() string
|
||||
}
|
||||
|
||||
// filterPrintableExpr filters the ast.Expr slice to only include Expr that are
|
||||
// easy to read when printed and contain relevant information to an assertion.
|
||||
//
|
||||
// Ident and SelectorExpr are included because they print nicely and the variable
|
||||
// names may provide additional context to their values.
|
||||
// BasicLit and CompositeLit are excluded because their source is equivalent to
|
||||
// their value, which is already available.
|
||||
// Other types are ignored for now, but could be added if they are relevant.
|
||||
func filterPrintableExpr(args []ast.Expr) []ast.Expr {
|
||||
result := make([]ast.Expr, len(args))
|
||||
for i, arg := range args {
|
||||
if isShortPrintableExpr(arg) {
|
||||
result[i] = arg
|
||||
continue
|
||||
}
|
||||
|
||||
if starExpr, ok := arg.(*ast.StarExpr); ok {
|
||||
result[i] = starExpr.X
|
||||
continue
|
||||
}
|
||||
result[i] = nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func isShortPrintableExpr(expr ast.Expr) bool {
|
||||
switch expr.(type) {
|
||||
case *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr:
|
||||
return true
|
||||
case *ast.BinaryExpr, *ast.UnaryExpr:
|
||||
return true
|
||||
default:
|
||||
// CallExpr, ParenExpr, TypeAssertExpr, KeyValueExpr, StarExpr
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type argSelector func([]ast.Expr) []ast.Expr
|
||||
|
||||
func argsAfterT(args []ast.Expr) []ast.Expr {
|
||||
if len(args) < 1 {
|
||||
return nil
|
||||
}
|
||||
return args[1:]
|
||||
}
|
||||
|
||||
func argsFromComparisonCall(args []ast.Expr) []ast.Expr {
|
||||
if len(args) < 1 {
|
||||
return nil
|
||||
}
|
||||
if callExpr, ok := args[1].(*ast.CallExpr); ok {
|
||||
return callExpr.Args
|
||||
}
|
||||
return nil
|
||||
}
|
||||
111
vendor/gotest.tools/env/env.go
vendored
Normal file
111
vendor/gotest.tools/env/env.go
vendored
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
/*Package env provides functions to test code that read environment variables
|
||||
or the current working directory.
|
||||
*/
|
||||
package env // import "gotest.tools/env"
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gotest.tools/assert"
|
||||
"gotest.tools/x/subtest"
|
||||
)
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
// Patch changes the value of an environment variable, and returns a
|
||||
// function which will reset the the value of that variable back to the
|
||||
// previous state.
|
||||
func Patch(t assert.TestingT, key, value string) func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
oldValue, ok := os.LookupEnv(key)
|
||||
assert.NilError(t, os.Setenv(key, value))
|
||||
cleanup := func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
if !ok {
|
||||
assert.NilError(t, os.Unsetenv(key))
|
||||
return
|
||||
}
|
||||
assert.NilError(t, os.Setenv(key, oldValue))
|
||||
}
|
||||
if tc, ok := t.(subtest.TestContext); ok {
|
||||
tc.AddCleanup(cleanup)
|
||||
}
|
||||
return cleanup
|
||||
}
|
||||
|
||||
// PatchAll sets the environment to env, and returns a function which will
|
||||
// reset the environment back to the previous state.
|
||||
func PatchAll(t assert.TestingT, env map[string]string) func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
oldEnv := os.Environ()
|
||||
os.Clearenv()
|
||||
|
||||
for key, value := range env {
|
||||
assert.NilError(t, os.Setenv(key, value), "setenv %s=%s", key, value)
|
||||
}
|
||||
cleanup := func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
os.Clearenv()
|
||||
for key, oldVal := range ToMap(oldEnv) {
|
||||
assert.NilError(t, os.Setenv(key, oldVal), "setenv %s=%s", key, oldVal)
|
||||
}
|
||||
}
|
||||
if tc, ok := t.(subtest.TestContext); ok {
|
||||
tc.AddCleanup(cleanup)
|
||||
}
|
||||
return cleanup
|
||||
}
|
||||
|
||||
// ToMap takes a list of strings in the format returned by os.Environ() and
|
||||
// returns a mapping of keys to values.
|
||||
func ToMap(env []string) map[string]string {
|
||||
result := map[string]string{}
|
||||
for _, raw := range env {
|
||||
key, value := getParts(raw)
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func getParts(raw string) (string, string) {
|
||||
// Environment variables on windows can begin with =
|
||||
// http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx
|
||||
parts := strings.SplitN(raw[1:], "=", 2)
|
||||
key := raw[:1] + parts[0]
|
||||
if len(parts) == 1 {
|
||||
return key, ""
|
||||
}
|
||||
return key, parts[1]
|
||||
}
|
||||
|
||||
// ChangeWorkingDir to the directory, and return a function which restores the
|
||||
// previous working directory.
|
||||
func ChangeWorkingDir(t assert.TestingT, dir string) func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
cwd, err := os.Getwd()
|
||||
assert.NilError(t, err)
|
||||
assert.NilError(t, os.Chdir(dir))
|
||||
cleanup := func() {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert.NilError(t, os.Chdir(cwd))
|
||||
}
|
||||
if tc, ok := t.(subtest.TestContext); ok {
|
||||
tc.AddCleanup(cleanup)
|
||||
}
|
||||
return cleanup
|
||||
}
|
||||
106
vendor/gotest.tools/fs/file.go
vendored
Normal file
106
vendor/gotest.tools/fs/file.go
vendored
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
/*Package fs provides tools for creating temporary files, and testing the
|
||||
contents and structure of a directory.
|
||||
*/
|
||||
package fs // import "gotest.tools/fs"
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"gotest.tools/assert"
|
||||
"gotest.tools/x/subtest"
|
||||
)
|
||||
|
||||
// Path objects return their filesystem path. Path may be implemented by a
|
||||
// real filesystem object (such as File and Dir) or by a type which updates
|
||||
// entries in a Manifest.
|
||||
type Path interface {
|
||||
Path() string
|
||||
Remove()
|
||||
}
|
||||
|
||||
var (
|
||||
_ Path = &Dir{}
|
||||
_ Path = &File{}
|
||||
)
|
||||
|
||||
// File is a temporary file on the filesystem
|
||||
type File struct {
|
||||
path string
|
||||
}
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
// NewFile creates a new file in a temporary directory using prefix as part of
|
||||
// the filename. The PathOps are applied to the before returning the File.
|
||||
func NewFile(t assert.TestingT, prefix string, ops ...PathOp) *File {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
tempfile, err := ioutil.TempFile("", prefix+"-")
|
||||
assert.NilError(t, err)
|
||||
file := &File{path: tempfile.Name()}
|
||||
assert.NilError(t, tempfile.Close())
|
||||
|
||||
for _, op := range ops {
|
||||
assert.NilError(t, op(file))
|
||||
}
|
||||
if tc, ok := t.(subtest.TestContext); ok {
|
||||
tc.AddCleanup(file.Remove)
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
// Path returns the full path to the file
|
||||
func (f *File) Path() string {
|
||||
return f.path
|
||||
}
|
||||
|
||||
// Remove the file
|
||||
func (f *File) Remove() {
|
||||
// nolint: errcheck
|
||||
os.Remove(f.path)
|
||||
}
|
||||
|
||||
// Dir is a temporary directory
|
||||
type Dir struct {
|
||||
path string
|
||||
}
|
||||
|
||||
// NewDir returns a new temporary directory using prefix as part of the directory
|
||||
// name. The PathOps are applied before returning the Dir.
|
||||
func NewDir(t assert.TestingT, prefix string, ops ...PathOp) *Dir {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
path, err := ioutil.TempDir("", prefix+"-")
|
||||
assert.NilError(t, err)
|
||||
dir := &Dir{path: path}
|
||||
|
||||
for _, op := range ops {
|
||||
assert.NilError(t, op(dir))
|
||||
}
|
||||
if tc, ok := t.(subtest.TestContext); ok {
|
||||
tc.AddCleanup(dir.Remove)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// Path returns the full path to the directory
|
||||
func (d *Dir) Path() string {
|
||||
return d.path
|
||||
}
|
||||
|
||||
// Remove the directory
|
||||
func (d *Dir) Remove() {
|
||||
// nolint: errcheck
|
||||
os.RemoveAll(d.path)
|
||||
}
|
||||
|
||||
// Join returns a new path with this directory as the base of the path
|
||||
func (d *Dir) Join(parts ...string) string {
|
||||
return filepath.Join(append([]string{d.Path()}, parts...)...)
|
||||
}
|
||||
129
vendor/gotest.tools/fs/manifest.go
vendored
Normal file
129
vendor/gotest.tools/fs/manifest.go
vendored
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
// Manifest stores the expected structure and properties of files and directories
|
||||
// in a filesystem.
|
||||
type Manifest struct {
|
||||
root *directory
|
||||
}
|
||||
|
||||
type resource struct {
|
||||
mode os.FileMode
|
||||
uid uint32
|
||||
gid uint32
|
||||
}
|
||||
|
||||
type file struct {
|
||||
resource
|
||||
content io.ReadCloser
|
||||
}
|
||||
|
||||
func (f *file) Type() string {
|
||||
return "file"
|
||||
}
|
||||
|
||||
type symlink struct {
|
||||
resource
|
||||
target string
|
||||
}
|
||||
|
||||
func (f *symlink) Type() string {
|
||||
return "symlink"
|
||||
}
|
||||
|
||||
type directory struct {
|
||||
resource
|
||||
items map[string]dirEntry
|
||||
}
|
||||
|
||||
func (f *directory) Type() string {
|
||||
return "directory"
|
||||
}
|
||||
|
||||
type dirEntry interface {
|
||||
Type() string
|
||||
}
|
||||
|
||||
// ManifestFromDir creates a Manifest by reading the directory at path. The
|
||||
// manifest stores the structure and properties of files in the directory.
|
||||
// ManifestFromDir can be used with Equal to compare two directories.
|
||||
func ManifestFromDir(t assert.TestingT, path string) Manifest {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
|
||||
manifest, err := manifestFromDir(path)
|
||||
assert.NilError(t, err)
|
||||
return manifest
|
||||
}
|
||||
|
||||
func manifestFromDir(path string) (Manifest, error) {
|
||||
info, err := os.Stat(path)
|
||||
switch {
|
||||
case err != nil:
|
||||
return Manifest{}, err
|
||||
case !info.IsDir():
|
||||
return Manifest{}, errors.Errorf("path %s must be a directory", path)
|
||||
}
|
||||
|
||||
directory, err := newDirectory(path, info)
|
||||
return Manifest{root: directory}, err
|
||||
}
|
||||
|
||||
func newDirectory(path string, info os.FileInfo) (*directory, error) {
|
||||
items := make(map[string]dirEntry)
|
||||
children, err := ioutil.ReadDir(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
fullPath := filepath.Join(path, child.Name())
|
||||
items[child.Name()], err = getTypedResource(fullPath, child)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return &directory{
|
||||
resource: newResourceFromInfo(info),
|
||||
items: items,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getTypedResource(path string, info os.FileInfo) (dirEntry, error) {
|
||||
switch {
|
||||
case info.IsDir():
|
||||
return newDirectory(path, info)
|
||||
case info.Mode()&os.ModeSymlink != 0:
|
||||
return newSymlink(path, info)
|
||||
// TODO: devices, pipes?
|
||||
default:
|
||||
return newFile(path, info)
|
||||
}
|
||||
}
|
||||
|
||||
func newSymlink(path string, info os.FileInfo) (*symlink, error) {
|
||||
target, err := os.Readlink(path)
|
||||
return &symlink{
|
||||
resource: newResourceFromInfo(info),
|
||||
target: target,
|
||||
}, err
|
||||
}
|
||||
|
||||
func newFile(path string, info os.FileInfo) (*file, error) {
|
||||
// TODO: defer file opening to reduce number of open FDs?
|
||||
readCloser, err := os.Open(path)
|
||||
return &file{
|
||||
resource: newResourceFromInfo(info),
|
||||
content: readCloser,
|
||||
}, err
|
||||
}
|
||||
30
vendor/gotest.tools/fs/manifest_unix.go
vendored
Normal file
30
vendor/gotest.tools/fs/manifest_unix.go
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// +build !windows
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultRootDirMode = os.ModeDir | 0700
|
||||
defaultSymlinkMode = os.ModeSymlink | 0777
|
||||
)
|
||||
|
||||
func newResourceFromInfo(info os.FileInfo) resource {
|
||||
statT := info.Sys().(*syscall.Stat_t)
|
||||
return resource{
|
||||
mode: info.Mode(),
|
||||
uid: statT.Uid,
|
||||
gid: statT.Gid,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *filePath) SetMode(mode os.FileMode) {
|
||||
p.file.mode = mode
|
||||
}
|
||||
|
||||
func (p *directoryPath) SetMode(mode os.FileMode) {
|
||||
p.directory.mode = mode | os.ModeDir
|
||||
}
|
||||
22
vendor/gotest.tools/fs/manifest_windows.go
vendored
Normal file
22
vendor/gotest.tools/fs/manifest_windows.go
vendored
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
package fs
|
||||
|
||||
import "os"
|
||||
|
||||
const (
|
||||
defaultRootDirMode = os.ModeDir | 0777
|
||||
defaultSymlinkMode = os.ModeSymlink | 0666
|
||||
)
|
||||
|
||||
func newResourceFromInfo(info os.FileInfo) resource {
|
||||
return resource{mode: info.Mode()}
|
||||
}
|
||||
|
||||
func (p *filePath) SetMode(mode os.FileMode) {
|
||||
bits := mode & 0600
|
||||
p.file.mode = bits + bits/010 + bits/0100
|
||||
}
|
||||
|
||||
// TODO: is mode ignored on windows?
|
||||
func (p *directoryPath) SetMode(mode os.FileMode) {
|
||||
p.directory.mode = defaultRootDirMode
|
||||
}
|
||||
237
vendor/gotest.tools/fs/ops.go
vendored
Normal file
237
vendor/gotest.tools/fs/ops.go
vendored
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const defaultFileMode = 0644
|
||||
|
||||
// PathOp is a function which accepts a Path and performs an operation on that
|
||||
// path. When called with real filesystem objects (File or Dir) a PathOp modifies
|
||||
// the filesystem at the path. When used with a Manifest object a PathOp updates
|
||||
// the manifest to expect a value.
|
||||
type PathOp func(path Path) error
|
||||
|
||||
type manifestResource interface {
|
||||
SetMode(mode os.FileMode)
|
||||
SetUID(uid uint32)
|
||||
SetGID(gid uint32)
|
||||
}
|
||||
|
||||
type manifestFile interface {
|
||||
manifestResource
|
||||
SetContent(content io.ReadCloser)
|
||||
}
|
||||
|
||||
type manifestDirectory interface {
|
||||
manifestResource
|
||||
AddSymlink(path, target string) error
|
||||
AddFile(path string, ops ...PathOp) error
|
||||
AddDirectory(path string, ops ...PathOp) error
|
||||
}
|
||||
|
||||
// WithContent writes content to a file at Path
|
||||
func WithContent(content string) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestFile); ok {
|
||||
m.SetContent(ioutil.NopCloser(strings.NewReader(content)))
|
||||
return nil
|
||||
}
|
||||
return ioutil.WriteFile(path.Path(), []byte(content), defaultFileMode)
|
||||
}
|
||||
}
|
||||
|
||||
// WithBytes write bytes to a file at Path
|
||||
func WithBytes(raw []byte) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestFile); ok {
|
||||
m.SetContent(ioutil.NopCloser(bytes.NewReader(raw)))
|
||||
return nil
|
||||
}
|
||||
return ioutil.WriteFile(path.Path(), raw, defaultFileMode)
|
||||
}
|
||||
}
|
||||
|
||||
// AsUser changes ownership of the file system object at Path
|
||||
func AsUser(uid, gid int) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestResource); ok {
|
||||
m.SetUID(uint32(uid))
|
||||
m.SetGID(uint32(gid))
|
||||
return nil
|
||||
}
|
||||
return os.Chown(path.Path(), uid, gid)
|
||||
}
|
||||
}
|
||||
|
||||
// WithFile creates a file in the directory at path with content
|
||||
func WithFile(filename, content string, ops ...PathOp) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestDirectory); ok {
|
||||
ops = append([]PathOp{WithContent(content), WithMode(defaultFileMode)}, ops...)
|
||||
return m.AddFile(filename, ops...)
|
||||
}
|
||||
|
||||
fullpath := filepath.Join(path.Path(), filepath.FromSlash(filename))
|
||||
if err := createFile(fullpath, content); err != nil {
|
||||
return err
|
||||
}
|
||||
return applyPathOps(&File{path: fullpath}, ops)
|
||||
}
|
||||
}
|
||||
|
||||
func createFile(fullpath string, content string) error {
|
||||
return ioutil.WriteFile(fullpath, []byte(content), defaultFileMode)
|
||||
}
|
||||
|
||||
// WithFiles creates all the files in the directory at path with their content
|
||||
func WithFiles(files map[string]string) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestDirectory); ok {
|
||||
for filename, content := range files {
|
||||
// TODO: remove duplication with WithFile
|
||||
if err := m.AddFile(filename, WithContent(content), WithMode(defaultFileMode)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
for filename, content := range files {
|
||||
fullpath := filepath.Join(path.Path(), filepath.FromSlash(filename))
|
||||
if err := createFile(fullpath, content); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// FromDir copies the directory tree from the source path into the new Dir
|
||||
func FromDir(source string) PathOp {
|
||||
return func(path Path) error {
|
||||
if _, ok := path.(manifestDirectory); ok {
|
||||
return errors.New("use manifest.FromDir")
|
||||
}
|
||||
return copyDirectory(source, path.Path())
|
||||
}
|
||||
}
|
||||
|
||||
// WithDir creates a subdirectory in the directory at path. Additional PathOp
|
||||
// can be used to modify the subdirectory
|
||||
func WithDir(name string, ops ...PathOp) PathOp {
|
||||
const defaultMode = 0755
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestDirectory); ok {
|
||||
ops = append([]PathOp{WithMode(defaultMode)}, ops...)
|
||||
return m.AddDirectory(name, ops...)
|
||||
}
|
||||
|
||||
fullpath := filepath.Join(path.Path(), filepath.FromSlash(name))
|
||||
err := os.MkdirAll(fullpath, defaultMode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return applyPathOps(&Dir{path: fullpath}, ops)
|
||||
}
|
||||
}
|
||||
|
||||
func applyPathOps(path Path, ops []PathOp) error {
|
||||
for _, op := range ops {
|
||||
if err := op(path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithMode sets the file mode on the directory or file at path
|
||||
func WithMode(mode os.FileMode) PathOp {
|
||||
return func(path Path) error {
|
||||
if m, ok := path.(manifestResource); ok {
|
||||
m.SetMode(mode)
|
||||
return nil
|
||||
}
|
||||
return os.Chmod(path.Path(), mode)
|
||||
}
|
||||
}
|
||||
|
||||
func copyDirectory(source, dest string) error {
|
||||
entries, err := ioutil.ReadDir(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
sourcePath := filepath.Join(source, entry.Name())
|
||||
destPath := filepath.Join(dest, entry.Name())
|
||||
if entry.IsDir() {
|
||||
if err := os.Mkdir(destPath, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := copyDirectory(sourcePath, destPath); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
// TODO: handle symlinks
|
||||
if err := copyFile(sourcePath, destPath); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyFile(source, dest string) error {
|
||||
content, err := ioutil.ReadFile(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ioutil.WriteFile(dest, content, 0644)
|
||||
}
|
||||
|
||||
// WithSymlink creates a symlink in the directory which links to target.
|
||||
// Target must be a path relative to the directory.
|
||||
//
|
||||
// Note: the argument order is the inverse of os.Symlink to be consistent with
|
||||
// the other functions in this package.
|
||||
func WithSymlink(path, target string) PathOp {
|
||||
return func(root Path) error {
|
||||
if v, ok := root.(manifestDirectory); ok {
|
||||
return v.AddSymlink(path, target)
|
||||
}
|
||||
return os.Symlink(filepath.Join(root.Path(), target), filepath.Join(root.Path(), path))
|
||||
}
|
||||
}
|
||||
|
||||
// WithHardlink creates a link in the directory which links to target.
|
||||
// Target must be a path relative to the directory.
|
||||
//
|
||||
// Note: the argument order is the inverse of os.Link to be consistent with
|
||||
// the other functions in this package.
|
||||
func WithHardlink(path, target string) PathOp {
|
||||
return func(root Path) error {
|
||||
if _, ok := root.(manifestDirectory); ok {
|
||||
return errors.New("WithHardlink yet implemented for manifests")
|
||||
}
|
||||
return os.Link(filepath.Join(root.Path(), target), filepath.Join(root.Path(), path))
|
||||
}
|
||||
}
|
||||
|
||||
// WithTimestamps sets the access and modification times of the file system object
|
||||
// at path.
|
||||
func WithTimestamps(atime, mtime time.Time) PathOp {
|
||||
return func(root Path) error {
|
||||
if _, ok := root.(manifestDirectory); ok {
|
||||
return errors.New("WithTimestamp yet implemented for manifests")
|
||||
}
|
||||
return os.Chtimes(root.Path(), atime, mtime)
|
||||
}
|
||||
}
|
||||
151
vendor/gotest.tools/fs/path.go
vendored
Normal file
151
vendor/gotest.tools/fs/path.go
vendored
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"gotest.tools/assert"
|
||||
)
|
||||
|
||||
// resourcePath is an adaptor for resources so they can be used as a Path
|
||||
// with PathOps.
|
||||
type resourcePath struct{}
|
||||
|
||||
func (p *resourcePath) Path() string {
|
||||
return "manifest: not a filesystem path"
|
||||
}
|
||||
|
||||
func (p *resourcePath) Remove() {}
|
||||
|
||||
type filePath struct {
|
||||
resourcePath
|
||||
file *file
|
||||
}
|
||||
|
||||
func (p *filePath) SetContent(content io.ReadCloser) {
|
||||
p.file.content = content
|
||||
}
|
||||
|
||||
func (p *filePath) SetUID(uid uint32) {
|
||||
p.file.uid = uid
|
||||
}
|
||||
|
||||
func (p *filePath) SetGID(gid uint32) {
|
||||
p.file.gid = gid
|
||||
}
|
||||
|
||||
type directoryPath struct {
|
||||
resourcePath
|
||||
directory *directory
|
||||
}
|
||||
|
||||
func (p *directoryPath) SetUID(uid uint32) {
|
||||
p.directory.uid = uid
|
||||
}
|
||||
|
||||
func (p *directoryPath) SetGID(gid uint32) {
|
||||
p.directory.gid = gid
|
||||
}
|
||||
|
||||
func (p *directoryPath) AddSymlink(path, target string) error {
|
||||
p.directory.items[path] = &symlink{
|
||||
resource: newResource(defaultSymlinkMode),
|
||||
target: target,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *directoryPath) AddFile(path string, ops ...PathOp) error {
|
||||
newFile := &file{resource: newResource(0)}
|
||||
p.directory.items[path] = newFile
|
||||
exp := &filePath{file: newFile}
|
||||
return applyPathOps(exp, ops)
|
||||
}
|
||||
|
||||
func (p *directoryPath) AddDirectory(path string, ops ...PathOp) error {
|
||||
newDir := newDirectoryWithDefaults()
|
||||
p.directory.items[path] = newDir
|
||||
exp := &directoryPath{directory: newDir}
|
||||
return applyPathOps(exp, ops)
|
||||
}
|
||||
|
||||
// Expected returns a Manifest with a directory structured created by ops. The
|
||||
// PathOp operations are applied to the manifest as expectations of the
|
||||
// filesystem structure and properties.
|
||||
func Expected(t assert.TestingT, ops ...PathOp) Manifest {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
|
||||
newDir := newDirectoryWithDefaults()
|
||||
e := &directoryPath{directory: newDir}
|
||||
assert.NilError(t, applyPathOps(e, ops))
|
||||
return Manifest{root: newDir}
|
||||
}
|
||||
|
||||
func newDirectoryWithDefaults() *directory {
|
||||
return &directory{
|
||||
resource: newResource(defaultRootDirMode),
|
||||
items: make(map[string]dirEntry),
|
||||
}
|
||||
}
|
||||
|
||||
func newResource(mode os.FileMode) resource {
|
||||
return resource{
|
||||
mode: mode,
|
||||
uid: currentUID(),
|
||||
gid: currentGID(),
|
||||
}
|
||||
}
|
||||
|
||||
func currentUID() uint32 {
|
||||
return normalizeID(os.Getuid())
|
||||
}
|
||||
|
||||
func currentGID() uint32 {
|
||||
return normalizeID(os.Getgid())
|
||||
}
|
||||
|
||||
func normalizeID(id int) uint32 {
|
||||
// ids will be -1 on windows
|
||||
if id < 0 {
|
||||
return 0
|
||||
}
|
||||
return uint32(id)
|
||||
}
|
||||
|
||||
var anyFileContent = ioutil.NopCloser(bytes.NewReader(nil))
|
||||
|
||||
// MatchAnyFileContent is a PathOp that updates a Manifest so that the file
|
||||
// at path may contain any content.
|
||||
func MatchAnyFileContent(path Path) error {
|
||||
if m, ok := path.(*filePath); ok {
|
||||
m.SetContent(anyFileContent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const anyFile = "*"
|
||||
|
||||
// MatchExtraFiles is a PathOp that updates a Manifest to allow a directory
|
||||
// to contain unspecified files.
|
||||
func MatchExtraFiles(path Path) error {
|
||||
if m, ok := path.(*directoryPath); ok {
|
||||
m.AddFile(anyFile)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// anyFileMode is represented by uint32_max
|
||||
const anyFileMode os.FileMode = 4294967295
|
||||
|
||||
// MatchAnyFileMode is a PathOp that updates a Manifest so that the resource at path
|
||||
// will match any file mode.
|
||||
func MatchAnyFileMode(path Path) error {
|
||||
if m, ok := path.(manifestResource); ok {
|
||||
m.SetMode(anyFileMode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
215
vendor/gotest.tools/fs/report.go
vendored
Normal file
215
vendor/gotest.tools/fs/report.go
vendored
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gotest.tools/assert/cmp"
|
||||
"gotest.tools/internal/format"
|
||||
)
|
||||
|
||||
// Equal compares a directory to the expected structured described by a manifest
|
||||
// and returns success if they match. If they do not match the failure message
|
||||
// will contain all the differences between the directory structure and the
|
||||
// expected structure defined by the Manifest.
|
||||
//
|
||||
// Equal is a cmp.Comparison which can be used with assert.Assert().
|
||||
func Equal(path string, expected Manifest) cmp.Comparison {
|
||||
return func() cmp.Result {
|
||||
actual, err := manifestFromDir(path)
|
||||
if err != nil {
|
||||
return cmp.ResultFromError(err)
|
||||
}
|
||||
failures := eqDirectory(string(os.PathSeparator), expected.root, actual.root)
|
||||
if len(failures) == 0 {
|
||||
return cmp.ResultSuccess
|
||||
}
|
||||
msg := fmt.Sprintf("directory %s does not match expected:\n", path)
|
||||
return cmp.ResultFailure(msg + formatFailures(failures))
|
||||
}
|
||||
}
|
||||
|
||||
type failure struct {
|
||||
path string
|
||||
problems []problem
|
||||
}
|
||||
|
||||
type problem string
|
||||
|
||||
func notEqual(property string, x, y interface{}) problem {
|
||||
return problem(fmt.Sprintf("%s: expected %s got %s", property, x, y))
|
||||
}
|
||||
|
||||
func errProblem(reason string, err error) problem {
|
||||
return problem(fmt.Sprintf("%s: %s", reason, err))
|
||||
}
|
||||
|
||||
func existenceProblem(filename, reason string, args ...interface{}) problem {
|
||||
return problem(filename + ": " + fmt.Sprintf(reason, args...))
|
||||
}
|
||||
|
||||
func eqResource(x, y resource) []problem {
|
||||
var p []problem
|
||||
if x.uid != y.uid {
|
||||
p = append(p, notEqual("uid", x.uid, y.uid))
|
||||
}
|
||||
if x.gid != y.gid {
|
||||
p = append(p, notEqual("gid", x.gid, y.gid))
|
||||
}
|
||||
if x.mode != anyFileMode && x.mode != y.mode {
|
||||
p = append(p, notEqual("mode", x.mode, y.mode))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func eqFile(x, y *file) []problem {
|
||||
p := eqResource(x.resource, y.resource)
|
||||
|
||||
switch {
|
||||
case x.content == nil:
|
||||
p = append(p, existenceProblem("content", "expected content is nil"))
|
||||
return p
|
||||
case x.content == anyFileContent:
|
||||
return p
|
||||
case y.content == nil:
|
||||
p = append(p, existenceProblem("content", "actual content is nil"))
|
||||
return p
|
||||
}
|
||||
|
||||
xContent, xErr := ioutil.ReadAll(x.content)
|
||||
defer x.content.Close()
|
||||
yContent, yErr := ioutil.ReadAll(y.content)
|
||||
defer y.content.Close()
|
||||
|
||||
if xErr != nil {
|
||||
p = append(p, errProblem("failed to read expected content", xErr))
|
||||
}
|
||||
if yErr != nil {
|
||||
p = append(p, errProblem("failed to read actual content", xErr))
|
||||
}
|
||||
if xErr != nil || yErr != nil {
|
||||
return p
|
||||
}
|
||||
|
||||
if !bytes.Equal(xContent, yContent) {
|
||||
p = append(p, diffContent(xContent, yContent))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func diffContent(x, y []byte) problem {
|
||||
diff := format.UnifiedDiff(format.DiffConfig{
|
||||
A: string(x),
|
||||
B: string(y),
|
||||
From: "expected",
|
||||
To: "actual",
|
||||
})
|
||||
// Remove the trailing newline in the diff. A trailing newline is always
|
||||
// added to a problem by formatFailures.
|
||||
diff = strings.TrimSuffix(diff, "\n")
|
||||
return problem("content:\n" + indent(diff, " "))
|
||||
}
|
||||
|
||||
func indent(s, prefix string) string {
|
||||
buf := new(bytes.Buffer)
|
||||
lines := strings.SplitAfter(s, "\n")
|
||||
for _, line := range lines {
|
||||
buf.WriteString(prefix + line)
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func eqSymlink(x, y *symlink) []problem {
|
||||
p := eqResource(x.resource, y.resource)
|
||||
if x.target != y.target {
|
||||
p = append(p, notEqual("target", x.target, y.target))
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func eqDirectory(path string, x, y *directory) []failure {
|
||||
p := eqResource(x.resource, y.resource)
|
||||
var f []failure
|
||||
|
||||
for _, name := range sortedKeys(x.items) {
|
||||
if name == anyFile {
|
||||
continue
|
||||
}
|
||||
xEntry := x.items[name]
|
||||
yEntry, ok := y.items[name]
|
||||
if !ok {
|
||||
p = append(p, existenceProblem(name, "expected %s to exist", xEntry.Type()))
|
||||
continue
|
||||
}
|
||||
|
||||
if xEntry.Type() != yEntry.Type() {
|
||||
p = append(p, notEqual(name, xEntry.Type(), yEntry.Type()))
|
||||
continue
|
||||
}
|
||||
|
||||
f = append(f, eqEntry(filepath.Join(path, name), xEntry, yEntry)...)
|
||||
}
|
||||
|
||||
if _, ok := x.items[anyFile]; !ok {
|
||||
for _, name := range sortedKeys(y.items) {
|
||||
if _, ok := x.items[name]; !ok {
|
||||
yEntry := y.items[name]
|
||||
p = append(p, existenceProblem(name, "unexpected %s", yEntry.Type()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(p) > 0 {
|
||||
f = append(f, failure{path: path, problems: p})
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func sortedKeys(items map[string]dirEntry) []string {
|
||||
var keys []string
|
||||
for key := range items {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
|
||||
// eqEntry assumes x and y to be the same type
|
||||
func eqEntry(path string, x, y dirEntry) []failure {
|
||||
resp := func(problems []problem) []failure {
|
||||
if len(problems) == 0 {
|
||||
return nil
|
||||
}
|
||||
return []failure{{path: path, problems: problems}}
|
||||
}
|
||||
|
||||
switch typed := x.(type) {
|
||||
case *file:
|
||||
return resp(eqFile(typed, y.(*file)))
|
||||
case *symlink:
|
||||
return resp(eqSymlink(typed, y.(*symlink)))
|
||||
case *directory:
|
||||
return eqDirectory(path, typed, y.(*directory))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func formatFailures(failures []failure) string {
|
||||
sort.Slice(failures, func(i, j int) bool {
|
||||
return failures[i].path < failures[j].path
|
||||
})
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
for _, failure := range failures {
|
||||
buf.WriteString(failure.path + "\n")
|
||||
for _, problem := range failure.problems {
|
||||
buf.WriteString(" " + string(problem) + "\n")
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
284
vendor/gotest.tools/icmd/command.go
vendored
Normal file
284
vendor/gotest.tools/icmd/command.go
vendored
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
/*Package icmd executes binaries and provides convenient assertions for testing the results.
|
||||
*/
|
||||
package icmd // import "gotest.tools/icmd"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gotest.tools/assert"
|
||||
"gotest.tools/assert/cmp"
|
||||
)
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
// None is a token to inform Result.Assert that the output should be empty
|
||||
const None = "[NOTHING]"
|
||||
|
||||
type lockedBuffer struct {
|
||||
m sync.RWMutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (buf *lockedBuffer) Write(b []byte) (int, error) {
|
||||
buf.m.Lock()
|
||||
defer buf.m.Unlock()
|
||||
return buf.buf.Write(b)
|
||||
}
|
||||
|
||||
func (buf *lockedBuffer) String() string {
|
||||
buf.m.RLock()
|
||||
defer buf.m.RUnlock()
|
||||
return buf.buf.String()
|
||||
}
|
||||
|
||||
// Result stores the result of running a command
|
||||
type Result struct {
|
||||
Cmd *exec.Cmd
|
||||
ExitCode int
|
||||
Error error
|
||||
// Timeout is true if the command was killed because it ran for too long
|
||||
Timeout bool
|
||||
outBuffer *lockedBuffer
|
||||
errBuffer *lockedBuffer
|
||||
}
|
||||
|
||||
// Assert compares the Result against the Expected struct, and fails the test if
|
||||
// any of the expectations are not met.
|
||||
//
|
||||
// This function is equivalent to assert.Assert(t, result.Equal(exp)).
|
||||
func (r *Result) Assert(t assert.TestingT, exp Expected) *Result {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
assert.Assert(t, r.Equal(exp))
|
||||
return r
|
||||
}
|
||||
|
||||
// Equal compares the result to Expected. If the result doesn't match expected
|
||||
// returns a formatted failure message with the command, stdout, stderr, exit code,
|
||||
// and any failed expectations.
|
||||
func (r *Result) Equal(exp Expected) cmp.Comparison {
|
||||
return func() cmp.Result {
|
||||
return cmp.ResultFromError(r.match(exp))
|
||||
}
|
||||
}
|
||||
|
||||
// Compare the result to Expected and return an error if they do not match.
|
||||
func (r *Result) Compare(exp Expected) error {
|
||||
return r.match(exp)
|
||||
}
|
||||
|
||||
// nolint: gocyclo
|
||||
func (r *Result) match(exp Expected) error {
|
||||
errors := []string{}
|
||||
add := func(format string, args ...interface{}) {
|
||||
errors = append(errors, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
if exp.ExitCode != r.ExitCode {
|
||||
add("ExitCode was %d expected %d", r.ExitCode, exp.ExitCode)
|
||||
}
|
||||
if exp.Timeout != r.Timeout {
|
||||
if exp.Timeout {
|
||||
add("Expected command to timeout")
|
||||
} else {
|
||||
add("Expected command to finish, but it hit the timeout")
|
||||
}
|
||||
}
|
||||
if !matchOutput(exp.Out, r.Stdout()) {
|
||||
add("Expected stdout to contain %q", exp.Out)
|
||||
}
|
||||
if !matchOutput(exp.Err, r.Stderr()) {
|
||||
add("Expected stderr to contain %q", exp.Err)
|
||||
}
|
||||
switch {
|
||||
// If a non-zero exit code is expected there is going to be an error.
|
||||
// Don't require an error message as well as an exit code because the
|
||||
// error message is going to be "exit status <code> which is not useful
|
||||
case exp.Error == "" && exp.ExitCode != 0:
|
||||
case exp.Error == "" && r.Error != nil:
|
||||
add("Expected no error")
|
||||
case exp.Error != "" && r.Error == nil:
|
||||
add("Expected error to contain %q, but there was no error", exp.Error)
|
||||
case exp.Error != "" && !strings.Contains(r.Error.Error(), exp.Error):
|
||||
add("Expected error to contain %q", exp.Error)
|
||||
}
|
||||
|
||||
if len(errors) == 0 {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("%s\nFailures:\n%s", r, strings.Join(errors, "\n"))
|
||||
}
|
||||
|
||||
func matchOutput(expected string, actual string) bool {
|
||||
switch expected {
|
||||
case None:
|
||||
return actual == ""
|
||||
default:
|
||||
return strings.Contains(actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Result) String() string {
|
||||
var timeout string
|
||||
if r.Timeout {
|
||||
timeout = " (timeout)"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(`
|
||||
Command: %s
|
||||
ExitCode: %d%s
|
||||
Error: %v
|
||||
Stdout: %v
|
||||
Stderr: %v
|
||||
`,
|
||||
strings.Join(r.Cmd.Args, " "),
|
||||
r.ExitCode,
|
||||
timeout,
|
||||
r.Error,
|
||||
r.Stdout(),
|
||||
r.Stderr())
|
||||
}
|
||||
|
||||
// Expected is the expected output from a Command. This struct is compared to a
|
||||
// Result struct by Result.Assert().
|
||||
type Expected struct {
|
||||
ExitCode int
|
||||
Timeout bool
|
||||
Error string
|
||||
Out string
|
||||
Err string
|
||||
}
|
||||
|
||||
// Success is the default expected result. A Success result is one with a 0
|
||||
// ExitCode.
|
||||
var Success = Expected{}
|
||||
|
||||
// Stdout returns the stdout of the process as a string
|
||||
func (r *Result) Stdout() string {
|
||||
return r.outBuffer.String()
|
||||
}
|
||||
|
||||
// Stderr returns the stderr of the process as a string
|
||||
func (r *Result) Stderr() string {
|
||||
return r.errBuffer.String()
|
||||
}
|
||||
|
||||
// Combined returns the stdout and stderr combined into a single string
|
||||
func (r *Result) Combined() string {
|
||||
return r.outBuffer.String() + r.errBuffer.String()
|
||||
}
|
||||
|
||||
func (r *Result) setExitError(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
r.Error = err
|
||||
r.ExitCode = processExitCode(err)
|
||||
}
|
||||
|
||||
// Cmd contains the arguments and options for a process to run as part of a test
|
||||
// suite.
|
||||
type Cmd struct {
|
||||
Command []string
|
||||
Timeout time.Duration
|
||||
Stdin io.Reader
|
||||
Stdout io.Writer
|
||||
Dir string
|
||||
Env []string
|
||||
}
|
||||
|
||||
// Command create a simple Cmd with the specified command and arguments
|
||||
func Command(command string, args ...string) Cmd {
|
||||
return Cmd{Command: append([]string{command}, args...)}
|
||||
}
|
||||
|
||||
// RunCmd runs a command and returns a Result
|
||||
func RunCmd(cmd Cmd, cmdOperators ...CmdOp) *Result {
|
||||
for _, op := range cmdOperators {
|
||||
op(&cmd)
|
||||
}
|
||||
result := StartCmd(cmd)
|
||||
if result.Error != nil {
|
||||
return result
|
||||
}
|
||||
return WaitOnCmd(cmd.Timeout, result)
|
||||
}
|
||||
|
||||
// RunCommand runs a command with default options, and returns a result
|
||||
func RunCommand(command string, args ...string) *Result {
|
||||
return RunCmd(Command(command, args...))
|
||||
}
|
||||
|
||||
// StartCmd starts a command, but doesn't wait for it to finish
|
||||
func StartCmd(cmd Cmd) *Result {
|
||||
result := buildCmd(cmd)
|
||||
if result.Error != nil {
|
||||
return result
|
||||
}
|
||||
result.setExitError(result.Cmd.Start())
|
||||
return result
|
||||
}
|
||||
|
||||
// TODO: support exec.CommandContext
|
||||
func buildCmd(cmd Cmd) *Result {
|
||||
var execCmd *exec.Cmd
|
||||
switch len(cmd.Command) {
|
||||
case 1:
|
||||
execCmd = exec.Command(cmd.Command[0])
|
||||
default:
|
||||
execCmd = exec.Command(cmd.Command[0], cmd.Command[1:]...)
|
||||
}
|
||||
outBuffer := new(lockedBuffer)
|
||||
errBuffer := new(lockedBuffer)
|
||||
|
||||
execCmd.Stdin = cmd.Stdin
|
||||
execCmd.Dir = cmd.Dir
|
||||
execCmd.Env = cmd.Env
|
||||
if cmd.Stdout != nil {
|
||||
execCmd.Stdout = io.MultiWriter(outBuffer, cmd.Stdout)
|
||||
} else {
|
||||
execCmd.Stdout = outBuffer
|
||||
}
|
||||
execCmd.Stderr = errBuffer
|
||||
return &Result{
|
||||
Cmd: execCmd,
|
||||
outBuffer: outBuffer,
|
||||
errBuffer: errBuffer,
|
||||
}
|
||||
}
|
||||
|
||||
// WaitOnCmd waits for a command to complete. If timeout is non-nil then
|
||||
// only wait until the timeout.
|
||||
func WaitOnCmd(timeout time.Duration, result *Result) *Result {
|
||||
if timeout == time.Duration(0) {
|
||||
result.setExitError(result.Cmd.Wait())
|
||||
return result
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
// Wait for command to exit in a goroutine
|
||||
go func() {
|
||||
done <- result.Cmd.Wait()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-time.After(timeout):
|
||||
killErr := result.Cmd.Process.Kill()
|
||||
if killErr != nil {
|
||||
fmt.Printf("failed to kill (pid=%d): %v\n", result.Cmd.Process.Pid, killErr)
|
||||
}
|
||||
result.Timeout = true
|
||||
case err := <-done:
|
||||
result.setExitError(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
32
vendor/gotest.tools/icmd/exitcode.go
vendored
Normal file
32
vendor/gotest.tools/icmd/exitcode.go
vendored
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
package icmd
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// getExitCode returns the ExitStatus of a process from the error returned by
|
||||
// exec.Run(). If the exit status could not be parsed an error is returned.
|
||||
func getExitCode(err error) (int, error) {
|
||||
if exiterr, ok := err.(*exec.ExitError); ok {
|
||||
if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok {
|
||||
return procExit.ExitStatus(), nil
|
||||
}
|
||||
}
|
||||
return 0, errors.Wrap(err, "failed to get exit code")
|
||||
}
|
||||
|
||||
func processExitCode(err error) (exitCode int) {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
exitCode, exiterr := getExitCode(err)
|
||||
if exiterr != nil {
|
||||
// TODO: Fix this so we check the error's text.
|
||||
// we've failed to retrieve exit code, so we set it to 127
|
||||
return 127
|
||||
}
|
||||
return exitCode
|
||||
}
|
||||
4
vendor/gotest.tools/icmd/ops.go
vendored
Normal file
4
vendor/gotest.tools/icmd/ops.go
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
package icmd
|
||||
|
||||
// CmdOp is an operation which modified a Cmd structure used to execute commands
|
||||
type CmdOp func(*Cmd)
|
||||
27
vendor/gotest.tools/internal/difflib/LICENSE
vendored
Normal file
27
vendor/gotest.tools/internal/difflib/LICENSE
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
Copyright (c) 2013, Patrick Mezard
|
||||
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.
|
||||
The names of its contributors may not 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
|
||||
HOLDER 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.
|
||||
420
vendor/gotest.tools/internal/difflib/difflib.go
vendored
Normal file
420
vendor/gotest.tools/internal/difflib/difflib.go
vendored
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
/* Package difflib is a partial port of Python difflib module.
|
||||
|
||||
Original source: https://github.com/pmezard/go-difflib
|
||||
|
||||
This file is trimmed to only the parts used by this repository.
|
||||
*/
|
||||
package difflib // import "gotest.tools/internal/difflib"
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
type Match struct {
|
||||
A int
|
||||
B int
|
||||
Size int
|
||||
}
|
||||
|
||||
type OpCode struct {
|
||||
Tag byte
|
||||
I1 int
|
||||
I2 int
|
||||
J1 int
|
||||
J2 int
|
||||
}
|
||||
|
||||
// SequenceMatcher compares sequence of strings. The basic
|
||||
// algorithm predates, and is a little fancier than, an algorithm
|
||||
// published in the late 1980's by Ratcliff and Obershelp under the
|
||||
// hyperbolic name "gestalt pattern matching". The basic idea is to find
|
||||
// the longest contiguous matching subsequence that contains no "junk"
|
||||
// elements (R-O doesn't address junk). The same idea is then applied
|
||||
// recursively to the pieces of the sequences to the left and to the right
|
||||
// of the matching subsequence. This does not yield minimal edit
|
||||
// sequences, but does tend to yield matches that "look right" to people.
|
||||
//
|
||||
// SequenceMatcher tries to compute a "human-friendly diff" between two
|
||||
// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
|
||||
// longest *contiguous* & junk-free matching subsequence. That's what
|
||||
// catches peoples' eyes. The Windows(tm) windiff has another interesting
|
||||
// notion, pairing up elements that appear uniquely in each sequence.
|
||||
// That, and the method here, appear to yield more intuitive difference
|
||||
// reports than does diff. This method appears to be the least vulnerable
|
||||
// to synching up on blocks of "junk lines", though (like blank lines in
|
||||
// ordinary text files, or maybe "<P>" lines in HTML files). That may be
|
||||
// because this is the only method of the 3 that has a *concept* of
|
||||
// "junk" <wink>.
|
||||
//
|
||||
// Timing: Basic R-O is cubic time worst case and quadratic time expected
|
||||
// case. SequenceMatcher is quadratic time for the worst case and has
|
||||
// expected-case behavior dependent in a complicated way on how many
|
||||
// elements the sequences have in common; best case time is linear.
|
||||
type SequenceMatcher struct {
|
||||
a []string
|
||||
b []string
|
||||
b2j map[string][]int
|
||||
IsJunk func(string) bool
|
||||
autoJunk bool
|
||||
bJunk map[string]struct{}
|
||||
matchingBlocks []Match
|
||||
fullBCount map[string]int
|
||||
bPopular map[string]struct{}
|
||||
opCodes []OpCode
|
||||
}
|
||||
|
||||
func NewMatcher(a, b []string) *SequenceMatcher {
|
||||
m := SequenceMatcher{autoJunk: true}
|
||||
m.SetSeqs(a, b)
|
||||
return &m
|
||||
}
|
||||
|
||||
// Set two sequences to be compared.
|
||||
func (m *SequenceMatcher) SetSeqs(a, b []string) {
|
||||
m.SetSeq1(a)
|
||||
m.SetSeq2(b)
|
||||
}
|
||||
|
||||
// Set the first sequence to be compared. The second sequence to be compared is
|
||||
// not changed.
|
||||
//
|
||||
// SequenceMatcher computes and caches detailed information about the second
|
||||
// sequence, so if you want to compare one sequence S against many sequences,
|
||||
// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
|
||||
// sequences.
|
||||
//
|
||||
// See also SetSeqs() and SetSeq2().
|
||||
func (m *SequenceMatcher) SetSeq1(a []string) {
|
||||
if &a == &m.a {
|
||||
return
|
||||
}
|
||||
m.a = a
|
||||
m.matchingBlocks = nil
|
||||
m.opCodes = nil
|
||||
}
|
||||
|
||||
// Set the second sequence to be compared. The first sequence to be compared is
|
||||
// not changed.
|
||||
func (m *SequenceMatcher) SetSeq2(b []string) {
|
||||
if &b == &m.b {
|
||||
return
|
||||
}
|
||||
m.b = b
|
||||
m.matchingBlocks = nil
|
||||
m.opCodes = nil
|
||||
m.fullBCount = nil
|
||||
m.chainB()
|
||||
}
|
||||
|
||||
func (m *SequenceMatcher) chainB() {
|
||||
// Populate line -> index mapping
|
||||
b2j := map[string][]int{}
|
||||
for i, s := range m.b {
|
||||
indices := b2j[s]
|
||||
indices = append(indices, i)
|
||||
b2j[s] = indices
|
||||
}
|
||||
|
||||
// Purge junk elements
|
||||
m.bJunk = map[string]struct{}{}
|
||||
if m.IsJunk != nil {
|
||||
junk := m.bJunk
|
||||
for s, _ := range b2j {
|
||||
if m.IsJunk(s) {
|
||||
junk[s] = struct{}{}
|
||||
}
|
||||
}
|
||||
for s, _ := range junk {
|
||||
delete(b2j, s)
|
||||
}
|
||||
}
|
||||
|
||||
// Purge remaining popular elements
|
||||
popular := map[string]struct{}{}
|
||||
n := len(m.b)
|
||||
if m.autoJunk && n >= 200 {
|
||||
ntest := n/100 + 1
|
||||
for s, indices := range b2j {
|
||||
if len(indices) > ntest {
|
||||
popular[s] = struct{}{}
|
||||
}
|
||||
}
|
||||
for s, _ := range popular {
|
||||
delete(b2j, s)
|
||||
}
|
||||
}
|
||||
m.bPopular = popular
|
||||
m.b2j = b2j
|
||||
}
|
||||
|
||||
func (m *SequenceMatcher) isBJunk(s string) bool {
|
||||
_, ok := m.bJunk[s]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Find longest matching block in a[alo:ahi] and b[blo:bhi].
|
||||
//
|
||||
// If IsJunk is not defined:
|
||||
//
|
||||
// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
|
||||
// alo <= i <= i+k <= ahi
|
||||
// blo <= j <= j+k <= bhi
|
||||
// and for all (i',j',k') meeting those conditions,
|
||||
// k >= k'
|
||||
// i <= i'
|
||||
// and if i == i', j <= j'
|
||||
//
|
||||
// In other words, of all maximal matching blocks, return one that
|
||||
// starts earliest in a, and of all those maximal matching blocks that
|
||||
// start earliest in a, return the one that starts earliest in b.
|
||||
//
|
||||
// If IsJunk is defined, first the longest matching block is
|
||||
// determined as above, but with the additional restriction that no
|
||||
// junk element appears in the block. Then that block is extended as
|
||||
// far as possible by matching (only) junk elements on both sides. So
|
||||
// the resulting block never matches on junk except as identical junk
|
||||
// happens to be adjacent to an "interesting" match.
|
||||
//
|
||||
// If no blocks match, return (alo, blo, 0).
|
||||
func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
|
||||
// CAUTION: stripping common prefix or suffix would be incorrect.
|
||||
// E.g.,
|
||||
// ab
|
||||
// acab
|
||||
// Longest matching block is "ab", but if common prefix is
|
||||
// stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
|
||||
// strip, so ends up claiming that ab is changed to acab by
|
||||
// inserting "ca" in the middle. That's minimal but unintuitive:
|
||||
// "it's obvious" that someone inserted "ac" at the front.
|
||||
// Windiff ends up at the same place as diff, but by pairing up
|
||||
// the unique 'b's and then matching the first two 'a's.
|
||||
besti, bestj, bestsize := alo, blo, 0
|
||||
|
||||
// find longest junk-free match
|
||||
// during an iteration of the loop, j2len[j] = length of longest
|
||||
// junk-free match ending with a[i-1] and b[j]
|
||||
j2len := map[int]int{}
|
||||
for i := alo; i != ahi; i++ {
|
||||
// look at all instances of a[i] in b; note that because
|
||||
// b2j has no junk keys, the loop is skipped if a[i] is junk
|
||||
newj2len := map[int]int{}
|
||||
for _, j := range m.b2j[m.a[i]] {
|
||||
// a[i] matches b[j]
|
||||
if j < blo {
|
||||
continue
|
||||
}
|
||||
if j >= bhi {
|
||||
break
|
||||
}
|
||||
k := j2len[j-1] + 1
|
||||
newj2len[j] = k
|
||||
if k > bestsize {
|
||||
besti, bestj, bestsize = i-k+1, j-k+1, k
|
||||
}
|
||||
}
|
||||
j2len = newj2len
|
||||
}
|
||||
|
||||
// Extend the best by non-junk elements on each end. In particular,
|
||||
// "popular" non-junk elements aren't in b2j, which greatly speeds
|
||||
// the inner loop above, but also means "the best" match so far
|
||||
// doesn't contain any junk *or* popular non-junk elements.
|
||||
for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
|
||||
m.a[besti-1] == m.b[bestj-1] {
|
||||
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
|
||||
}
|
||||
for besti+bestsize < ahi && bestj+bestsize < bhi &&
|
||||
!m.isBJunk(m.b[bestj+bestsize]) &&
|
||||
m.a[besti+bestsize] == m.b[bestj+bestsize] {
|
||||
bestsize += 1
|
||||
}
|
||||
|
||||
// Now that we have a wholly interesting match (albeit possibly
|
||||
// empty!), we may as well suck up the matching junk on each
|
||||
// side of it too. Can't think of a good reason not to, and it
|
||||
// saves post-processing the (possibly considerable) expense of
|
||||
// figuring out what to do with it. In the case of an empty
|
||||
// interesting match, this is clearly the right thing to do,
|
||||
// because no other kind of match is possible in the regions.
|
||||
for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
|
||||
m.a[besti-1] == m.b[bestj-1] {
|
||||
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
|
||||
}
|
||||
for besti+bestsize < ahi && bestj+bestsize < bhi &&
|
||||
m.isBJunk(m.b[bestj+bestsize]) &&
|
||||
m.a[besti+bestsize] == m.b[bestj+bestsize] {
|
||||
bestsize += 1
|
||||
}
|
||||
|
||||
return Match{A: besti, B: bestj, Size: bestsize}
|
||||
}
|
||||
|
||||
// Return list of triples describing matching subsequences.
|
||||
//
|
||||
// Each triple is of the form (i, j, n), and means that
|
||||
// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
|
||||
// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
|
||||
// adjacent triples in the list, and the second is not the last triple in the
|
||||
// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
|
||||
// adjacent equal blocks.
|
||||
//
|
||||
// The last triple is a dummy, (len(a), len(b), 0), and is the only
|
||||
// triple with n==0.
|
||||
func (m *SequenceMatcher) GetMatchingBlocks() []Match {
|
||||
if m.matchingBlocks != nil {
|
||||
return m.matchingBlocks
|
||||
}
|
||||
|
||||
var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
|
||||
matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
|
||||
match := m.findLongestMatch(alo, ahi, blo, bhi)
|
||||
i, j, k := match.A, match.B, match.Size
|
||||
if match.Size > 0 {
|
||||
if alo < i && blo < j {
|
||||
matched = matchBlocks(alo, i, blo, j, matched)
|
||||
}
|
||||
matched = append(matched, match)
|
||||
if i+k < ahi && j+k < bhi {
|
||||
matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
|
||||
}
|
||||
}
|
||||
return matched
|
||||
}
|
||||
matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
|
||||
|
||||
// It's possible that we have adjacent equal blocks in the
|
||||
// matching_blocks list now.
|
||||
nonAdjacent := []Match{}
|
||||
i1, j1, k1 := 0, 0, 0
|
||||
for _, b := range matched {
|
||||
// Is this block adjacent to i1, j1, k1?
|
||||
i2, j2, k2 := b.A, b.B, b.Size
|
||||
if i1+k1 == i2 && j1+k1 == j2 {
|
||||
// Yes, so collapse them -- this just increases the length of
|
||||
// the first block by the length of the second, and the first
|
||||
// block so lengthened remains the block to compare against.
|
||||
k1 += k2
|
||||
} else {
|
||||
// Not adjacent. Remember the first block (k1==0 means it's
|
||||
// the dummy we started with), and make the second block the
|
||||
// new block to compare against.
|
||||
if k1 > 0 {
|
||||
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
|
||||
}
|
||||
i1, j1, k1 = i2, j2, k2
|
||||
}
|
||||
}
|
||||
if k1 > 0 {
|
||||
nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
|
||||
}
|
||||
|
||||
nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
|
||||
m.matchingBlocks = nonAdjacent
|
||||
return m.matchingBlocks
|
||||
}
|
||||
|
||||
// Return list of 5-tuples describing how to turn a into b.
|
||||
//
|
||||
// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
|
||||
// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
|
||||
// tuple preceding it, and likewise for j1 == the previous j2.
|
||||
//
|
||||
// The tags are characters, with these meanings:
|
||||
//
|
||||
// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
|
||||
//
|
||||
// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
|
||||
//
|
||||
// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
|
||||
//
|
||||
// 'e' (equal): a[i1:i2] == b[j1:j2]
|
||||
func (m *SequenceMatcher) GetOpCodes() []OpCode {
|
||||
if m.opCodes != nil {
|
||||
return m.opCodes
|
||||
}
|
||||
i, j := 0, 0
|
||||
matching := m.GetMatchingBlocks()
|
||||
opCodes := make([]OpCode, 0, len(matching))
|
||||
for _, m := range matching {
|
||||
// invariant: we've pumped out correct diffs to change
|
||||
// a[:i] into b[:j], and the next matching block is
|
||||
// a[ai:ai+size] == b[bj:bj+size]. So we need to pump
|
||||
// out a diff to change a[i:ai] into b[j:bj], pump out
|
||||
// the matching block, and move (i,j) beyond the match
|
||||
ai, bj, size := m.A, m.B, m.Size
|
||||
tag := byte(0)
|
||||
if i < ai && j < bj {
|
||||
tag = 'r'
|
||||
} else if i < ai {
|
||||
tag = 'd'
|
||||
} else if j < bj {
|
||||
tag = 'i'
|
||||
}
|
||||
if tag > 0 {
|
||||
opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
|
||||
}
|
||||
i, j = ai+size, bj+size
|
||||
// the list of matching blocks is terminated by a
|
||||
// sentinel with size 0
|
||||
if size > 0 {
|
||||
opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
|
||||
}
|
||||
}
|
||||
m.opCodes = opCodes
|
||||
return m.opCodes
|
||||
}
|
||||
|
||||
// Isolate change clusters by eliminating ranges with no changes.
|
||||
//
|
||||
// Return a generator of groups with up to n lines of context.
|
||||
// Each group is in the same format as returned by GetOpCodes().
|
||||
func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
|
||||
if n < 0 {
|
||||
n = 3
|
||||
}
|
||||
codes := m.GetOpCodes()
|
||||
if len(codes) == 0 {
|
||||
codes = []OpCode{OpCode{'e', 0, 1, 0, 1}}
|
||||
}
|
||||
// Fixup leading and trailing groups if they show no changes.
|
||||
if codes[0].Tag == 'e' {
|
||||
c := codes[0]
|
||||
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
|
||||
codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
|
||||
}
|
||||
if codes[len(codes)-1].Tag == 'e' {
|
||||
c := codes[len(codes)-1]
|
||||
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
|
||||
codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
|
||||
}
|
||||
nn := n + n
|
||||
groups := [][]OpCode{}
|
||||
group := []OpCode{}
|
||||
for _, c := range codes {
|
||||
i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
|
||||
// End the current group and start a new one whenever
|
||||
// there is a large range with no changes.
|
||||
if c.Tag == 'e' && i2-i1 > nn {
|
||||
group = append(group, OpCode{c.Tag, i1, min(i2, i1+n),
|
||||
j1, min(j2, j1+n)})
|
||||
groups = append(groups, group)
|
||||
group = []OpCode{}
|
||||
i1, j1 = max(i1, i2-n), max(j1, j2-n)
|
||||
}
|
||||
group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
|
||||
}
|
||||
if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
|
||||
groups = append(groups, group)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
161
vendor/gotest.tools/internal/format/diff.go
vendored
Normal file
161
vendor/gotest.tools/internal/format/diff.go
vendored
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
package format
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"gotest.tools/internal/difflib"
|
||||
)
|
||||
|
||||
const (
|
||||
contextLines = 2
|
||||
)
|
||||
|
||||
// DiffConfig for a unified diff
|
||||
type DiffConfig struct {
|
||||
A string
|
||||
B string
|
||||
From string
|
||||
To string
|
||||
}
|
||||
|
||||
// UnifiedDiff is a modified version of difflib.WriteUnifiedDiff with better
|
||||
// support for showing the whitespace differences.
|
||||
func UnifiedDiff(conf DiffConfig) string {
|
||||
a := strings.SplitAfter(conf.A, "\n")
|
||||
b := strings.SplitAfter(conf.B, "\n")
|
||||
groups := difflib.NewMatcher(a, b).GetGroupedOpCodes(contextLines)
|
||||
if len(groups) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
writeFormat := func(format string, args ...interface{}) {
|
||||
buf.WriteString(fmt.Sprintf(format, args...))
|
||||
}
|
||||
writeLine := func(prefix string, s string) {
|
||||
buf.WriteString(prefix + s)
|
||||
}
|
||||
if hasWhitespaceDiffLines(groups, a, b) {
|
||||
writeLine = visibleWhitespaceLine(writeLine)
|
||||
}
|
||||
formatHeader(writeFormat, conf)
|
||||
for _, group := range groups {
|
||||
formatRangeLine(writeFormat, group)
|
||||
for _, opCode := range group {
|
||||
in, out := a[opCode.I1:opCode.I2], b[opCode.J1:opCode.J2]
|
||||
switch opCode.Tag {
|
||||
case 'e':
|
||||
formatLines(writeLine, " ", in)
|
||||
case 'r':
|
||||
formatLines(writeLine, "-", in)
|
||||
formatLines(writeLine, "+", out)
|
||||
case 'd':
|
||||
formatLines(writeLine, "-", in)
|
||||
case 'i':
|
||||
formatLines(writeLine, "+", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// hasWhitespaceDiffLines returns true if any diff groups is only different
|
||||
// because of whitespace characters.
|
||||
func hasWhitespaceDiffLines(groups [][]difflib.OpCode, a, b []string) bool {
|
||||
for _, group := range groups {
|
||||
in, out := new(bytes.Buffer), new(bytes.Buffer)
|
||||
for _, opCode := range group {
|
||||
if opCode.Tag == 'e' {
|
||||
continue
|
||||
}
|
||||
for _, line := range a[opCode.I1:opCode.I2] {
|
||||
in.WriteString(line)
|
||||
}
|
||||
for _, line := range b[opCode.J1:opCode.J2] {
|
||||
out.WriteString(line)
|
||||
}
|
||||
}
|
||||
if removeWhitespace(in.String()) == removeWhitespace(out.String()) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func removeWhitespace(s string) string {
|
||||
var result []rune
|
||||
for _, r := range s {
|
||||
if !unicode.IsSpace(r) {
|
||||
result = append(result, r)
|
||||
}
|
||||
}
|
||||
return string(result)
|
||||
}
|
||||
|
||||
func visibleWhitespaceLine(ws func(string, string)) func(string, string) {
|
||||
mapToVisibleSpace := func(r rune) rune {
|
||||
switch r {
|
||||
case '\n':
|
||||
case ' ':
|
||||
return '·'
|
||||
case '\t':
|
||||
return '▷'
|
||||
case '\v':
|
||||
return '▽'
|
||||
case '\r':
|
||||
return '↵'
|
||||
case '\f':
|
||||
return '↓'
|
||||
default:
|
||||
if unicode.IsSpace(r) {
|
||||
return '<27>'
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
return func(prefix, s string) {
|
||||
ws(prefix, strings.Map(mapToVisibleSpace, s))
|
||||
}
|
||||
}
|
||||
|
||||
func formatHeader(wf func(string, ...interface{}), conf DiffConfig) {
|
||||
if conf.From != "" || conf.To != "" {
|
||||
wf("--- %s\n", conf.From)
|
||||
wf("+++ %s\n", conf.To)
|
||||
}
|
||||
}
|
||||
|
||||
func formatRangeLine(wf func(string, ...interface{}), group []difflib.OpCode) {
|
||||
first, last := group[0], group[len(group)-1]
|
||||
range1 := formatRangeUnified(first.I1, last.I2)
|
||||
range2 := formatRangeUnified(first.J1, last.J2)
|
||||
wf("@@ -%s +%s @@\n", range1, range2)
|
||||
}
|
||||
|
||||
// Convert range to the "ed" format
|
||||
func formatRangeUnified(start, stop int) string {
|
||||
// Per the diff spec at http://www.unix.org/single_unix_specification/
|
||||
beginning := start + 1 // lines start numbering with one
|
||||
length := stop - start
|
||||
if length == 1 {
|
||||
return fmt.Sprintf("%d", beginning)
|
||||
}
|
||||
if length == 0 {
|
||||
beginning-- // empty ranges begin at line just before the range
|
||||
}
|
||||
return fmt.Sprintf("%d,%d", beginning, length)
|
||||
}
|
||||
|
||||
func formatLines(writeLine func(string, string), prefix string, lines []string) {
|
||||
for _, line := range lines {
|
||||
writeLine(prefix, line)
|
||||
}
|
||||
// Add a newline if the last line is missing one so that the diff displays
|
||||
// properly.
|
||||
if !strings.HasSuffix(lines[len(lines)-1], "\n") {
|
||||
writeLine("", "\n")
|
||||
}
|
||||
}
|
||||
27
vendor/gotest.tools/internal/format/format.go
vendored
Normal file
27
vendor/gotest.tools/internal/format/format.go
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
package format // import "gotest.tools/internal/format"
|
||||
|
||||
import "fmt"
|
||||
|
||||
// Message accepts a msgAndArgs varargs and formats it using fmt.Sprintf
|
||||
func Message(msgAndArgs ...interface{}) string {
|
||||
switch len(msgAndArgs) {
|
||||
case 0:
|
||||
return ""
|
||||
case 1:
|
||||
return fmt.Sprintf("%v", msgAndArgs[0])
|
||||
default:
|
||||
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithCustomMessage accepts one or two messages and formats them appropriately
|
||||
func WithCustomMessage(source string, msgAndArgs ...interface{}) string {
|
||||
custom := Message(msgAndArgs...)
|
||||
switch {
|
||||
case custom == "":
|
||||
return source
|
||||
case source == "":
|
||||
return custom
|
||||
}
|
||||
return fmt.Sprintf("%s: %s", source, custom)
|
||||
}
|
||||
163
vendor/gotest.tools/internal/source/source.go
vendored
Normal file
163
vendor/gotest.tools/internal/source/source.go
vendored
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
package source // import "gotest.tools/internal/source"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/format"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const baseStackIndex = 1
|
||||
|
||||
// FormattedCallExprArg returns the argument from an ast.CallExpr at the
|
||||
// index in the call stack. The argument is formatted using FormatNode.
|
||||
func FormattedCallExprArg(stackIndex int, argPos int) (string, error) {
|
||||
args, err := CallExprArgs(stackIndex + 1)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return FormatNode(args[argPos])
|
||||
}
|
||||
|
||||
func getNodeAtLine(filename string, lineNum int) (ast.Node, error) {
|
||||
fileset := token.NewFileSet()
|
||||
astFile, err := parser.ParseFile(fileset, filename, nil, parser.AllErrors)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "failed to parse source file: %s", filename)
|
||||
}
|
||||
|
||||
node := scanToLine(fileset, astFile, lineNum)
|
||||
if node == nil {
|
||||
return nil, errors.Errorf(
|
||||
"failed to find an expression on line %d in %s", lineNum, filename)
|
||||
}
|
||||
return node, nil
|
||||
}
|
||||
|
||||
func scanToLine(fileset *token.FileSet, node ast.Node, lineNum int) ast.Node {
|
||||
v := &scanToLineVisitor{lineNum: lineNum, fileset: fileset}
|
||||
ast.Walk(v, node)
|
||||
return v.matchedNode
|
||||
}
|
||||
|
||||
type scanToLineVisitor struct {
|
||||
lineNum int
|
||||
matchedNode ast.Node
|
||||
fileset *token.FileSet
|
||||
}
|
||||
|
||||
func (v *scanToLineVisitor) Visit(node ast.Node) ast.Visitor {
|
||||
if node == nil || v.matchedNode != nil {
|
||||
return nil
|
||||
}
|
||||
if v.nodePosition(node).Line == v.lineNum {
|
||||
v.matchedNode = node
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// In golang 1.9 the line number changed from being the line where the statement
|
||||
// ended to the line where the statement began.
|
||||
func (v *scanToLineVisitor) nodePosition(node ast.Node) token.Position {
|
||||
if goVersionBefore19 {
|
||||
return v.fileset.Position(node.End())
|
||||
}
|
||||
return v.fileset.Position(node.Pos())
|
||||
}
|
||||
|
||||
var goVersionBefore19 = isGOVersionBefore19()
|
||||
|
||||
func isGOVersionBefore19() bool {
|
||||
version := runtime.Version()
|
||||
// not a release version
|
||||
if !strings.HasPrefix(version, "go") {
|
||||
return false
|
||||
}
|
||||
version = strings.TrimPrefix(version, "go")
|
||||
parts := strings.Split(version, ".")
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
minor, err := strconv.ParseInt(parts[1], 10, 32)
|
||||
return err == nil && parts[0] == "1" && minor < 9
|
||||
}
|
||||
|
||||
func getCallExprArgs(node ast.Node) ([]ast.Expr, error) {
|
||||
visitor := &callExprVisitor{}
|
||||
ast.Walk(visitor, node)
|
||||
if visitor.expr == nil {
|
||||
return nil, errors.New("failed to find call expression")
|
||||
}
|
||||
return visitor.expr.Args, nil
|
||||
}
|
||||
|
||||
type callExprVisitor struct {
|
||||
expr *ast.CallExpr
|
||||
}
|
||||
|
||||
func (v *callExprVisitor) Visit(node ast.Node) ast.Visitor {
|
||||
if v.expr != nil || node == nil {
|
||||
return nil
|
||||
}
|
||||
debug("visit (%T): %s", node, debugFormatNode{node})
|
||||
|
||||
if callExpr, ok := node.(*ast.CallExpr); ok {
|
||||
v.expr = callExpr
|
||||
return nil
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// FormatNode using go/format.Node and return the result as a string
|
||||
func FormatNode(node ast.Node) (string, error) {
|
||||
buf := new(bytes.Buffer)
|
||||
err := format.Node(buf, token.NewFileSet(), node)
|
||||
return buf.String(), err
|
||||
}
|
||||
|
||||
// CallExprArgs returns the ast.Expr slice for the args of an ast.CallExpr at
|
||||
// the index in the call stack.
|
||||
func CallExprArgs(stackIndex int) ([]ast.Expr, error) {
|
||||
_, filename, lineNum, ok := runtime.Caller(baseStackIndex + stackIndex)
|
||||
if !ok {
|
||||
return nil, errors.New("failed to get call stack")
|
||||
}
|
||||
debug("call stack position: %s:%d", filename, lineNum)
|
||||
|
||||
node, err := getNodeAtLine(filename, lineNum)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
debug("found node (%T): %s", node, debugFormatNode{node})
|
||||
|
||||
return getCallExprArgs(node)
|
||||
}
|
||||
|
||||
var debugEnabled = os.Getenv("GOTESTYOURSELF_DEBUG") != ""
|
||||
|
||||
func debug(format string, args ...interface{}) {
|
||||
if debugEnabled {
|
||||
fmt.Fprintf(os.Stderr, "DEBUG: "+format+"\n", args...)
|
||||
}
|
||||
}
|
||||
|
||||
type debugFormatNode struct {
|
||||
ast.Node
|
||||
}
|
||||
|
||||
func (n debugFormatNode) String() string {
|
||||
out, err := FormatNode(n.Node)
|
||||
if err != nil {
|
||||
return fmt.Sprintf("failed to format %s: %s", n.Node, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
140
vendor/gotest.tools/poll/poll.go
vendored
Normal file
140
vendor/gotest.tools/poll/poll.go
vendored
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
/*Package poll provides tools for testing asynchronous code.
|
||||
*/
|
||||
package poll // import "gotest.tools/poll"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestingT is the subset of testing.T used by WaitOn
|
||||
type TestingT interface {
|
||||
LogT
|
||||
Fatalf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
// LogT is a logging interface that is passed to the WaitOn check function
|
||||
type LogT interface {
|
||||
Log(args ...interface{})
|
||||
Logf(format string, args ...interface{})
|
||||
}
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
// Settings are used to configure the behaviour of WaitOn
|
||||
type Settings struct {
|
||||
// Timeout is the maximum time to wait for the condition. Defaults to 10s.
|
||||
Timeout time.Duration
|
||||
// Delay is the time to sleep between checking the condition. Defaults to
|
||||
// 100ms.
|
||||
Delay time.Duration
|
||||
}
|
||||
|
||||
func defaultConfig() *Settings {
|
||||
return &Settings{Timeout: 10 * time.Second, Delay: 100 * time.Millisecond}
|
||||
}
|
||||
|
||||
// SettingOp is a function which accepts and modifies Settings
|
||||
type SettingOp func(config *Settings)
|
||||
|
||||
// WithDelay sets the delay to wait between polls
|
||||
func WithDelay(delay time.Duration) SettingOp {
|
||||
return func(config *Settings) {
|
||||
config.Delay = delay
|
||||
}
|
||||
}
|
||||
|
||||
// WithTimeout sets the timeout
|
||||
func WithTimeout(timeout time.Duration) SettingOp {
|
||||
return func(config *Settings) {
|
||||
config.Timeout = timeout
|
||||
}
|
||||
}
|
||||
|
||||
// Result of a check performed by WaitOn
|
||||
type Result interface {
|
||||
// Error indicates that the check failed and polling should stop, and the
|
||||
// the has failed
|
||||
Error() error
|
||||
// Done indicates that polling should stop, and the test should proceed
|
||||
Done() bool
|
||||
// Message provides the most recent state when polling has not completed
|
||||
Message() string
|
||||
}
|
||||
|
||||
type result struct {
|
||||
done bool
|
||||
message string
|
||||
err error
|
||||
}
|
||||
|
||||
func (r result) Done() bool {
|
||||
return r.done
|
||||
}
|
||||
|
||||
func (r result) Message() string {
|
||||
return r.message
|
||||
}
|
||||
|
||||
func (r result) Error() error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// Continue returns a Result that indicates to WaitOn that it should continue
|
||||
// polling. The message text will be used as the failure message if the timeout
|
||||
// is reached.
|
||||
func Continue(message string, args ...interface{}) Result {
|
||||
return result{message: fmt.Sprintf(message, args...)}
|
||||
}
|
||||
|
||||
// Success returns a Result where Done() returns true, which indicates to WaitOn
|
||||
// that it should stop polling and exit without an error.
|
||||
func Success() Result {
|
||||
return result{done: true}
|
||||
}
|
||||
|
||||
// Error returns a Result that indicates to WaitOn that it should fail the test
|
||||
// and stop polling.
|
||||
func Error(err error) Result {
|
||||
return result{err: err}
|
||||
}
|
||||
|
||||
// WaitOn a condition or until a timeout. Poll by calling check and exit when
|
||||
// check returns a done Result. To fail a test and exit polling with an error
|
||||
// return a error result.
|
||||
func WaitOn(t TestingT, check func(t LogT) Result, pollOps ...SettingOp) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
config := defaultConfig()
|
||||
for _, pollOp := range pollOps {
|
||||
pollOp(config)
|
||||
}
|
||||
|
||||
var lastMessage string
|
||||
after := time.After(config.Timeout)
|
||||
chResult := make(chan Result)
|
||||
for {
|
||||
go func() {
|
||||
chResult <- check(t)
|
||||
}()
|
||||
select {
|
||||
case <-after:
|
||||
if lastMessage == "" {
|
||||
lastMessage = "first check never completed"
|
||||
}
|
||||
t.Fatalf("timeout hit after %s: %s", config.Timeout, lastMessage)
|
||||
case result := <-chResult:
|
||||
switch {
|
||||
case result.Error() != nil:
|
||||
t.Fatalf("polling check failed: %s", result.Error())
|
||||
case result.Done():
|
||||
return
|
||||
}
|
||||
time.Sleep(config.Delay)
|
||||
lastMessage = result.Message()
|
||||
}
|
||||
}
|
||||
}
|
||||
71
vendor/gotest.tools/skip/skip.go
vendored
Normal file
71
vendor/gotest.tools/skip/skip.go
vendored
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
/*Package skip provides functions for skipping a test and printing the source code
|
||||
of the condition used to skip the test.
|
||||
*/
|
||||
package skip // import "gotest.tools/skip"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"gotest.tools/internal/format"
|
||||
"gotest.tools/internal/source"
|
||||
)
|
||||
|
||||
type skipT interface {
|
||||
Skip(args ...interface{})
|
||||
Log(args ...interface{})
|
||||
}
|
||||
|
||||
type helperT interface {
|
||||
Helper()
|
||||
}
|
||||
|
||||
// BoolOrCheckFunc can be a bool or func() bool, other types will panic
|
||||
type BoolOrCheckFunc interface{}
|
||||
|
||||
// If the condition expression evaluates to true, or the condition function returns
|
||||
// true, skip the test.
|
||||
// The skip message will contain the source code of the expression.
|
||||
// Extra message text can be passed as a format string with args
|
||||
func If(t skipT, condition BoolOrCheckFunc, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
switch check := condition.(type) {
|
||||
case bool:
|
||||
ifCondition(t, check, msgAndArgs...)
|
||||
case func() bool:
|
||||
if check() {
|
||||
t.Skip(format.WithCustomMessage(getFunctionName(check), msgAndArgs...))
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("invalid type for condition arg: %T", check))
|
||||
}
|
||||
}
|
||||
|
||||
func getFunctionName(function func() bool) string {
|
||||
funcPath := runtime.FuncForPC(reflect.ValueOf(function).Pointer()).Name()
|
||||
return strings.SplitN(path.Base(funcPath), ".", 2)[1]
|
||||
}
|
||||
|
||||
func ifCondition(t skipT, condition bool, msgAndArgs ...interface{}) {
|
||||
if ht, ok := t.(helperT); ok {
|
||||
ht.Helper()
|
||||
}
|
||||
if !condition {
|
||||
return
|
||||
}
|
||||
const (
|
||||
stackIndex = 2
|
||||
argPos = 1
|
||||
)
|
||||
source, err := source.FormattedCallExprArg(stackIndex, argPos)
|
||||
if err != nil {
|
||||
t.Log(err.Error())
|
||||
t.Skip(format.Message(msgAndArgs...))
|
||||
}
|
||||
t.Skip(format.WithCustomMessage(source, msgAndArgs...))
|
||||
}
|
||||
81
vendor/gotest.tools/x/subtest/context.go
vendored
Normal file
81
vendor/gotest.tools/x/subtest/context.go
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/*Package subtest provides a TestContext to subtests which handles cleanup, and
|
||||
provides a testing.TB, and context.Context.
|
||||
|
||||
This package was inspired by github.com/frankban/quicktest.
|
||||
*/
|
||||
package subtest // import "gotest.tools/x/subtest"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type testcase struct {
|
||||
testing.TB
|
||||
ctx context.Context
|
||||
cleanupFuncs []cleanupFunc
|
||||
}
|
||||
|
||||
type cleanupFunc func()
|
||||
|
||||
func (tc *testcase) Ctx() context.Context {
|
||||
if tc.ctx == nil {
|
||||
var cancel func()
|
||||
tc.ctx, cancel = context.WithCancel(context.Background())
|
||||
tc.AddCleanup(cancel)
|
||||
}
|
||||
return tc.ctx
|
||||
}
|
||||
|
||||
// Cleanup runs all cleanup functions. Functions are run in the opposite order
|
||||
// in which they were added. Cleanup is called automatically before Run exits.
|
||||
func (tc *testcase) Cleanup() {
|
||||
for _, f := range tc.cleanupFuncs {
|
||||
// Defer all cleanup functions so they all run even if one calls
|
||||
// t.FailNow() or panics. Deferring them also runs them in reverse order.
|
||||
defer f()
|
||||
}
|
||||
tc.cleanupFuncs = nil
|
||||
}
|
||||
|
||||
func (tc *testcase) AddCleanup(f func()) {
|
||||
tc.cleanupFuncs = append(tc.cleanupFuncs, f)
|
||||
}
|
||||
|
||||
func (tc *testcase) Parallel() {
|
||||
tp, ok := tc.TB.(parallel)
|
||||
if !ok {
|
||||
panic("Parallel called with a testing.B")
|
||||
}
|
||||
tp.Parallel()
|
||||
}
|
||||
|
||||
type parallel interface {
|
||||
Parallel()
|
||||
}
|
||||
|
||||
// Run a subtest. When subtest exits, every cleanup function added with
|
||||
// TestContext.AddCleanup will be run.
|
||||
func Run(t *testing.T, name string, subtest func(t TestContext)) bool {
|
||||
return t.Run(name, func(t *testing.T) {
|
||||
tc := &testcase{TB: t}
|
||||
defer tc.Cleanup()
|
||||
subtest(tc)
|
||||
})
|
||||
}
|
||||
|
||||
// TestContext provides a testing.TB and a context.Context for a test case.
|
||||
type TestContext interface {
|
||||
testing.TB
|
||||
// AddCleanup function which will be run when before Run returns.
|
||||
AddCleanup(f func())
|
||||
// Ctx returns a context for the test case. Multiple calls from the same subtest
|
||||
// will return the same context. The context is cancelled when Run
|
||||
// returns.
|
||||
Ctx() context.Context
|
||||
// Parallel calls t.Parallel on the testing.TB. Panics if testing.TB does
|
||||
// not implement Parallel.
|
||||
Parallel()
|
||||
}
|
||||
|
||||
var _ TestContext = &testcase{}
|
||||
Loading…
Add table
Add a link
Reference in a new issue