[tests] Unzip contents of test module
To comply with licensing requirements, check in the unzipped contents of
the `ut` package instead of a zip file.
We can't use the normal Go vendoring process because it strips out
`_test.go` files and .git files, which are included in the go.sum hash
calculation and thus need to be available for the test.
Bug: 131750
Change-Id: I11333ff9bbb2a86fa53ef93da3f199a15c0307d2
Reviewed-on: https://fuchsia-review.googlesource.com/c/shac-project/shac/+/898278
Reviewed-by: Marc-Antoine Ruel <maruel@google.com>
Commit-Queue: Oliver Newman <olivernewman@google.com>
Fuchsia-Auto-Submit: Oliver Newman <olivernewman@google.com>
diff --git a/internal/engine/pkg_test.go b/internal/engine/pkg_test.go
index 08deeca..ae91fa2 100644
--- a/internal/engine/pkg_test.go
+++ b/internal/engine/pkg_test.go
@@ -15,14 +15,11 @@
package engine
import (
- "archive/zip"
"context"
"errors"
"fmt"
- "io"
"io/fs"
"os"
- "path"
"path/filepath"
"runtime"
"sort"
@@ -36,16 +33,33 @@
func TestFSToDigest_Reproducible(t *testing.T) {
t.Parallel()
- // Reuse a simple Go project that is in Go Proxy (https://proxy.golang.org/).
- // This ensures the algorithm matches the expected value.
- // Intentionally unzip to disk so we don't use funky in-memory file system
- // for unit test, only to have it fail in practice.
- root := t.TempDir()
+
+ // Reuse a simple Go project that is in Go Proxy
+ // (https://proxy.golang.org/). This ensures the algorithm matches the
+ // expected value.
+ //
// Created with:
// git clone https://github.com/maruel/ut -b v1.0.0
// cd ut
- // zip ut_v1.0.0.zip *.go LICENSE README.md .travis.yml .git/config
- unzip(t, root, filepath.Join("testdata", "ut_v1.0.0.zip"))
+ // cp *.go LICENSE README.md .travis.yml .git/config ../internal/engine/testdata/ut
+ //
+ // Ideally we could use a module already included the vendor directory, but
+ // Go's vendoring process strips out test files and .git files even though
+ // they are taken into account by the mod hash computation. We need to take
+ // an alternate approach that doesn't strip out those files, so bypass the
+ // normal vendoring process.
+ srcDir := filepath.Join("testdata", "ut")
+
+ root := t.TempDir()
+
+ copyTree(t, root, srcDir, map[string]string{
+ // Git doesn't allow committing the .git directory, but .git/config
+ // needs to be considered in the hash computation, so we commit it to
+ // `config` instead of `.git/config` and then copy it into the right
+ // place.
+ "config": ".git/config",
+ })
+
const prefix = "github.com/maruel/ut@v1.0.0"
// Retrieved from an empty directory:
// go mod init main
@@ -72,6 +86,33 @@
}
}
+func copyTree(t *testing.T, dstDir, srcDir string, renamings map[string]string) {
+ err := filepath.WalkDir(srcDir, func(path string, d fs.DirEntry, err error) error {
+ if d.IsDir() || err != nil {
+ return err
+ }
+ rel, err := filepath.Rel(srcDir, path)
+ if err != nil {
+ return err
+ }
+ if newName, ok := renamings[rel]; ok {
+ rel = newName
+ }
+ dest := filepath.Join(dstDir, rel)
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil {
+ return err
+ }
+ return os.WriteFile(dest, b, 0o600)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
func TestFSToDigest_Fail(t *testing.T) {
t.Parallel()
root := t.TempDir()
@@ -196,34 +237,3 @@
t.Fatalf("mismatch (-want +got):\n%s", diff)
}
}
-
-func unzip(t *testing.T, dst, in string) {
- r, err := zip.OpenReader(in)
- if err != nil {
- t.Fatal(err)
- }
- for _, f := range r.File {
- rc, err := f.Open()
- if err != nil {
- t.Fatal(err)
- }
- data, err := io.ReadAll(rc)
- if err != nil {
- t.Error(err)
- }
- if err = rc.Close(); err != nil {
- t.Fatal(err)
- }
- if strings.Contains(f.Name, "/") {
- if err = os.MkdirAll(filepath.Join(dst, path.Dir(f.Name)), 0o700); err != nil {
- t.Fatal(err)
- }
- }
- if err = os.WriteFile(filepath.Join(dst, f.Name), data, f.Mode()); err != nil {
- t.Fatal(err)
- }
- }
- if err := r.Close(); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/internal/engine/testdata/ut/.travis.yml b/internal/engine/testdata/ut/.travis.yml
new file mode 100644
index 0000000..b130aaa
--- /dev/null
+++ b/internal/engine/testdata/ut/.travis.yml
@@ -0,0 +1,16 @@
+# Copyright 2014 Marc-Antoine Ruel. All rights reserved.
+# Use of this source code is governed under the Apache License, Version 2.0
+# that can be found in the LICENSE file.
+
+sudo: false
+language: go
+
+go:
+- 1.2
+- 1.4.2
+
+before_install:
+ - go get github.com/maruel/pre-commit-go/cmd/pcg
+
+script:
+ - pcg
diff --git a/internal/engine/testdata/ut/LICENSE b/internal/engine/testdata/ut/LICENSE
new file mode 100644
index 0000000..c2341a9
--- /dev/null
+++ b/internal/engine/testdata/ut/LICENSE
@@ -0,0 +1,201 @@
+ 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 2014 Marc-Antoine Ruel
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/internal/engine/testdata/ut/README.md b/internal/engine/testdata/ut/README.md
new file mode 100644
index 0000000..c1bad0c
--- /dev/null
+++ b/internal/engine/testdata/ut/README.md
@@ -0,0 +1,52 @@
+ut (utiltest)
+=============
+
+Collection of small functions to shorten Go test cases.
+
+Requires Go 1.2 due to the use of `testing.TB`. If needed, replace with
+`*testing.T` at the cost of not being usable in benchmarks.
+
+[![GoDoc](https://godoc.org/github.com/maruel/ut?status.svg)](https://godoc.org/github.com/maruel/ut)
+[![Build Status](https://travis-ci.org/maruel/ut.svg?branch=master)](https://travis-ci.org/maruel/ut)
+[![Coverage Status](https://img.shields.io/coveralls/maruel/ut.svg)](https://coveralls.io/r/maruel/ut?branch=master)
+
+
+Examples
+--------
+
+ package foo
+
+ import (
+ "github.com/maruel/ut"
+ "log"
+ "strconv"
+ "testing"
+ )
+
+ func TestItoa(t *testing.T) {
+ ut.AssertEqual(t, "42", strconv.Itoa(42))
+ }
+
+ func TestItoaDataListDriven(t *testing.T) {
+ data := []struct {
+ in int
+ expected string
+ }{
+ {9, "9"},
+ {11, "11"},
+ }
+ for i, item := range data {
+ ut.AssertEqualIndex(t, i, item.expected, strconv.Itoa(item.in))
+ }
+ }
+
+ func TestWithLog(t *testing.T) {
+ out := ut.NewWriter(t)
+ defer out.Close()
+
+ logger := log.New(out, "Foo:", 0)
+
+ // These will be included in the test output only if the test case fails.
+ logger.Printf("Q: What is the answer to life the universe and everything?")
+ logger.Printf("A: %d", 42)
+ }
diff --git a/internal/engine/testdata/ut/config b/internal/engine/testdata/ut/config
new file mode 100644
index 0000000..d373584
--- /dev/null
+++ b/internal/engine/testdata/ut/config
@@ -0,0 +1,8 @@
+[core]
+ repositoryformatversion = 0
+ filemode = true
+ bare = false
+ logallrefupdates = true
+[remote "origin"]
+ url = https://github.com/maruel/ut
+ fetch = +refs/heads/*:refs/remotes/origin/*
diff --git a/internal/engine/testdata/ut/decorate_test.go b/internal/engine/testdata/ut/decorate_test.go
new file mode 100644
index 0000000..5443680
--- /dev/null
+++ b/internal/engine/testdata/ut/decorate_test.go
@@ -0,0 +1,50 @@
+// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
+// Use of this source code is governed under the Apache License, Version 2.0
+// that can be found in the LICENSE file.
+
+package ut
+
+import (
+ "fmt"
+ "testing"
+)
+
+// WARNING: Any code change to this file will trigger a test failure of
+// TestDecorateMax or TestDecorate. Make sure to update the expectation
+// accordingly. Sorry for the inconvenience.
+
+// TODO(maruel): It's wrong to hard code the containing path name.
+const file = "ut/decorate_test.go"
+
+func a() string {
+ return b()
+}
+
+func b() string {
+ return c()
+}
+
+func c() string {
+ return d()
+}
+
+func d() string {
+ return Decorate("Foo")
+}
+
+func TestDecorateMax(t *testing.T) {
+ t.Parallel()
+ // This test is line number dependent. a() is not listed, only b(), c() and
+ // d().
+ base := 24
+ expected := fmt.Sprintf("%s:%d: %s:%d: %s:%d: Foo", file, base, file, base+4, file, base+8)
+ AssertEqual(t, expected, a())
+}
+
+func TestDecorate(t *testing.T) {
+ t.Parallel()
+ // This test is line number dependent.
+ a := Decorate("Foo")
+ expected := fmt.Sprintf("%s:47: Foo", file)
+ AssertEqual(t, expected, a)
+}
diff --git a/internal/engine/testdata/ut/utiltest.go b/internal/engine/testdata/ut/utiltest.go
new file mode 100644
index 0000000..0485395
--- /dev/null
+++ b/internal/engine/testdata/ut/utiltest.go
@@ -0,0 +1,286 @@
+// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
+// Use of this source code is governed under the Apache License, Version 2.0
+// that can be found in the LICENSE file.
+
+// Package ut (for UtilTest) contains testing utilities to shorten unit tests.
+package ut
+
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/kr/pretty"
+ "github.com/pmezard/go-difflib/difflib"
+)
+
+var newLine = []byte{'\n'}
+
+var blacklistedItems = map[string]bool{
+ filepath.Join("runtime", "asm_386.s"): true,
+ filepath.Join("runtime", "asm_amd64.s"): true,
+ filepath.Join("runtime", "asm_arm.s"): true,
+ filepath.Join("runtime", "proc.c"): true,
+ filepath.Join("testing", "testing.go"): true,
+ filepath.Join("ut", "utiltest.go"): true,
+ "utiltest.go": true,
+}
+
+// truncatePath only keep the base filename and its immediate containing
+// directory.
+func truncatePath(file string) string {
+ return filepath.Join(filepath.Base(filepath.Dir(file)), filepath.Base(file))
+}
+
+func isBlacklisted(file string) bool {
+ _, ok := blacklistedItems[file]
+ return ok
+}
+
+// Decorate adds a prefix 'file:line: ' to a string, containing the 3 recent
+// callers in the stack.
+//
+// It skips internal functions. It is mostly meant to be used internally.
+//
+// It is inspired by testing's decorate().
+func Decorate(s string) string {
+ type item struct {
+ file string
+ line int
+ }
+ items := []item{}
+ for i := 1; i < 8 && len(items) < 3; i++ {
+ _, file, line, ok := runtime.Caller(i) // decorate + log + public function.
+ if ok {
+ file = truncatePath(file)
+ if !isBlacklisted(file) {
+ items = append(items, item{file, line})
+ }
+ }
+ }
+ for _, i := range items {
+ s = fmt.Sprintf("%s:%d: %s", strings.Replace(i.file, "%", "%%", -1), i.line, s)
+ }
+ return s
+}
+
+// AssertEqual verifies that two objects are equals and calls FailNow() to
+// immediately cancel the test case.
+//
+// It must be called from the main goroutine. Other goroutines must call
+// ExpectEqual* flavors.
+//
+// Equality is determined via reflect.DeepEqual().
+func AssertEqual(t testing.TB, expected, actual interface{}) {
+ AssertEqualf(t, expected, actual, "AssertEqual() failure.\n%# v", formatAsDiff(expected, actual))
+}
+
+// AssertEqualIndex verifies that two objects are equals and calls FailNow() to
+// immediately cancel the test case.
+//
+// It must be called from the main goroutine. Other goroutines must call
+// ExpectEqual* flavors.
+//
+// It is meant to be used in loops where a list of intrant->expected is
+// processed so the assert failure message contains the index of the failing
+// expectation.
+//
+// Equality is determined via reflect.DeepEqual().
+func AssertEqualIndex(t testing.TB, index int, expected, actual interface{}) {
+ AssertEqualf(t, expected, actual, "AssertEqualIndex() failure.\nIndex: %d\n%# v", index, formatAsDiff(expected, actual))
+}
+
+// AssertEqualf verifies that two objects are equals and calls FailNow() to
+// immediately cancel the test case.
+//
+// It must be called from the main goroutine. Other goroutines must call
+// ExpectEqual* flavors.
+//
+// This functions enables specifying an arbitrary string on failure.
+//
+// Equality is determined via reflect.DeepEqual().
+func AssertEqualf(t testing.TB, expected, actual interface{}, format string, items ...interface{}) {
+ // This is cheezy, as there's no way to figure out if the test was properly
+ // started by the test framework.
+ found := false
+ root := ""
+ for i := 1; ; i++ {
+ if _, file, _, ok := runtime.Caller(i); ok {
+ if filepath.Base(file) == "testing.go" {
+ found = true
+ break
+ }
+ root = file
+ } else {
+ break
+ }
+ }
+ if !found {
+ t.Logf(Decorate("ut.AssertEqual*() function MUST be called from within main test goroutine, use ut.ExpectEqual*() instead; found %s."), root)
+ // TODO(maruel): Warning: this will be enforced soon.
+ //t.Fail()
+ }
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf(Decorate(format), items...)
+ }
+}
+
+// ExpectEqual verifies that two objects are equals and calls Fail() to mark
+// the test case as failed but let it continue.
+//
+// It is fine to call this function from another goroutine than the main test
+// case goroutine.
+//
+// Equality is determined via reflect.DeepEqual().
+func ExpectEqual(t testing.TB, expected, actual interface{}) {
+ ExpectEqualf(t, expected, actual, "ExpectEqual() failure.\n%# v", formatAsDiff(expected, actual))
+}
+
+// ExpectEqualIndex verifies that two objects are equals and calls Fail() to
+// mark the test case as failed but let it continue.
+//
+// It is fine to call this function from another goroutine than the main test
+// case goroutine.
+//
+// It is meant to be used in loops where a list of intrant->expected is
+// processed so the assert failure message contains the index of the failing
+// expectation.
+//
+// Equality is determined via reflect.DeepEqual().
+func ExpectEqualIndex(t testing.TB, index int, expected, actual interface{}) {
+ ExpectEqualf(t, expected, actual, "ExpectEqualIndex() failure.\nIndex: %d\n%# v", index, formatAsDiff(expected, actual))
+}
+
+// ExpectEqualf verifies that two objects are equals and calls Fail() to mark
+// the test case as failed but let it continue.
+//
+// It is fine to call this function from another goroutine than the main test
+// case goroutine.
+//
+// This functions enables specifying an arbitrary string on failure.
+//
+// Equality is determined via reflect.DeepEqual().
+func ExpectEqualf(t testing.TB, expected, actual interface{}, format string, items ...interface{}) {
+ if !reflect.DeepEqual(actual, expected) {
+ // Errorf() is thread-safe, t.Fatalf() is not.
+ t.Errorf(Decorate(format), items...)
+ }
+}
+
+// testingWriter is used by NewWriter().
+type testingWriter struct {
+ t testing.TB
+ b bytes.Buffer
+}
+
+func (t testingWriter) Write(p []byte) (int, error) {
+ n, err := t.b.Write(p)
+ if err != nil || n != len(p) {
+ return n, err
+ }
+ // Manually scan for lines.
+ for {
+ b := t.b.Bytes()
+ i := bytes.Index(b, newLine)
+ if i == -1 {
+ break
+ }
+ t.t.Log(string(b[:i]))
+ t.b.Next(i + 1)
+ }
+ return n, err
+}
+
+func (t testingWriter) Close() error {
+ remaining := t.b.Bytes()
+ if len(remaining) != 0 {
+ t.t.Log(string(remaining))
+ }
+ return nil
+}
+
+// NewWriter adapts a testing.TB into a io.WriteCloser that can be used
+// with to log.SetOutput().
+//
+// Don't forget to defer foo.Close().
+func NewWriter(t testing.TB) io.WriteCloser {
+ return &testingWriter{t: t}
+}
+
+// Private stuff.
+
+// format creates a formatter that is both pretty and size limited.
+//
+// The limit is hardcoded to 2048. If you need more, edit the sources or send a
+// pull request.
+func format(i interface{}) fmt.Formatter {
+ return &formatter{formatter: pretty.Formatter(i), limit: 2048}
+}
+
+type formatter struct {
+ formatter fmt.Formatter
+ limit int
+ size int
+}
+
+func (f *formatter) Format(s fmt.State, c rune) {
+ l := &limiter{s, f.limit, f.size}
+ f.formatter.Format(l, c)
+ f.size = l.size
+}
+
+// formatAsDiff returns a formatable object that will print itself as the diff
+// between two objects.
+func formatAsDiff(expected, actual interface{}) fmt.Formatter {
+ return &formatterAsDiff{expected, actual}
+}
+
+type formatterAsDiff struct {
+ expected, actual interface{}
+}
+
+func (f *formatterAsDiff) Format(s fmt.State, c rune) {
+ // Format the items and escape those pesky ANSI codes.
+ expected := strings.Replace(pretty.Sprintf("%# v", f.expected), "\033", "\\033", -1)
+ actual := strings.Replace(pretty.Sprintf("%# v", f.actual), "\033", "\\033", -1)
+ if strings.IndexByte(expected, '\n') == -1 && strings.IndexByte(actual, '\n') == -1 {
+ fmt.Fprintf(s, "Expected: %s\nActual: %s", expected, actual)
+ return
+ }
+ diff := difflib.UnifiedDiff{
+ A: difflib.SplitLines(expected),
+ B: difflib.SplitLines(actual),
+ FromFile: "Expected",
+ ToFile: "Actual",
+ Context: 3,
+ }
+ _ = difflib.WriteUnifiedDiff(s, diff)
+}
+
+type limiter struct {
+ fmt.State
+ limit int
+ size int
+}
+
+func (l *limiter) Write(data []byte) (int, error) {
+ var err error
+ if l.size <= l.limit {
+ if chunk := len(data); chunk+l.size > l.limit {
+ chunk = l.limit - l.size
+ if chunk != 0 {
+ _, err = l.State.Write(data[:chunk])
+ }
+ _, err = l.State.Write([]byte("..."))
+ l.size = l.limit + 1
+ } else {
+ _, err = l.State.Write(data)
+ }
+ }
+ return len(data), err
+}
diff --git a/internal/engine/testdata/ut/utiltest_test.go b/internal/engine/testdata/ut/utiltest_test.go
new file mode 100644
index 0000000..91f6238
--- /dev/null
+++ b/internal/engine/testdata/ut/utiltest_test.go
@@ -0,0 +1,315 @@
+// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
+// Use of this source code is governed under the Apache License, Version 2.0
+// that can be found in the LICENSE file.
+
+package ut
+
+import (
+ "fmt"
+ "log"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func ExampleAssertEqual() {
+ // For a func TestXXX(t *testing.T)
+ t := &testing.T{}
+ AssertEqual(t, "10", strconv.Itoa(10))
+}
+
+func ExampleAssertEqualIndex() {
+ // For a func TestXXX(t *testing.T)
+ t := &testing.T{}
+
+ data := []struct {
+ in int
+ expected string
+ }{
+ {9, "9"},
+ {11, "11"},
+ }
+ for i, item := range data {
+ // Call a function to test.
+ actual := strconv.Itoa(item.in)
+ // Then do an assert as a one-liner.
+ AssertEqualIndex(t, i, item.expected, actual)
+ }
+}
+
+func ExampleExpectEqual() {
+ // For a func TestXXX(t *testing.T)
+ t := &testing.T{}
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ // ExpectEqual* flavors are safe to call in other goroutines.
+ ExpectEqual(t, "10", strconv.Itoa(10))
+ }()
+ wg.Wait()
+}
+
+func ExampleNewWriter() {
+ // For a func TestXXX(t *testing.T)
+ t := &testing.T{}
+
+ out := NewWriter(t)
+ defer out.Close()
+
+ logger := log.New(out, "Foo:", 0)
+
+ // These will be included in the test output only if the test case fails.
+ logger.Printf("Q: What is the answer to life the universe and everything?")
+ logger.Printf("A: %d", 42)
+}
+
+// AssertEqual*
+
+func TestAssertEqual(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ AssertEqual(t, &j, i)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestAssertEqualFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ var err interface{} = 1
+ defer func() {
+ if err != nil {
+ t.Fatalf("unexpected %s", err)
+ }
+ // Abuse the testing framework so this test is not marked as failed. It is
+ // not really skipped but that's the only way to set
+ // testing.T.finished = true.
+ t.SkipNow()
+ }()
+ defer func() {
+ err = recover()
+ }()
+ AssertEqual(t2, true, false)
+ // This line is never executed.
+ t.Fail()
+}
+
+func TestAssertEqualIndex(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ AssertEqualIndex(t, 24, &j, i)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestAssertEqualIndexFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ var err interface{} = 1
+ defer func() {
+ if err != nil {
+ t.Fatalf("unexpected %s", err)
+ }
+ // Abuse the testing framework so this test is not marked as failed. It is
+ // not really skipped but that's the only way to set
+ // testing.T.finished = true.
+ t.SkipNow()
+ }()
+ defer func() {
+ err = recover()
+ }()
+ AssertEqualIndex(t2, 24, true, false)
+ // This line is never executed.
+ t.Fail()
+}
+
+func TestAssertEqualf(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ AssertEqualf(t, &j, i, "foo %s %d", "bar", 2)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestAssertEqualfFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ var err interface{} = 1
+ defer func() {
+ if err != nil {
+ t.Fatalf("unexpected %s", err)
+ }
+ // Abuse the testing framework so this test is not marked as failed. It is
+ // not really skipped but that's the only way to set
+ // testing.T.finished = true.
+ t.SkipNow()
+ }()
+ defer func() {
+ err = recover()
+ }()
+ AssertEqualf(t2, true, false, "foo %s %d", "bar", 2)
+ // This line is never executed.
+ t.Fail()
+
+}
+
+// ExpectEqual*
+
+func TestExpectEqual(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ ExpectEqual(t, &j, i)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestExpectEqualFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ completed := false
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ // Ensure ExpectEqual* can be run from a goroutine.
+ defer wg.Done()
+ ExpectEqual(t2, true, false)
+ completed = true
+ }()
+ wg.Wait()
+ if !completed {
+ t.Fatal("didn't complete")
+ }
+}
+
+func TestExpectEqualIndex(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ ExpectEqualIndex(t, 24, &j, i)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestExpectEqualIndexFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ completed := false
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ // Ensure ExpectEqual* can be run from a goroutine.
+ defer wg.Done()
+ ExpectEqualIndex(t2, 24, true, false)
+ completed = true
+ }()
+ wg.Wait()
+ if !completed {
+ t.Fatal("didn't complete")
+ }
+}
+
+func TestExpectEqualf(t *testing.T) {
+ t.Parallel()
+ j := true
+ var i interface{} = &j
+ ExpectEqualf(t, &j, i, "foo %s %d", "bar", 2)
+ if t.Failed() {
+ t.Fatal("Expected success")
+ }
+}
+
+func TestExpectEqualfFail(t *testing.T) {
+ t.Parallel()
+ // Abuse the testing framework to mark a fake test as failed.
+ t2 := &testing.T{}
+ completed := false
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ // Ensure ExpectEqual* can be run from a goroutine.
+ defer wg.Done()
+ ExpectEqualf(t2, true, false, "foo %s %d", "bar", 2)
+ completed = true
+ }()
+ wg.Wait()
+ if !completed {
+ t.Fatal("didn't complete")
+ }
+
+}
+
+// Other
+
+type stubTB struct {
+ *testing.T
+ out []string
+}
+
+func (s *stubTB) Log(args ...interface{}) {
+ if len(args) != 1 {
+ s.FailNow()
+ }
+ str, ok := args[0].(string)
+ if !ok {
+ panic("Unexpected Log() call with something else than string")
+ }
+ s.out = append(s.out, str)
+}
+
+func TestNewWriter(t *testing.T) {
+ t.Parallel()
+ tStub := &stubTB{T: t}
+ out := NewWriter(tStub)
+ logger := log.New(out, "Foo:", 0)
+ logger.Printf("Q: What is the answer to life the universe and everything?")
+ logger.Printf("A: %d", 42)
+ ExpectEqual(t, nil, out.Close())
+ expected := []string{
+ "Foo:Q: What is the answer to life the universe and everything?",
+ "Foo:A: 42",
+ }
+ AssertEqual(t, expected, tStub.out)
+}
+
+func TestTruncatePath(t *testing.T) {
+ t.Parallel()
+ data := []struct{ in, expected string }{
+ {"foo", "foo"},
+ {filepath.Join("foo", "bar"), filepath.Join("foo", "bar")},
+ {filepath.Join("foo", "bar", "baz"), filepath.Join("bar", "baz")},
+ }
+ for i, line := range data {
+ AssertEqualIndex(t, i, line.expected, truncatePath(line.in))
+ }
+}
+
+func TestFormatter(t *testing.T) {
+ t.Parallel()
+ large := strings.Repeat("0123456789abcedf", 2048/16+1)
+ expected := strings.Repeat("0123456789abcedf", 2048/16) + "..."
+ AssertEqual(t, expected, fmt.Sprintf("%s", format(large)))
+}
+
+func TestDiffEscapeANSI(t *testing.T) {
+ t.Parallel()
+ actual := fmt.Sprintf("% #v", formatAsDiff("\033[31mHi", "\033[32mHi"))
+ expected := "Expected: \\033[31mHi\nActual: \\033[32mHi"
+ AssertEqual(t, expected, actual)
+}
diff --git a/internal/engine/testdata/ut_v1.0.0.zip b/internal/engine/testdata/ut_v1.0.0.zip
deleted file mode 100644
index 24099ec..0000000
--- a/internal/engine/testdata/ut_v1.0.0.zip
+++ /dev/null
Binary files differ
diff --git a/shac.textproto b/shac.textproto
index 4c7c760..f0a7b5f 100644
--- a/shac.textproto
+++ b/shac.textproto
@@ -18,6 +18,8 @@
min_shac_version: "0.0.0"
allow_network: False
ignore: "/vendor/"
+# Vendored code for test data only.
+ignore: "/internal/engine/testdata/ut/"
# TODO(olivernewman): Make root non-writable once we can use caches and
# pass-throughs to avoid having checks install tools and do Go builds within the
# checkout directory.