From f761eabd6e918435293e7feb438a3175fdbe29b2 Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 13:12:39 -0700 Subject: [PATCH 1/6] Re-establish v2 module. This reverts commit 07fc26ff556bcbe542febec6ffd12c6e8c7131fd. This reverts commit 5ffbd8d8af95f0b4420772275d2862037b79dceb. This reverts commit 07c29ade0887bdcc0f95edf3420d866d483b2d61. --- README.md | 17 +- fixture.go | 1 + v2/Makefile | 14 + v2/README.md | 38 + v2/better/better.go | 74 + v2/better/better_test.go | 28 + v2/examples/bowling_game.go | 51 + v2/examples/bowling_game_test.go | 85 ++ v2/fixture.go | 62 + v2/fixture_test.go | 73 + v2/go.mod | 3 + v2/gunit.go | 190 +++ v2/gunit_test.go | 199 +++ v2/options.go | 110 ++ v2/panic_test.go | 49 + v2/should/assert_test.go | 60 + v2/should/be_chronological.go | 40 + v2/should/be_chronological_test.go | 44 + v2/should/be_empty.go | 40 + v2/should/be_empty_test.go | 72 + v2/should/be_false.go | 21 + v2/should/be_false_test.go | 17 + v2/should/be_greater_than.go | 37 + v2/should/be_greater_than_or_equal_to.go | 41 + v2/should/be_greater_than_or_equal_to_test.go | 113 ++ v2/should/be_greater_than_test.go | 96 ++ v2/should/be_in.go | 27 + v2/should/be_in_test.go | 63 + v2/should/be_less_than.go | 160 ++ v2/should/be_less_than_or_equal_to.go | 41 + v2/should/be_less_than_or_equal_to_test.go | 116 ++ v2/should/be_less_than_test.go | 102 ++ v2/should/be_nil.go | 48 + v2/should/be_nil_test.go | 31 + v2/should/be_true.go | 20 + v2/should/be_true_test.go | 18 + v2/should/contain.go | 87 ++ v2/should/contain_test.go | 64 + v2/should/end_with.go | 57 + v2/should/end_with_test.go | 34 + v2/should/equal.go | 199 +++ v2/should/equal_test.go | 48 + v2/should/errors.go | 64 + v2/should/errors_test.go | 38 + v2/should/expected.go | 40 + v2/should/happen_after.go | 20 + v2/should/happen_after_test.go | 21 + v2/should/happen_before.go | 20 + v2/should/happen_before_test.go | 21 + v2/should/happen_on.go | 44 + v2/should/happen_on_test.go | 36 + v2/should/happen_within.go | 41 + v2/should/happen_within_test.go | 22 + v2/should/have_length.go | 29 + v2/should/have_length_test.go | 35 + v2/should/internal/go-diff/.gitignore | 22 + v2/should/internal/go-diff/.travis.yml | 27 + v2/should/internal/go-diff/APACHE-LICENSE-2.0 | 177 +++ v2/should/internal/go-diff/AUTHORS | 25 + v2/should/internal/go-diff/CONTRIBUTORS | 32 + v2/should/internal/go-diff/LICENSE | 20 + v2/should/internal/go-diff/Makefile | 44 + v2/should/internal/go-diff/README.md | 84 + .../internal/go-diff/diffmatchpatch/diff.go | 1345 +++++++++++++++++ .../go-diff/diffmatchpatch/diffmatchpatch.go | 46 + .../internal/go-diff/diffmatchpatch/match.go | 160 ++ .../diffmatchpatch/operation_string.go | 17 + .../internal/go-diff/diffmatchpatch/patch.go | 556 +++++++ .../go-diff/diffmatchpatch/stringutil.go | 88 ++ v2/should/internal/go-diff/scripts/lint.sh | 22 + .../internal/go-diff/testdata/speedtest1.txt | 230 +++ .../internal/go-diff/testdata/speedtest2.txt | 188 +++ v2/should/internal/go-render/.travis.yml | 21 + v2/should/internal/go-render/LICENSE | 27 + v2/should/internal/go-render/PRESUBMIT.py | 109 ++ v2/should/internal/go-render/README.md | 78 + v2/should/internal/go-render/WATCHLISTS | 26 + .../internal/go-render/pre-commit-go.yml | 78 + v2/should/internal/go-render/render/render.go | 481 ++++++ .../internal/go-render/render/render_test.go | 281 ++++ .../internal/go-render/render/render_time.go | 26 + v2/should/kinds.go | 107 ++ v2/should/not.go | 6 + v2/should/panic.go | 46 + v2/should/panic_test.go | 28 + v2/should/spec.go | 6 + v2/should/start_with.go | 57 + v2/should/start_with_test.go | 34 + v2/should/wrap_error.go | 46 + v2/should/wrap_error_test.go | 27 + v2/so.go | 25 + v2/so_test.go | 75 + 92 files changed, 7786 insertions(+), 2 deletions(-) create mode 100755 v2/Makefile create mode 100644 v2/README.md create mode 100644 v2/better/better.go create mode 100644 v2/better/better_test.go create mode 100644 v2/examples/bowling_game.go create mode 100644 v2/examples/bowling_game_test.go create mode 100644 v2/fixture.go create mode 100644 v2/fixture_test.go create mode 100644 v2/go.mod create mode 100644 v2/gunit.go create mode 100644 v2/gunit_test.go create mode 100644 v2/options.go create mode 100644 v2/panic_test.go create mode 100644 v2/should/assert_test.go create mode 100644 v2/should/be_chronological.go create mode 100644 v2/should/be_chronological_test.go create mode 100644 v2/should/be_empty.go create mode 100644 v2/should/be_empty_test.go create mode 100644 v2/should/be_false.go create mode 100644 v2/should/be_false_test.go create mode 100644 v2/should/be_greater_than.go create mode 100644 v2/should/be_greater_than_or_equal_to.go create mode 100644 v2/should/be_greater_than_or_equal_to_test.go create mode 100644 v2/should/be_greater_than_test.go create mode 100644 v2/should/be_in.go create mode 100644 v2/should/be_in_test.go create mode 100644 v2/should/be_less_than.go create mode 100644 v2/should/be_less_than_or_equal_to.go create mode 100644 v2/should/be_less_than_or_equal_to_test.go create mode 100644 v2/should/be_less_than_test.go create mode 100644 v2/should/be_nil.go create mode 100644 v2/should/be_nil_test.go create mode 100644 v2/should/be_true.go create mode 100644 v2/should/be_true_test.go create mode 100644 v2/should/contain.go create mode 100644 v2/should/contain_test.go create mode 100644 v2/should/end_with.go create mode 100644 v2/should/end_with_test.go create mode 100644 v2/should/equal.go create mode 100644 v2/should/equal_test.go create mode 100644 v2/should/errors.go create mode 100644 v2/should/errors_test.go create mode 100644 v2/should/expected.go create mode 100644 v2/should/happen_after.go create mode 100644 v2/should/happen_after_test.go create mode 100644 v2/should/happen_before.go create mode 100644 v2/should/happen_before_test.go create mode 100644 v2/should/happen_on.go create mode 100644 v2/should/happen_on_test.go create mode 100644 v2/should/happen_within.go create mode 100644 v2/should/happen_within_test.go create mode 100644 v2/should/have_length.go create mode 100644 v2/should/have_length_test.go create mode 100644 v2/should/internal/go-diff/.gitignore create mode 100644 v2/should/internal/go-diff/.travis.yml create mode 100644 v2/should/internal/go-diff/APACHE-LICENSE-2.0 create mode 100644 v2/should/internal/go-diff/AUTHORS create mode 100644 v2/should/internal/go-diff/CONTRIBUTORS create mode 100644 v2/should/internal/go-diff/LICENSE create mode 100644 v2/should/internal/go-diff/Makefile create mode 100644 v2/should/internal/go-diff/README.md create mode 100644 v2/should/internal/go-diff/diffmatchpatch/diff.go create mode 100644 v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go create mode 100644 v2/should/internal/go-diff/diffmatchpatch/match.go create mode 100644 v2/should/internal/go-diff/diffmatchpatch/operation_string.go create mode 100644 v2/should/internal/go-diff/diffmatchpatch/patch.go create mode 100644 v2/should/internal/go-diff/diffmatchpatch/stringutil.go create mode 100755 v2/should/internal/go-diff/scripts/lint.sh create mode 100644 v2/should/internal/go-diff/testdata/speedtest1.txt create mode 100644 v2/should/internal/go-diff/testdata/speedtest2.txt create mode 100644 v2/should/internal/go-render/.travis.yml create mode 100644 v2/should/internal/go-render/LICENSE create mode 100644 v2/should/internal/go-render/PRESUBMIT.py create mode 100644 v2/should/internal/go-render/README.md create mode 100644 v2/should/internal/go-render/WATCHLISTS create mode 100644 v2/should/internal/go-render/pre-commit-go.yml create mode 100644 v2/should/internal/go-render/render/render.go create mode 100644 v2/should/internal/go-render/render/render_test.go create mode 100644 v2/should/internal/go-render/render/render_time.go create mode 100644 v2/should/kinds.go create mode 100644 v2/should/not.go create mode 100644 v2/should/panic.go create mode 100644 v2/should/panic_test.go create mode 100644 v2/should/spec.go create mode 100644 v2/should/start_with.go create mode 100644 v2/should/start_with_test.go create mode 100644 v2/should/wrap_error.go create mode 100644 v2/should/wrap_error_test.go create mode 100644 v2/so.go create mode 100644 v2/so_test.go diff --git a/README.md b/README.md index 8e345a1..68f340c 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,19 @@ # gunit +## v2 + +[![GoDoc](https://godoc.org/github.com/smarty/gunit/v2?status.svg)](http://godoc.org/github.com/smarty/gunit/v2) + +Installation: + +``` +$ go get github.com/smarty/gunit/v2 +``` + + +## v1 + [![GoDoc](https://godoc.org/github.com/smarty/gunit?status.svg)](http://godoc.org/github.com/smarty/gunit) Installation: @@ -39,8 +52,8 @@ import ( "time" "testing" - "github.com/smarty/gunit/" - "github.com/smarty/gunit/assert/should" + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/should" ) func TestExampleFixture(t *testing.T) { diff --git a/fixture.go b/fixture.go index afe46f7..272d8dc 100644 --- a/fixture.go +++ b/fixture.go @@ -1,6 +1,7 @@ // Package gunit provides "testing" package hooks and convenience // functions for writing tests in an xUnit style. // See the README file and the examples folder for examples. +// Deprecated: use github.com/smarty/gunit/v2 instead. package gunit import ( diff --git a/v2/Makefile b/v2/Makefile new file mode 100755 index 0000000..9cdd664 --- /dev/null +++ b/v2/Makefile @@ -0,0 +1,14 @@ +#!/usr/bin/make -f + +test: fmt + GORACE="atexit_sleep_ms=50" go test -timeout=1s -race -count=1 -covermode=atomic ./... + +fmt: + go mod tidy && go fmt ./... + +compile: + go build ./... + +build: test compile + +.PHONY: fmt test compile build diff --git a/v2/README.md b/v2/README.md new file mode 100644 index 0000000..2a0088b --- /dev/null +++ b/v2/README.md @@ -0,0 +1,38 @@ +#### SMARTY DISCLAIMER: Subject to the terms of the associated license agreement, this software is freely available for your use. This software is FREE, AS IN PUPPIES, and is a gift. Enjoy your new responsibility. This means that while we may consider enhancement requests, we may or may not choose to entertain requests at our sole and absolute discretion. + +[![GoDoc](https://godoc.org/github.com/smarty/gunit/v2?status.svg)](http://godoc.org/github.com/smarty/gunit/v2) + +# gunit (v2) + +## Installation + +``` +$ go get github.com/smarty/gunit/v2 +``` + +## Usage + +For users of JetBrains IDEs, here's LiveTemplate you can use for generating the scaffolding for a new fixture: + +- Abbreviation: `fixture` +- Description: `Generate gunit Fixture boilerplate` +- Template Text: + +``` +func Test$NAME$Fixture(t *testing.T) { + gunit.Run(new($NAME$Fixture), t) +} + +type $NAME$Fixture struct { + *gunit.Fixture +} + +func (this *$NAME$Fixture) Setup() { +} + +func (this *$NAME$Fixture) Test$END$() { +} + +``` + +**NOTE:** _Be sure to specify that this LiveTemplate is applicable in Go files._ diff --git a/v2/better/better.go b/v2/better/better.go new file mode 100644 index 0000000..88e7f9f --- /dev/null +++ b/v2/better/better.go @@ -0,0 +1,74 @@ +// Package better provides the same assertions as the should package, but the +// error returned in failure conditions results in a call to *testing.T.Fatal(), +// halting the currently running test. +package better + +import ( + "fmt" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/should" +) + +var ( + BeChronological = wrapFatal(should.BeChronological) + BeEmpty = wrapFatal(should.BeEmpty) + BeFalse = wrapFatal(should.BeFalse) + BeGreaterThan = wrapFatal(should.BeGreaterThan) + BeGreaterThanOrEqualTo = wrapFatal(should.BeGreaterThanOrEqualTo) + BeIn = wrapFatal(should.BeIn) + BeLessThan = wrapFatal(should.BeLessThan) + BeLessThanOrEqualTo = wrapFatal(should.BeLessThanOrEqualTo) + BeNil = wrapFatal(should.BeNil) + BeTrue = wrapFatal(should.BeTrue) + Contain = wrapFatal(should.Contain) + EndWith = wrapFatal(should.EndWith) + Equal = wrapFatal(should.Equal) + HappenAfter = wrapFatal(should.HappenAfter) + HappenBefore = wrapFatal(should.HappenBefore) + HappenOn = wrapFatal(should.HappenOn) + HappenWithin = wrapFatal(should.HappenWithin) + HaveLength = wrapFatal(should.HaveLength) + Panic = wrapFatal(should.Panic) + StartWith = wrapFatal(should.StartWith) + WrapError = wrapFatal(should.WrapError) +) + +// NOT constrains all negated assertions to their own 'namespace'. +var NOT = struct { + BeChronological gunit.Assertion + BeEmpty gunit.Assertion + BeGreaterThan gunit.Assertion + BeGreaterThanOrEqualTo gunit.Assertion + BeIn gunit.Assertion + BeLessThan gunit.Assertion + BeLessThanOrEqualTo gunit.Assertion + BeNil gunit.Assertion + Contain gunit.Assertion + Equal gunit.Assertion + HappenOn gunit.Assertion + Panic gunit.Assertion +}{ + BeChronological: wrapFatal(should.NOT.BeChronological), + BeEmpty: wrapFatal(should.NOT.BeEmpty), + BeGreaterThan: wrapFatal(should.NOT.BeGreaterThan), + BeGreaterThanOrEqualTo: wrapFatal(should.NOT.BeGreaterThanOrEqualTo), + BeIn: wrapFatal(should.NOT.BeIn), + BeLessThan: wrapFatal(should.NOT.BeLessThan), + BeLessThanOrEqualTo: wrapFatal(should.NOT.BeLessThanOrEqualTo), + BeNil: wrapFatal(should.NOT.BeNil), + Contain: wrapFatal(should.NOT.Contain), + Equal: wrapFatal(should.NOT.Equal), + HappenOn: wrapFatal(should.NOT.HappenOn), + Panic: wrapFatal(should.NOT.Panic), +} + +func wrapFatal(original gunit.Assertion) gunit.Assertion { + return func(actual any, expected ...any) error { + err := original(actual, expected...) + if err != nil { + return fmt.Errorf("%w %w", should.ErrFatalAssertionFailure, err) + } + return nil + } +} diff --git a/v2/better/better_test.go b/v2/better/better_test.go new file mode 100644 index 0000000..efb1c1a --- /dev/null +++ b/v2/better/better_test.go @@ -0,0 +1,28 @@ +package better_test + +import ( + "testing" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/better" + "github.com/smarty/gunit/v2/should" +) + +func TestWrapFatalSuccess(t *testing.T) { + err := better.Equal(1, 1) + gunit.So(t, err, should.BeNil) +} +func TestWrapFatalFailure(t *testing.T) { + err := better.Equal(1, 2) + gunit.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) + gunit.So(t, err, should.WrapError, should.ErrAssertionFailure) +} +func TestWrapFatalSuccess_NOT(t *testing.T) { + err := better.NOT.Equal(1, 2) + gunit.So(t, err, should.BeNil) +} +func TestWrapFatalFailure_NOT(t *testing.T) { + err := better.NOT.Equal(1, 1) + gunit.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) + gunit.So(t, err, should.WrapError, should.ErrAssertionFailure) +} diff --git a/v2/examples/bowling_game.go b/v2/examples/bowling_game.go new file mode 100644 index 0000000..1bacfb8 --- /dev/null +++ b/v2/examples/bowling_game.go @@ -0,0 +1,51 @@ +package examples + +type Game struct { + rolls [maxThrowsPerGame]int + roll int + score int +} + +func NewGame() *Game { + return new(Game) +} + +func (this *Game) RecordRoll(pins int) { + this.rolls[this.roll] = pins + this.roll++ +} + +func (this *Game) CalculateScore() int { + this.roll = 0 + for frame := 0; frame < framesPerGame; frame++ { + this.score += this.calculateFrameScore() + this.roll += this.advanceFrame() + } + return this.score +} + +func (this *Game) calculateFrameScore() int { + if this.isStrike() { + return allPins + this.at(1) + this.at(2) + } + if this.isSpare() { + return allPins + this.at(2) + } + return this.at(0) + this.at(1) +} +func (this *Game) advanceFrame() int { + if this.isStrike() { + return 1 + } + return 2 +} + +func (this *Game) isStrike() bool { return this.at(0) == allPins } +func (this *Game) isSpare() bool { return this.at(0)+this.at(1) == allPins } +func (this *Game) at(offset int) int { return this.rolls[this.roll+offset] } + +const ( + allPins = 10 + framesPerGame = 10 + maxThrowsPerGame = 21 +) diff --git a/v2/examples/bowling_game_test.go b/v2/examples/bowling_game_test.go new file mode 100644 index 0000000..d668150 --- /dev/null +++ b/v2/examples/bowling_game_test.go @@ -0,0 +1,85 @@ +package examples + +import ( + "slices" + "testing" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/should" +) + +func TestBowlingGameScoringFixture(t *testing.T) { + gunit.Run(new(BowlingGameScoringFixture), t) +} + +type BowlingGameScoringFixture struct { + *gunit.Fixture + game *Game +} + +func (this *BowlingGameScoringFixture) Setup() { + this.game = NewGame() +} + +func (this *BowlingGameScoringFixture) TestGutterGame() { + this.rollMany(20, 0) + this.assertScore(0) +} +func (this *BowlingGameScoringFixture) TestAllOnes() { + this.rollMany(20, 1) + this.assertScore(20) +} +func (this *BowlingGameScoringFixture) TestSpare() { + this.rollSeveral(5, 5, 4, 3) + this.assertScore(21) +} +func (this *BowlingGameScoringFixture) TestStrike() { + this.rollSeveral(10, 3, 4) + this.assertScore(24) +} +func (this *BowlingGameScoringFixture) Test21Throws() { + this.rollMany(18, 0) + this.rollSeveral(5, 5, 5) + this.assertScore(15) +} +func (this *BowlingGameScoringFixture) TestPerfection() { + this.rollMany(12, 10) + this.assertScore(300) +} +func (this *BowlingGameScoringFixture) assertScore(expected int) { + this.So(this.game.CalculateScore(), should.Equal, expected) +} + +func (this *BowlingGameScoringFixture) rollMany(times, pins int) { + for x := 0; x < times; x++ { + this.game.RecordRoll(pins) + } +} +func (this *BowlingGameScoringFixture) rollSeveral(rolls ...int) { + for _, roll := range rolls { + this.game.RecordRoll(roll) + } +} + +func (this *BowlingGameScoringFixture) TestTable() { + subTests := []struct { + name string + rolls []int + expected int + }{ + {name: "gutter-game", rolls: slices.Repeat([]int{0}, 20), expected: 0}, + {name: "all-ones", rolls: slices.Repeat([]int{1}, 20), expected: 20}, + {name: "spare", rolls: []int{5, 5, 4, 3}, expected: 21}, + {name: "strike", rolls: []int{10, 3, 4}, expected: 24}, + {name: "perfection", rolls: slices.Repeat([]int{10}, 12), expected: 300}, + } + for _, sub := range subTests { + this.Run(sub.name, func(fixture *gunit.Fixture) { + game := NewGame() + for _, roll := range sub.rolls { + game.RecordRoll(roll) + } + fixture.So(game.CalculateScore(), should.Equal, sub.expected) + }) + } +} diff --git a/v2/fixture.go b/v2/fixture.go new file mode 100644 index 0000000..57ad211 --- /dev/null +++ b/v2/fixture.go @@ -0,0 +1,62 @@ +package gunit + +import ( + "context" + "fmt" + "io" + "runtime/debug" + "testing" +) + +type Fixture struct{ TestingT } + +func (this *Fixture) Print(a ...any) { _, _ = fmt.Fprint(this.Output(), a...) } +func (this *Fixture) Printf(f string, a ...any) { _, _ = fmt.Fprintf(this.Output(), f, a...) } +func (this *Fixture) Println(a ...any) { _, _ = fmt.Fprintln(this.Output(), a...) } + +// So is a convenience method for reporting assertion failure messages +// with the many assertion functions found in github.com/smarty/gunit/v2/should. +// Example: this.So(actual, should.Equal, expected) +func (this *Fixture) So(actual any, assert Assertion, expected ...any) { + this.Helper() + So(this, actual, assert, expected...) +} + +// Run is analogous to *testing.T.Run and allows for running subtests from +// test fixture methods (such as for table-driven tests). +func (this *Fixture) Run(name string, test func(fixture *Fixture)) { + this.TestingT.(*testing.T).Run(name, func(t *testing.T) { + t.Helper() + fixture := &Fixture{TestingT: t} + defer func() { + if r := recover(); r != nil { + fixture.Fail() + fixture.Log(panicReport(r, debug.Stack())) + } + }() + test(fixture) + }) +} + +type TestingT interface { + Cleanup(func()) + Context() context.Context + Error(args ...any) + Errorf(format string, args ...any) + Fail() + FailNow() + Failed() bool + Fatal(args ...any) + Fatalf(format string, args ...any) + Helper() + Log(args ...any) + Logf(format string, args ...any) + Name() string + Output() io.Writer + Setenv(key, value string) + Skip(args ...any) + SkipNow() + Skipf(format string, args ...any) + Skipped() bool + TempDir() string +} diff --git a/v2/fixture_test.go b/v2/fixture_test.go new file mode 100644 index 0000000..243874e --- /dev/null +++ b/v2/fixture_test.go @@ -0,0 +1,73 @@ +package gunit + +import ( + "bytes" + "context" + "fmt" + "io" + "strings" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldFailure(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + fixture := &Fixture{TestingT: fakeT} + fixture.So(1, should.Equal, 2) + actual := strings.Join(strings.Fields(fakeT.buffer.String()), " ") + expected := "assertion failure: Expected: (int) 2 Actual: (int) 1 ^ Stack: (filtered)" + if !strings.HasPrefix(actual, expected) { + t.Errorf("\n"+ + "expected: %s\n"+ + "actual: %s", expected, actual) + } + if fakeT.failCount != 1 { + t.Error("Expected 1 failure, got:", fakeT.failCount) + } +} +func TestPrint(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + fixture := &Fixture{TestingT: fakeT} + fixture.Print("one") + fixture.Printf("%s", "two") + fixture.Println("three") + actual := fakeT.buffer.String() + expected := "one" + "two" + "three\n" + if actual != expected { + t.Errorf("\n"+ + "expected: %s\n"+ + "actual: %s", expected, actual) + } +} + +type FakeT struct { + failCount int + buffer *bytes.Buffer +} + +func (this *FakeT) Cleanup(func()) { panic("not implemented") } +func (this *FakeT) Context() context.Context { panic("not implemented") } +func (this *FakeT) Errorf(string, ...any) { panic("not implemented") } +func (this *FakeT) Fail() { panic("not implemented") } +func (this *FakeT) FailNow() { panic("not implemented") } +func (this *FakeT) Failed() bool { panic("not implemented") } +func (this *FakeT) Fatal(a ...any) { panic("not implemented") } +func (this *FakeT) Fatalf(string, ...any) { panic("not implemented") } +func (this *FakeT) Logf(string, ...any) { panic("not implemented") } +func (this *FakeT) Name() string { panic("not implemented") } +func (this *FakeT) Output() io.Writer { return this.buffer } +func (this *FakeT) Setenv(string, string) { panic("not implemented") } +func (this *FakeT) Skip(...any) { panic("not implemented") } +func (this *FakeT) SkipNow() { panic("not implemented") } +func (this *FakeT) Skipf(string, ...any) { panic("not implemented") } +func (this *FakeT) Skipped() bool { panic("not implemented") } +func (this *FakeT) TempDir() string { panic("not implemented") } +func (this *FakeT) Helper() {} +func (this *FakeT) Log(a ...any) { + _, _ = this.buffer.Write([]byte(fmt.Sprint(a...))) +} +func (this *FakeT) Error(a ...any) { + this.failCount++ + _, _ = fmt.Fprintln(this.buffer, a...) +} diff --git a/v2/go.mod b/v2/go.mod new file mode 100644 index 0000000..5bb55a2 --- /dev/null +++ b/v2/go.mod @@ -0,0 +1,3 @@ +module github.com/smarty/gunit/v2 + +go 1.25 diff --git a/v2/gunit.go b/v2/gunit.go new file mode 100644 index 0000000..7c5d10a --- /dev/null +++ b/v2/gunit.go @@ -0,0 +1,190 @@ +package gunit + +import ( + "fmt" + "reflect" + "runtime/debug" + "strings" + "testing" +) + +/* +Run accepts a fixture with Test* methods and +optional setup/teardown methods and executes +the suite. Fixtures must be struct types which +embeds a *gunit.Fixture. Assuming a fixture struct +with test methods 'Test1' and 'Test2' execution +would proceed as follows: + + 1. fixture.SetupSuite() + 2. fixture.Setup() + 3. fixture.Test1() + 4. fixture.Teardown() + 5. fixture.Setup() + 6. fixture.Test2() + 7. fixture.Teardown() + 8. fixture.TeardownSuite() + +The methods provided by Options may be supplied +to this function to tweak the execution. +*/ +func Run(outerFixture any, t *testing.T, options ...Option) { + config := new(config) + for _, option := range append(defaultOptions, options...) { + option(config) + } + + fixtureValue := reflect.ValueOf(outerFixture) + fixtureType := reflect.TypeOf(outerFixture) + + var ( + testNames []string + skippedTestNames []string + focusedTestNames []string + ) + for x := range fixtureType.NumMethod() { + name := fixtureType.Method(x).Name + method := fixtureValue.MethodByName(name) + _, isNiladic := method.Interface().(func()) + if !isNiladic { + continue + } + + if strings.HasPrefix(name, "Test") { + testNames = append(testNames, name) + } else if config.skipAllTests || strings.HasPrefix(name, "SkipTest") { + skippedTestNames = append(skippedTestNames, name) + } else if strings.HasPrefix(name, "FocusTest") { + focusedTestNames = append(focusedTestNames, name) + } + } + + for _, name := range skippedTestNames { + testCase{t: t, manualSkip: true, name: name}.run() + } + + if len(focusedTestNames) > 0 { + testNames = focusedTestNames + } + + if len(testNames) == 0 { + t.Skip("NOT IMPLEMENTED (no test cases defined, or they are all marked as skipped)") + return + } + + if config.parallelFixture { + t.Parallel() + } + + setInnerFixture(fixtureValue, t) + + setup, hasSetup := outerFixture.(setupSuite) + if hasSetup { + setup.SetupSuite() + } + + teardown, hasTeardown := outerFixture.(teardownSuite) + if hasTeardown { + defer teardown.TeardownSuite() + } + + for _, name := range testNames { + testCase{ + t: t, + name: name, + config: config, + fixtureType: fixtureType, + fixtureValue: fixtureValue, + }.run() + } +} + +func setInnerFixture(fixtureValue reflect.Value, t *testing.T) { + defer func() { + if recover() != nil { + panic("must embed a *gunit.Fixture on the provided fixture") + } + }() + fixtureValue.Elem().FieldByName("Fixture").Set(reflect.ValueOf(&Fixture{TestingT: t})) +} + +type testCase struct { + t *testing.T + name string + config *config + manualSkip bool + fixtureType reflect.Type + fixtureValue reflect.Value +} + +func (this testCase) run() { + _ = this.t.Run(this.name, this.decideRun()) +} +func (this testCase) decideRun() func(*testing.T) { + if this.manualSkip { + return this.skipFunc("Skipping: " + this.name) + } + return this.runTest +} +func (this testCase) skipFunc(message string) func(*testing.T) { + return func(t *testing.T) { t.Skip(message) } +} +func (this testCase) runTest(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fail() + t.Log(panicReport(r, debug.Stack())) + } + }() + if this.config.parallelTests { + t.Parallel() + } + + fixtureValue := this.fixtureValue + if this.config.freshFixture { + fixtureValue = reflect.New(this.fixtureType.Elem()) + } + setInnerFixture(fixtureValue, t) + + setup, hasSetup := fixtureValue.Interface().(setupTest) + if hasSetup { + setup.Setup() + } + + teardown, hasTeardown := fixtureValue.Interface().(teardownTest) + if hasTeardown { + defer teardown.Teardown() + } + + fixtureValue.MethodByName(this.name).Call(nil) +} + +type ( + setupSuite interface{ SetupSuite() } + setupTest interface{ Setup() } + teardownTest interface{ Teardown() } + teardownSuite interface{ TeardownSuite() } +) + +func panicReport(r any, stack []byte) string { + var builder strings.Builder + _, _ = fmt.Fprintln(&builder, "PANIC:", r) + _, _ = fmt.Fprintln(&builder, "...") + + opened, closed := false, false + for _, line := range strings.Split(string(stack), "\n") { + if strings.Contains(line, "/runtime/panic.go:") { + opened = true + continue + } + if !opened || closed { + continue + } + if strings.Contains(line, "reflect.Value.call({0x") { + closed = true + continue + } + _, _ = fmt.Fprintln(&builder, line) + } + return strings.TrimSpace(builder.String()) +} diff --git a/v2/gunit_test.go b/v2/gunit_test.go new file mode 100644 index 0000000..e68b76c --- /dev/null +++ b/v2/gunit_test.go @@ -0,0 +1,199 @@ +package gunit_test + +import ( + "testing" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/should" +) + +func TestSuiteWithoutEmbeddedFixture(t *testing.T) { + defer func() { + if recover() == nil { + t.Error("Expected panic didn't occur.") + } + }() + gunit.Run(&Suite00{}, t) +} + +type Suite00 struct{} + +func (this *Suite00) Test() {} + +/////////////////////////// + +func TestSuiteWithSetupsAndTeardowns(t *testing.T) { + fixture := &Suite01{} + + gunit.Run(fixture, t, gunit.Options.IntegrationTests()) + + fixture.So(fixture.events, should.Equal, []string{ + "SetupSuite", + "Setup", + "Test", + "Teardown", + "TeardownSuite", + }) +} + +type Suite01 struct { + *gunit.Fixture + events []string +} + +func (this *Suite01) SetupSuite() { this.record("SetupSuite") } +func (this *Suite01) TeardownSuite() { this.record("TeardownSuite") } +func (this *Suite01) Setup() { this.record("Setup") } +func (this *Suite01) Teardown() { this.record("Teardown") } +func (this *Suite01) Test() { this.record("Test") } +func (this *Suite01) record(event string) { this.events = append(this.events, event) } + +/////////////////////////// + +func TestFreshFixture(t *testing.T) { + fixture := &Suite02{} + gunit.Run(fixture, t, gunit.Options.UnitTests()) + fixture.So(fixture.counter, should.Equal, 0) +} + +type Suite02 struct { + *gunit.Fixture + counter int +} + +func (this *Suite02) TestSomething() { + this.Printf("*** this should appear in the test log!") + this.counter++ +} + +/////////////////////////// + +func TestSkip(t *testing.T) { + fixture := &Suite03{} + gunit.Run(fixture, t) + fixture.So(t.Failed(), should.Equal, false) +} + +type Suite03 struct{ *gunit.Fixture } + +func (this *Suite03) SkipTestThatFails() { + this.So(1, should.Equal, 2) +} + +/////////////////////////// + +func TestFocus(t *testing.T) { + fixture := &Suite04{events: make(map[string]struct{})} + + gunit.Run(fixture, t, gunit.Options.SharedFixture()) + + fixture.So(t.Failed(), should.Equal, false) + fixture.So(fixture.events, should.Equal, map[string]struct{}{"1": {}}) +} + +type Suite04 struct { + *gunit.Fixture + events map[string]struct{} +} + +func (this *Suite04) FocusTest1() { + this.events["1"] = struct{}{} +} +func (this *Suite04) TestThatFails() { + this.So(1, should.Equal, 2) +} + +/////////////////////////// + +func TestSuiteWithSetupsAndTeardownsSkippedEntirelyIfAllTestsSkipped(t *testing.T) { + fixture := &Suite05{} + + gunit.Run(fixture, t, gunit.Options.SharedFixture()) + + fixture.So(fixture.events, should.Equal, nil) +} + +type Suite05 struct { + *gunit.Fixture + events []string +} + +func (this *Suite05) SetupSuite() { this.record("SetupSuite") } +func (this *Suite05) TeardownSuite() { this.record("TeardownSuite") } +func (this *Suite05) Setup() { this.record("Setup") } +func (this *Suite05) Teardown() { this.record("Teardown") } +func (this *Suite05) SkipTest() { this.record("SkipTest") } +func (this *Suite05) record(event string) { this.events = append(this.events, event) } + +/////////////////////////// + +func TestSuiteWithSkippedTests(t *testing.T) { + fixture := &Suite06{} + + gunit.Run(fixture, t, gunit.Options.SharedFixture()) + + fixture.So(fixture.events, should.Equal, []string{ + "SetupSuite", + "Setup", + "Test1", + "Teardown", + "TeardownSuite", + }) +} + +type Suite06 struct { + *gunit.Fixture + events []string +} + +func (this *Suite06) SetupSuite() { this.record("SetupSuite") } +func (this *Suite06) TeardownSuite() { this.record("TeardownSuite") } +func (this *Suite06) Setup() { this.record("Setup") } +func (this *Suite06) Teardown() { this.record("Teardown") } +func (this *Suite06) Test1() { this.record("Test1") } +func (this *Suite06) SkipTest2() { this.record("SkipTest2") } +func (this *Suite06) record(event string) { this.events = append(this.events, event) } + +/////////////////////////// + +func TestSuiteWithSubTests(t *testing.T) { + fixture := &Suite07{} + + gunit.Run(fixture, t, gunit.Options.SharedFixture()) + + fixture.So(fixture.events, should.Equal, []string{ + "TestSuiteWithSubTests/Test1/a", + "TestSuiteWithSubTests/Test1/b", + "TestSuiteWithSubTests/Test1/c", + }) +} + +type Suite07 struct { + *gunit.Fixture + events []string +} + +func (this *Suite07) Test1() { + this.Run("a", func(fixture *gunit.Fixture) { this.record(fixture.Name()) }) + this.Run("b", func(fixture *gunit.Fixture) { this.record(fixture.Name()) }) + this.Run("c", func(fixture *gunit.Fixture) { this.record(fixture.Name()) }) +} +func (this *Suite07) record(event string) { this.events = append(this.events, event) } + +/////////////////////////// + +func TestSuiteThatPanics(t *testing.T) { + t.Skip("Unskip to see this test fail with a nicely filtered and formatted stack trace.") + + fixture := &Suite08{} + + gunit.Run(fixture, t, gunit.Options.SharedFixture()) +} + +type Suite08 struct { + *gunit.Fixture +} + +func (this *Suite08) Test1() { + panic("boink") +} diff --git a/v2/options.go b/v2/options.go new file mode 100644 index 0000000..808e730 --- /dev/null +++ b/v2/options.go @@ -0,0 +1,110 @@ +package gunit + +type config struct { + skipAllTests bool + freshFixture bool + parallelFixture bool + parallelTests bool +} + +// Option is a function that modifies a config. +// See Options for provided behaviors. +type Option func(*config) + +type singleton struct{} + +// Options provides the sole entrypoint +// to the option functions provided by +// this package. +var Options singleton + +// SkipAll causes each and every "Test" method in the corresponding +// fixture to be skipped (as if each had been prefixed with +// "Skip"). Even "Test" methods marked with the "Focus" prefix +// will be skipped. +func (singleton) SkipAll() Option { + return func(this *config) { + this.skipAllTests = true + } +} + +// FreshFixture signals to Run that the +// new instances of the provided fixture +// are to be instantiated for each and +// every test case. The Setup and Teardown +// methods are also executed on the +// specifically instantiated fixtures. +// NOTE: the SetupSuite and TeardownSuite +// methods are always run on the provided +// fixture instance, regardless of this +// option having been provided. +func (singleton) FreshFixture() Option { + return func(c *config) { + c.freshFixture = true + } +} + +// SharedFixture signals to Run that the +// provided fixture instance is to be used +// to run all test methods. This mode is +// not compatible with ParallelFixture or +// ParallelTests and disables them. +func (singleton) SharedFixture() Option { + return func(c *config) { + c.freshFixture = false + c.parallelTests = false + c.parallelFixture = false + } +} + +// ParallelFixture signals to Run that the +// provided fixture instance can be executed +// in parallel with other go test functions. +// This option assumes that `go test` was +// invoked with the -parallel flag. +func (singleton) ParallelFixture() Option { + return func(c *config) { + c.parallelFixture = true + } +} + +// ParallelTests signals to Run that the +// test methods on the provided fixture +// instance can be executed in parallel +// with each other. This option assumes +// that `go test` was invoked with the +// -parallel flag. +func (singleton) ParallelTests() Option { + return func(c *config) { + c.parallelTests = true + c.freshFixture = true + Options.FreshFixture()(c) + } +} + +// UnitTests signals to Run that the test +// suite can be treated as a unit-test suite +// by employing parallelism and fresh fixtures +// to maximize the chances of exposing +// unwanted coupling between tests. +func (singleton) UnitTests() Option { + return func(c *config) { + Options.ParallelTests()(c) + Options.ParallelFixture()(c) + } +} + +// IntegrationTests is a composite option that +// signals to Run that the test suite should be +// treated as an integration test suite, avoiding +// parallelism and utilizing shared fixtures to +// allow reuse of potentially expensive resources. +func (singleton) IntegrationTests() Option { + return func(c *config) { + Options.SharedFixture()(c) + } +} + +var defaultOptions = []Option{ + Options.UnitTests(), +} diff --git a/v2/panic_test.go b/v2/panic_test.go new file mode 100644 index 0000000..2e5e17a --- /dev/null +++ b/v2/panic_test.go @@ -0,0 +1,49 @@ +package gunit + +import ( + "strings" + "testing" +) + +func TestPanicReport(t *testing.T) { + actualStackTrace := panicReport("boink", []byte(rawStackTrace)) + if actualStackTrace != expectedStackTrace { + t.Error(actualStackTrace) + } +} + +var rawStackTrace = strings.TrimSpace(` +runtime/debug.Stack() + /usr/local/go/src/runtime/debug/stack.go:24 +0x5e +github.com/smarty/gunit/v2/should.testCase.runTest.func1() + /Users/mike/src/github.com/smarty/gunit/v2/should/run.go:139 +0xce +panic({0x10720340?, 0x10762000?}) + /usr/local/go/src/runtime/panic.go:770 +0x132 +github.com/smarty/gunit/v2/examples/bowling.(*game).calculateScore(...) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling.go:15 +github.com/smarty/gunit/v2/examples/bowling.(*GameFixture).assertScore(...) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling_test.go:22 +github.com/smarty/gunit/v2/examples/bowling.(*GameFixture).TestAllOnes(0x0?) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling_test.go:40 +0x5b +reflect.Value.call({0x1075d540?, 0xc000025100?, 0xc000025100?}, {0x106bf18b, 0x4}, {0x0, 0x0, 0x10766658?}) + /usr/local/go/src/reflect/value.go:596 +0xce5 +reflect.Value.Call({0x1075d540?, 0xc000025100?, 0x603?}, {0x0?, 0xc000054678?, 0x10897a60?}) + /usr/local/go/src/reflect/value.go:380 +0xb9 +github.com/smarty/gunit/v2/should.testCase.runTest({0xc000108680, {0x10710a0c, 0xb}, 0xc000012330, 0x0, {0x10766658, 0x1075d540}, {0x1075d540, 0xc000024350, 0x16}}, ...) + /Users/mike/src/github.com/smarty/gunit/v2/should/run.go:162 +0x2b1 +testing.tRunner(0xc000108ea0, 0xc00002e720) + /usr/local/go/src/testing/testing.go:1689 +0xfb +created by testing.(*T).Run in goroutine 6 + /usr/local/go/src/testing/testing.go:1742 +0x390 +`) + +var expectedStackTrace = strings.TrimSpace(` +PANIC: boink +... +github.com/smarty/gunit/v2/examples/bowling.(*game).calculateScore(...) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling.go:15 +github.com/smarty/gunit/v2/examples/bowling.(*GameFixture).assertScore(...) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling_test.go:22 +github.com/smarty/gunit/v2/examples/bowling.(*GameFixture).TestAllOnes(0x0?) + /Users/mike/src/github.com/smarty/gunit/v2/examples/bowling/bowling_test.go:40 +0x5b +`) diff --git a/v2/should/assert_test.go b/v2/should/assert_test.go new file mode 100644 index 0000000..56ada4a --- /dev/null +++ b/v2/should/assert_test.go @@ -0,0 +1,60 @@ +package should_test + +import ( + "errors" + "fmt" + "path/filepath" + "runtime" + "testing" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/should" +) + +type Assertion struct{ *testing.T } + +func NewAssertion(t *testing.T) *Assertion { + return &Assertion{T: t} +} +func (this *Assertion) ExpectedCountInvalid(actual any, assertion gunit.Assertion, expected ...any) { + this.Helper() + this.err(actual, assertion, expected, should.ErrExpectedCountInvalid) +} +func (this *Assertion) TypeMismatch(actual any, assertion gunit.Assertion, expected ...any) { + this.Helper() + this.err(actual, assertion, expected, should.ErrTypeMismatch) +} +func (this *Assertion) KindMismatch(actual any, assertion gunit.Assertion, expected ...any) { + this.Helper() + this.err(actual, assertion, expected, should.ErrKindMismatch) +} +func (this *Assertion) Fail(actual any, assertion gunit.Assertion, expected ...any) { + this.Helper() + this.err(actual, assertion, expected, should.ErrAssertionFailure) +} +func (this *Assertion) Pass(actual any, assertion gunit.Assertion, expected ...any) { + this.Helper() + this.err(actual, assertion, expected, nil) +} +func (this *Assertion) err(actual any, assertion gunit.Assertion, expected []any, expectedErr error) { + this.Helper() + _, file, line, _ := runtime.Caller(2) + subTest := fmt.Sprintf("%s:%d", filepath.Base(file), line) + this.Run(subTest, func(t *testing.T) { + t.Helper() + err := assertion(actual, expected...) + if !errors.Is(err, expectedErr) { + t.Errorf("[FAIL]\n"+ + "expected: %v\n"+ + "actual: %v", + expected, + actual, + ) + } else if testing.Verbose() { + t.Log( + "\n", err, "\n", + "(above error report printed for visual inspection)", + ) + } + }) +} diff --git a/v2/should/be_chronological.go b/v2/should/be_chronological.go new file mode 100644 index 0000000..81b91ea --- /dev/null +++ b/v2/should/be_chronological.go @@ -0,0 +1,40 @@ +package should + +import ( + "errors" + "sort" + "time" +) + +// BeChronological asserts whether actual is a []time.Time and +// whether the values are in chronological order. +func BeChronological(actual any, expected ...any) error { + err := validateExpected(0, expected) + if err != nil { + return err + } + + var t []time.Time + err = validateType(actual, t) + if err != nil { + return err + } + + times := actual.([]time.Time) + if sort.SliceIsSorted(times, func(i, j int) bool { return times[i].Before(times[j]) }) { + return nil + } + return failure("expected to be chronological: %v", times) +} + +// BeChronological (negated!) +func (negated) BeChronological(actual any, expected ...any) error { + err := BeChronological(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + if err != nil { + return err + } + return failure("want non-chronological times, got chronological times:", actual) +} diff --git a/v2/should/be_chronological_test.go b/v2/should/be_chronological_test.go new file mode 100644 index 0000000..bd9ddde --- /dev/null +++ b/v2/should/be_chronological_test.go @@ -0,0 +1,44 @@ +package should_test + +import ( + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeChronological(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeChronological, "EXTRA") + + assert.TypeMismatch(42, should.BeChronological) + + var ( + a = time.Now() + b = a.Add(time.Nanosecond) + c = b.Add(time.Nanosecond) + ) + assert.Pass([]time.Time{}, should.BeChronological) + assert.Pass([]time.Time{a, a, a}, should.BeChronological) + assert.Pass([]time.Time{a, b, c}, should.BeChronological) + assert.Fail([]time.Time{a, c, b}, should.BeChronological) +} + +func TestShouldNOTBeChronological(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.BeChronological, "EXTRA") + + assert.TypeMismatch(42, should.NOT.BeChronological) + + var ( + a = time.Now() + b = a.Add(time.Nanosecond) + c = b.Add(time.Nanosecond) + ) + assert.Fail([]time.Time{}, should.NOT.BeChronological) + assert.Fail([]time.Time{a, a, a}, should.NOT.BeChronological) + assert.Fail([]time.Time{a, b, c}, should.NOT.BeChronological) + assert.Pass([]time.Time{a, c, b}, should.NOT.BeChronological) +} diff --git a/v2/should/be_empty.go b/v2/should/be_empty.go new file mode 100644 index 0000000..1c80847 --- /dev/null +++ b/v2/should/be_empty.go @@ -0,0 +1,40 @@ +package should + +import ( + "errors" + "reflect" +) + +// BeEmpty uses reflection to verify that len(actual) == 0. +func BeEmpty(actual any, expected ...any) error { + err := validateExpected(0, expected) + if err != nil { + return err + } + + err = validateKind(actual, kindsWithLength...) + if err != nil { + return err + } + + length := reflect.ValueOf(actual).Len() + if length == 0 { + return nil + } + + TYPE := reflect.TypeOf(actual).String() + return failure("got len(%s) == %d, want empty %s", TYPE, length, TYPE) +} + +// BeEmpty (negated!) +func (negated) BeEmpty(actual any, expected ...any) error { + err := BeEmpty(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + if err != nil { + return err + } + TYPE := reflect.TypeOf(actual).String() + return failure("got empty %s, want non-empty %s", TYPE, TYPE) +} diff --git a/v2/should/be_empty_test.go b/v2/should/be_empty_test.go new file mode 100644 index 0000000..c8a1df3 --- /dev/null +++ b/v2/should/be_empty_test.go @@ -0,0 +1,72 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeEmpty(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeEmpty, "EXTRA") + + assert.KindMismatch(42, should.BeEmpty) + + assert.Pass([]string(nil), should.BeEmpty) + assert.Pass(make([]string, 0, 0), should.BeEmpty) + assert.Pass(make([]string, 0, 1), should.BeEmpty) + assert.Fail([]string{""}, should.BeEmpty) + + assert.Pass([0]string{}, should.BeEmpty) // The only possible empty array! + assert.Fail([1]string{}, should.BeEmpty) + + assert.Pass(chan string(nil), should.BeEmpty) + assert.Pass(make(chan string), should.BeEmpty) + assert.Pass(make(chan string, 1), should.BeEmpty) + assert.Fail(nonEmptyChannel(), should.BeEmpty) + + assert.Pass(map[string]string(nil), should.BeEmpty) + assert.Pass(make(map[string]string), should.BeEmpty) + assert.Pass(make(map[string]string, 1), should.BeEmpty) + assert.Fail(map[string]string{"": ""}, should.BeEmpty) + + assert.Pass("", should.BeEmpty) + assert.Pass(*new(string), should.BeEmpty) + assert.Fail(" ", should.BeEmpty) +} + +func TestShouldNotBeEmpty(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.BeEmpty, "EXTRA") + assert.KindMismatch(42, should.NOT.BeEmpty) + + assert.Fail([]string(nil), should.NOT.BeEmpty) + assert.Fail(make([]string, 0, 0), should.NOT.BeEmpty) + assert.Fail(make([]string, 0, 1), should.NOT.BeEmpty) + assert.Pass([]string{""}, should.NOT.BeEmpty) + + assert.Fail([0]string{}, should.NOT.BeEmpty) + assert.Pass([1]string{}, should.NOT.BeEmpty) + + assert.Fail(chan string(nil), should.NOT.BeEmpty) + assert.Fail(make(chan string), should.NOT.BeEmpty) + assert.Fail(make(chan string, 1), should.NOT.BeEmpty) + assert.Pass(nonEmptyChannel(), should.NOT.BeEmpty) + + assert.Fail(map[string]string(nil), should.NOT.BeEmpty) + assert.Fail(make(map[string]string), should.NOT.BeEmpty) + assert.Fail(make(map[string]string, 1), should.NOT.BeEmpty) + assert.Pass(map[string]string{"": ""}, should.NOT.BeEmpty) + + assert.Fail("", should.NOT.BeEmpty) + assert.Fail(*new(string), should.NOT.BeEmpty) + assert.Pass(" ", should.NOT.BeEmpty) +} + +func nonEmptyChannel() chan string { + c := make(chan string, 1) + c <- "" + return c +} diff --git a/v2/should/be_false.go b/v2/should/be_false.go new file mode 100644 index 0000000..39721c0 --- /dev/null +++ b/v2/should/be_false.go @@ -0,0 +1,21 @@ +package should + +// BeFalse verifies that actual is the boolean false value. +func BeFalse(actual any, expected ...any) error { + err := validateExpected(0, expected) + if err != nil { + return err + } + + err = validateType(actual, *new(bool)) + if err != nil { + return err + } + + boolean := actual.(bool) + if boolean { + return failure("got , want ") + } + + return nil +} diff --git a/v2/should/be_false_test.go b/v2/should/be_false_test.go new file mode 100644 index 0000000..0815244 --- /dev/null +++ b/v2/should/be_false_test.go @@ -0,0 +1,17 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeFalse(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeFalse, "EXTRA") + assert.TypeMismatch(1, should.BeFalse) + + assert.Fail(true, should.BeFalse) + assert.Pass(false, should.BeFalse) +} diff --git a/v2/should/be_greater_than.go b/v2/should/be_greater_than.go new file mode 100644 index 0000000..d5d192b --- /dev/null +++ b/v2/should/be_greater_than.go @@ -0,0 +1,37 @@ +package should + +import "errors" + +// BeGreaterThan verifies that actual is greater than expected. +// Both actual and expected must be strings or numeric in type. +func BeGreaterThan(actual any, EXPECTED ...any) error { + lessThanErr := BeLessThan(actual, EXPECTED...) + if errors.Is(lessThanErr, ErrTypeMismatch) || errors.Is(lessThanErr, ErrExpectedCountInvalid) { + return lessThanErr + } + equalityErr := Equal(actual, EXPECTED...) + if lessThanErr == nil || equalityErr == nil { + return failure("%v was not greater than %v", actual, EXPECTED[0]) + } + return nil +} + +// BeGreaterThan negated! +func (negated) BeGreaterThan(actual any, expected ...any) error { + err := BeGreaterThan(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not be greater than: %#v\n"+ + " (but it was)", + expected[0], + actual, + ) +} diff --git a/v2/should/be_greater_than_or_equal_to.go b/v2/should/be_greater_than_or_equal_to.go new file mode 100644 index 0000000..7f1fcc2 --- /dev/null +++ b/v2/should/be_greater_than_or_equal_to.go @@ -0,0 +1,41 @@ +package should + +import "errors" + +// BeGreaterThanOrEqualTo verifies that actual is less than or equal to expected. +// Both actual and expected must be strings or numeric in type. +func BeGreaterThanOrEqualTo(actual any, expected ...any) error { + err := Equal(actual, expected...) + if err == nil { + return nil + } + err = BeGreaterThan(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return failure("%v was not greater than or equal to %v", actual, expected) + } + + if err != nil { + return err + } + return nil +} + +// BeGreaterThanOrEqualTo negated! +func (negated) BeGreaterThanOrEqualTo(actual any, expected ...any) error { + err := BeGreaterThanOrEqualTo(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not be greater than or equal to: %#v\n"+ + " (but it was)", + expected[0], + actual, + ) +} diff --git a/v2/should/be_greater_than_or_equal_to_test.go b/v2/should/be_greater_than_or_equal_to_test.go new file mode 100644 index 0000000..9693599 --- /dev/null +++ b/v2/should/be_greater_than_or_equal_to_test.go @@ -0,0 +1,113 @@ +package should_test + +import ( + "math" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeGreaterThanOrEqualTo(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.BeGreaterThanOrEqualTo) + assert.ExpectedCountInvalid("actual", should.BeGreaterThanOrEqualTo, "expected", "required") + assert.TypeMismatch(true, should.BeGreaterThanOrEqualTo, 1) + assert.TypeMismatch(1, should.BeGreaterThanOrEqualTo, true) + + assert.Fail("a", should.BeGreaterThanOrEqualTo, "b") // both strings + assert.Pass("b", should.BeGreaterThanOrEqualTo, "a") + + assert.Pass(2, should.BeGreaterThanOrEqualTo, 1) // both ints + assert.Pass(1, should.BeGreaterThanOrEqualTo, 1) + assert.Fail(1, should.BeGreaterThanOrEqualTo, 2) + + assert.Pass(float32(2.0), should.BeGreaterThanOrEqualTo, float64(1)) // both floats + assert.Pass(float32(2.0), should.BeGreaterThanOrEqualTo, float64(2)) + assert.Fail(1.0, should.BeGreaterThanOrEqualTo, 2.0) + + assert.Pass(int32(2), should.BeGreaterThanOrEqualTo, int64(1)) // both signed + assert.Pass(int32(2), should.BeGreaterThanOrEqualTo, int64(2)) + assert.Fail(int32(1), should.BeGreaterThanOrEqualTo, int64(2)) + + assert.Pass(uint32(2), should.BeGreaterThanOrEqualTo, uint64(1)) // both unsigned + assert.Pass(uint32(2), should.BeGreaterThanOrEqualTo, uint64(2)) + assert.Fail(uint32(1), should.BeGreaterThanOrEqualTo, uint64(2)) + + assert.Pass(int32(2), should.BeGreaterThanOrEqualTo, uint32(1)) // signed and unsigned + assert.Pass(int32(2), should.BeGreaterThanOrEqualTo, uint32(2)) + assert.Fail(int32(1), should.BeGreaterThanOrEqualTo, uint32(2)) + // if actual < 0: false + // (because by definition the expected value, an unsigned value must be >= 0) + const reallyBig uint64 = math.MaxUint64 + assert.Fail(-1, should.BeGreaterThanOrEqualTo, reallyBig) + + assert.Pass(uint32(2), should.BeGreaterThanOrEqualTo, int32(1)) // unsigned and signed + assert.Pass(uint32(2), should.BeGreaterThanOrEqualTo, int32(2)) + assert.Fail(uint32(1), should.BeGreaterThanOrEqualTo, int32(2)) + // if actual > math.MaxInt64: true + // (because by definition the expected value, a signed value must be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Pass(tooBig, should.BeGreaterThanOrEqualTo, 42) + + assert.Pass(2.0, should.BeGreaterThanOrEqualTo, 1) // float and integer + assert.Pass(2.0, should.BeGreaterThanOrEqualTo, 2) + assert.Fail(1.0, should.BeGreaterThanOrEqualTo, 2) + + assert.Pass(2, should.BeGreaterThanOrEqualTo, 1.0) // integer and float + assert.Pass(2, should.BeGreaterThanOrEqualTo, 2.0) + assert.Fail(1, should.BeGreaterThanOrEqualTo, 2.0) +} + +func TestShouldNOTBeGreaterThanOrEqualTo(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.NOT.BeGreaterThanOrEqualTo) + assert.ExpectedCountInvalid("actual", should.NOT.BeGreaterThanOrEqualTo, "expected", "required") + assert.TypeMismatch(true, should.NOT.BeGreaterThanOrEqualTo, 1) + assert.TypeMismatch(1, should.NOT.BeGreaterThanOrEqualTo, true) + + assert.Pass("a", should.NOT.BeGreaterThanOrEqualTo, "b") // both strings + assert.Fail("a", should.NOT.BeGreaterThanOrEqualTo, "a") + assert.Fail("b", should.NOT.BeGreaterThanOrEqualTo, "a") + + assert.Pass(1, should.NOT.BeGreaterThanOrEqualTo, 2) // both ints + assert.Fail(1, should.NOT.BeGreaterThanOrEqualTo, 1) + assert.Fail(2, should.NOT.BeGreaterThanOrEqualTo, 1) + + assert.Fail(float32(2.0), should.NOT.BeGreaterThanOrEqualTo, float64(1)) // both floats + assert.Fail(float32(2.0), should.NOT.BeGreaterThanOrEqualTo, float64(2)) + assert.Pass(1.0, should.NOT.BeGreaterThanOrEqualTo, 2.0) + + assert.Fail(int32(2), should.NOT.BeGreaterThanOrEqualTo, int64(1)) // both signed + assert.Fail(int32(2), should.NOT.BeGreaterThanOrEqualTo, int64(2)) + assert.Pass(int32(1), should.NOT.BeGreaterThanOrEqualTo, int64(2)) + + assert.Fail(uint32(2), should.NOT.BeGreaterThanOrEqualTo, uint64(1)) // both unsigned + assert.Fail(uint32(2), should.NOT.BeGreaterThanOrEqualTo, uint64(2)) + assert.Pass(uint32(1), should.NOT.BeGreaterThanOrEqualTo, uint64(2)) + + assert.Fail(int32(2), should.NOT.BeGreaterThanOrEqualTo, uint32(1)) // signed and unsigned + assert.Fail(int32(2), should.NOT.BeGreaterThanOrEqualTo, uint32(2)) + assert.Pass(int32(1), should.NOT.BeGreaterThanOrEqualTo, uint32(2)) + // if actual < 0: true + // (because by definition the expected value, an unsigned value must be >= 0) + const reallyBig uint64 = math.MaxUint64 + assert.Pass(-1, should.NOT.BeGreaterThanOrEqualTo, reallyBig) + + assert.Fail(uint32(2), should.NOT.BeGreaterThanOrEqualTo, int32(1)) // unsigned and signed + assert.Fail(uint32(2), should.NOT.BeGreaterThanOrEqualTo, int32(2)) + assert.Pass(uint32(1), should.NOT.BeGreaterThanOrEqualTo, int32(2)) + // if actual > math.MaxInt64: false + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Fail(tooBig, should.NOT.BeGreaterThanOrEqualTo, 42) + + assert.Fail(2.0, should.NOT.BeGreaterThanOrEqualTo, 1) // float and integer + assert.Fail(2.0, should.NOT.BeGreaterThanOrEqualTo, 2) + assert.Pass(1.0, should.NOT.BeGreaterThanOrEqualTo, 2) + + assert.Fail(2, should.NOT.BeGreaterThanOrEqualTo, 1.0) // integer and float + assert.Fail(2, should.NOT.BeGreaterThanOrEqualTo, 2.0) + assert.Pass(1, should.NOT.BeGreaterThanOrEqualTo, 2.0) +} diff --git a/v2/should/be_greater_than_test.go b/v2/should/be_greater_than_test.go new file mode 100644 index 0000000..19434f2 --- /dev/null +++ b/v2/should/be_greater_than_test.go @@ -0,0 +1,96 @@ +package should_test + +import ( + "math" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeGreaterThan(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.BeGreaterThan) + assert.ExpectedCountInvalid("actual", should.BeGreaterThan, "expected", "required") + assert.TypeMismatch(true, should.BeGreaterThan, 1) + assert.TypeMismatch(1, should.BeGreaterThan, true) + + assert.Fail("a", should.BeGreaterThan, "b") // both strings + assert.Pass("b", should.BeGreaterThan, "a") + + assert.Fail(1, should.BeGreaterThan, 1) // both ints + assert.Pass(2, should.BeGreaterThan, 1) + + assert.Pass(float32(2.0), should.BeGreaterThan, float64(1)) // both floats + assert.Fail(1.0, should.BeGreaterThan, 2.0) + + assert.Pass(int32(2), should.BeGreaterThan, int64(1)) // both signed + assert.Fail(int32(1), should.BeGreaterThan, int64(2)) + + assert.Pass(uint32(2), should.BeGreaterThan, uint64(1)) // both unsigned + assert.Fail(uint32(1), should.BeGreaterThan, uint64(2)) + + assert.Pass(int32(2), should.BeGreaterThan, uint32(1)) // signed and unsigned + assert.Fail(int32(1), should.BeGreaterThan, uint32(2)) + // if actual < 0: false + // (because by definition the expected value, an unsigned value must be >= 0) + const reallyBig uint64 = math.MaxUint64 + assert.Fail(-1, should.BeGreaterThan, reallyBig) + + assert.Pass(uint32(2), should.BeGreaterThan, int32(1)) // unsigned and signed + assert.Fail(uint32(1), should.BeGreaterThan, int32(2)) + // if actual > math.MaxInt64: true + // (because by definition the expected value, a signed value must be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Pass(tooBig, should.BeGreaterThan, 42) + + assert.Pass(2.0, should.BeGreaterThan, 1) // float and integer + assert.Fail(1.0, should.BeGreaterThan, 2) + + assert.Pass(2, should.BeGreaterThan, 1.0) // integer and float + assert.Fail(1, should.BeGreaterThan, 2.0) +} + +func TestShouldNOTBeGreaterThan(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.NOT.BeGreaterThan) + assert.ExpectedCountInvalid("actual", should.NOT.BeGreaterThan, "expected", "required") + assert.TypeMismatch(true, should.NOT.BeGreaterThan, 1) + assert.TypeMismatch(1, should.NOT.BeGreaterThan, true) + + assert.Pass("a", should.NOT.BeGreaterThan, "b") // both strings + assert.Fail("b", should.NOT.BeGreaterThan, "a") + + assert.Pass(1, should.NOT.BeGreaterThan, 1) // both ints + assert.Fail(2, should.NOT.BeGreaterThan, 1) + + assert.Fail(float32(2.0), should.NOT.BeGreaterThan, float64(1)) // both floats + assert.Pass(1.0, should.NOT.BeGreaterThan, 2.0) + + assert.Fail(int32(2), should.NOT.BeGreaterThan, int64(1)) // both signed + assert.Pass(int32(1), should.NOT.BeGreaterThan, int64(2)) + + assert.Fail(uint32(2), should.NOT.BeGreaterThan, uint64(1)) // both unsigned + assert.Pass(uint32(1), should.NOT.BeGreaterThan, uint64(2)) + + assert.Fail(int32(2), should.NOT.BeGreaterThan, uint32(1)) // signed and unsigned + assert.Pass(int32(1), should.NOT.BeGreaterThan, uint32(2)) + // if actual < 0: true + // (because by definition the expected value, an unsigned value must be >= 0) + const reallyBig uint64 = math.MaxUint64 + assert.Pass(-1, should.NOT.BeGreaterThan, reallyBig) + + assert.Fail(uint32(2), should.NOT.BeGreaterThan, int32(1)) // unsigned and signed + assert.Pass(uint32(1), should.NOT.BeGreaterThan, int32(2)) + // if actual > math.MaxInt64: false + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Fail(tooBig, should.NOT.BeGreaterThan, 42) + + assert.Fail(2.0, should.NOT.BeGreaterThan, 1) // float and integer + assert.Pass(1.0, should.NOT.BeGreaterThan, 2) + + assert.Fail(2, should.NOT.BeGreaterThan, 1.0) // integer and float + assert.Pass(1, should.NOT.BeGreaterThan, 2.0) +} diff --git a/v2/should/be_in.go b/v2/should/be_in.go new file mode 100644 index 0000000..12143c5 --- /dev/null +++ b/v2/should/be_in.go @@ -0,0 +1,27 @@ +package should + +// BeIn determines whether actual is a member of expected[0]. +// It defers to Contain. +func BeIn(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + err = Contain(expected[0], actual) + if err != nil { + return err + } + + return nil +} + +// BeIn (negated!) +func (negated) BeIn(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + return NOT.Contain(expected[0], actual) +} diff --git a/v2/should/be_in_test.go b/v2/should/be_in_test.go new file mode 100644 index 0000000..1b5a2d1 --- /dev/null +++ b/v2/should/be_in_test.go @@ -0,0 +1,63 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeIn(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeIn) + assert.ExpectedCountInvalid("actual", should.BeIn, "EXPECTED", "EXTRA") + + assert.KindMismatch(false, should.BeIn, "string") + assert.KindMismatch("hi", should.BeIn, 1) + + // strings: + assert.Fail("no", should.BeIn, "") + assert.Pass("rat", should.BeIn, "integrate") + assert.Pass('b', should.BeIn, "abc") + + // slices: + assert.Fail('d', should.BeIn, []byte("abc")) + assert.Pass('b', should.BeIn, []byte("abc")) + assert.Pass(98, should.BeIn, []byte("abc")) + + // arrays: + assert.Fail('d', should.BeIn, [3]byte{'a', 'b', 'c'}) + assert.Pass('b', should.BeIn, [3]byte{'a', 'b', 'c'}) + assert.Pass(98, should.BeIn, [3]byte{'a', 'b', 'c'}) + + // maps: + assert.Fail('b', should.BeIn, map[rune]int{'a': 1}) + assert.Pass('a', should.BeIn, map[rune]int{'a': 1}) +} + +func TestShouldNotBeIn(t *testing.T) { + assert := NewAssertion(t) + assert.ExpectedCountInvalid("actual", should.NOT.BeIn) + assert.ExpectedCountInvalid("actual", should.NOT.BeIn, "EXPECTED", "EXTRA") + assert.KindMismatch(false, should.NOT.BeIn, "string") + assert.KindMismatch("hi", should.NOT.BeIn, 1) + + // strings: + assert.Pass("no", should.NOT.BeIn, "yes") + assert.Fail("rat", should.NOT.BeIn, "integrate") + assert.Fail('b', should.NOT.BeIn, "abc") + + // slices: + assert.Pass('d', should.NOT.BeIn, []byte("abc")) + assert.Fail('b', should.NOT.BeIn, []byte("abc")) + assert.Fail(98, should.NOT.BeIn, []byte("abc")) + + // arrays: + assert.Pass('d', should.NOT.BeIn, [3]byte{'a', 'b', 'c'}) + assert.Fail('b', should.NOT.BeIn, [3]byte{'a', 'b', 'c'}) + assert.Fail(98, should.NOT.BeIn, [3]byte{'a', 'b', 'c'}) + + // maps: + assert.Pass('b', should.NOT.BeIn, map[rune]int{'a': 1}) + assert.Fail('a', should.NOT.BeIn, map[rune]int{'a': 1}) +} diff --git a/v2/should/be_less_than.go b/v2/should/be_less_than.go new file mode 100644 index 0000000..5429428 --- /dev/null +++ b/v2/should/be_less_than.go @@ -0,0 +1,160 @@ +package should + +import ( + "errors" + "math" + "reflect" + "time" +) + +// BeLessThan verifies that actual is less than expected. +// Both actual and expected must be strings or numeric in type. +func BeLessThan(actual any, EXPECTED ...any) error { + err := validateExpected(1, EXPECTED) + if err != nil { + return err + } + + expected := EXPECTED[0] + failed := false + + for _, spec := range lessThanSpecs { + if !spec.assertable(actual, expected) { + continue + } + if spec.passes(actual, expected) { + return nil + } + failed = true + break + } + + if failed { + return failure("%v was not less than %v", actual, expected) + } + return wrap(ErrTypeMismatch, "could not compare [%v] and [%v]", + reflect.TypeOf(actual), reflect.TypeOf(expected)) +} + +// BeLessThan negated! +func (negated) BeLessThan(actual any, expected ...any) error { + err := BeLessThan(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not be less than: %#v\n"+ + " (but it was)", + expected[0], + actual, + ) +} + +var lessThanSpecs = []specification{ + bothStringsLessThan{}, + bothSignedIntegersLessThan{}, + bothUnsignedIntegersLessThan{}, + bothFloatsLessThan{}, + signedAndUnsignedLessThan{}, + unsignedAndSignedLessThan{}, + floatAndIntegerLessThan{}, + integerAndFloatLessThan{}, + bothTimesLessThan{}, +} + +type bothStringsLessThan struct{} + +func (bothStringsLessThan) assertable(a, b any) bool { + return reflect.ValueOf(a).Kind() == reflect.String && reflect.ValueOf(b).Kind() == reflect.String +} +func (bothStringsLessThan) passes(a, b any) bool { + return reflect.ValueOf(a).String() < reflect.ValueOf(b).String() +} + +type bothSignedIntegersLessThan struct{} + +func (bothSignedIntegersLessThan) assertable(a, b any) bool { + return isSignedInteger(a) && isSignedInteger(b) +} +func (bothSignedIntegersLessThan) passes(a, b any) bool { + return reflect.ValueOf(a).Int() < reflect.ValueOf(b).Int() +} + +type bothUnsignedIntegersLessThan struct{} + +func (bothUnsignedIntegersLessThan) assertable(a, b any) bool { + return isUnsignedInteger(a) && isUnsignedInteger(b) +} +func (bothUnsignedIntegersLessThan) passes(a, b any) bool { + return reflect.ValueOf(a).Uint() < reflect.ValueOf(b).Uint() +} + +type bothFloatsLessThan struct{} + +func (bothFloatsLessThan) assertable(a, b any) bool { + return isFloat(a) && isFloat(b) +} +func (bothFloatsLessThan) passes(a, b any) bool { + return reflect.ValueOf(a).Float() < reflect.ValueOf(b).Float() +} + +type signedAndUnsignedLessThan struct{} + +func (signedAndUnsignedLessThan) assertable(a, b any) bool { + return isSignedInteger(a) && isUnsignedInteger(b) +} +func (signedAndUnsignedLessThan) passes(a, b any) bool { + A := reflect.ValueOf(a) + B := reflect.ValueOf(b) + if A.Int() < 0 { + return true + } + return uint64(A.Int()) < B.Uint() +} + +type unsignedAndSignedLessThan struct{} + +func (unsignedAndSignedLessThan) assertable(a, b any) bool { + return isUnsignedInteger(a) && isSignedInteger(b) +} +func (unsignedAndSignedLessThan) passes(a, b any) bool { + A := reflect.ValueOf(a) + B := reflect.ValueOf(b) + if A.Uint() > math.MaxInt64 { + return false + } + return int64(A.Uint()) < B.Int() +} + +type floatAndIntegerLessThan struct{} + +func (floatAndIntegerLessThan) assertable(a, b any) bool { + return isFloat(a) && isInteger(b) +} +func (floatAndIntegerLessThan) passes(a, b any) bool { + return asFloat(a) < asFloat(b) +} + +type integerAndFloatLessThan struct{} + +func (integerAndFloatLessThan) assertable(a, b any) bool { + return isInteger(a) && isFloat(b) +} +func (integerAndFloatLessThan) passes(a, b any) bool { + return asFloat(a) < asFloat(b) +} + +type bothTimesLessThan struct{} + +func (bothTimesLessThan) assertable(a, b any) bool { + return isTime(a) && isTime(b) +} +func (bothTimesLessThan) passes(a, b any) bool { + return a.(time.Time).Before(b.(time.Time)) +} diff --git a/v2/should/be_less_than_or_equal_to.go b/v2/should/be_less_than_or_equal_to.go new file mode 100644 index 0000000..34a93f8 --- /dev/null +++ b/v2/should/be_less_than_or_equal_to.go @@ -0,0 +1,41 @@ +package should + +import "errors" + +// BeLessThanOrEqualTo verifies that actual is less than or equal to expected. +// Both actual and expected must be strings or numeric in type. +func BeLessThanOrEqualTo(actual any, expected ...any) error { + err := Equal(actual, expected...) + if err == nil { + return nil + } + err = BeLessThan(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return failure("%v was not less than or equal to %v", actual, expected) + } + + if err != nil { + return err + } + return nil +} + +// BeLessThanOrEqualTo negated! +func (negated) BeLessThanOrEqualTo(actual any, expected ...any) error { + err := BeLessThanOrEqualTo(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not be less than or equal to: %#v\n"+ + " (but it was)", + expected[0], + actual, + ) +} diff --git a/v2/should/be_less_than_or_equal_to_test.go b/v2/should/be_less_than_or_equal_to_test.go new file mode 100644 index 0000000..082b20e --- /dev/null +++ b/v2/should/be_less_than_or_equal_to_test.go @@ -0,0 +1,116 @@ +package should_test + +import ( + "math" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeLessThanOrEqualTo(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.BeLessThanOrEqualTo) + assert.ExpectedCountInvalid("actual", should.BeLessThanOrEqualTo, "expected", "required") + assert.TypeMismatch(true, should.BeLessThanOrEqualTo, 1) + assert.TypeMismatch(1, should.BeLessThanOrEqualTo, true) + + assert.Fail("b", should.BeLessThanOrEqualTo, "a") // both strings + assert.Pass("a", should.BeLessThanOrEqualTo, "b") + assert.Pass("a", should.BeLessThanOrEqualTo, "a") + + assert.Fail(2, should.BeLessThanOrEqualTo, 1) // both ints + assert.Pass(1, should.BeLessThanOrEqualTo, 2) + assert.Pass(1, should.BeLessThanOrEqualTo, 1) + + assert.Pass(float32(1.0), should.BeLessThanOrEqualTo, float64(2)) // both floats + assert.Fail(2.0, should.BeLessThanOrEqualTo, 1.0) + assert.Pass(2.0, should.BeLessThanOrEqualTo, 2.0) + + assert.Pass(int32(1), should.BeLessThanOrEqualTo, int64(2)) // both signed + assert.Fail(int32(2), should.BeLessThanOrEqualTo, int64(1)) + assert.Pass(int32(2), should.BeLessThanOrEqualTo, int64(2)) + + assert.Pass(uint32(1), should.BeLessThanOrEqualTo, uint64(2)) // both unsigned + assert.Fail(uint32(2), should.BeLessThanOrEqualTo, uint64(1)) + assert.Pass(uint32(2), should.BeLessThanOrEqualTo, uint64(2)) + + assert.Pass(int32(1), should.BeLessThanOrEqualTo, uint32(2)) // signed and unsigned + assert.Fail(int32(2), should.BeLessThanOrEqualTo, uint32(1)) + assert.Pass(int32(2), should.BeLessThanOrEqualTo, uint32(2)) + // if actual < 0: true + // (because by definition the expected value, an unsigned value can't be < 0) + const reallyBig uint64 = math.MaxUint64 + assert.Pass(-1, should.BeLessThanOrEqualTo, reallyBig) + + assert.Pass(uint32(1), should.BeLessThanOrEqualTo, int32(2)) // unsigned and signed + assert.Fail(uint32(2), should.BeLessThanOrEqualTo, int32(1)) + assert.Pass(uint32(2), should.BeLessThanOrEqualTo, int32(2)) + // if actual > math.MaxInt64: false + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Fail(tooBig, should.BeLessThanOrEqualTo, 42) + + assert.Pass(1.0, should.BeLessThanOrEqualTo, 2) // float and integer + assert.Fail(2.0, should.BeLessThanOrEqualTo, 1) + assert.Pass(2.0, should.BeLessThanOrEqualTo, 2) + + assert.Pass(1, should.BeLessThanOrEqualTo, 2.0) // integer and float + assert.Fail(2, should.BeLessThanOrEqualTo, 1.0) + assert.Pass(2, should.BeLessThanOrEqualTo, 2.0) + +} + +func TestShouldNotBeLessThanOrEqualTo(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.NOT.BeLessThanOrEqualTo) + assert.ExpectedCountInvalid("actual", should.NOT.BeLessThanOrEqualTo, "expected", "required") + assert.TypeMismatch(true, should.NOT.BeLessThanOrEqualTo, 1) + assert.TypeMismatch(1, should.NOT.BeLessThanOrEqualTo, true) + + assert.Pass("b", should.NOT.BeLessThanOrEqualTo, "a") // both strings + assert.Fail("a", should.NOT.BeLessThanOrEqualTo, "b") + assert.Fail("a", should.NOT.BeLessThanOrEqualTo, "a") + + assert.Pass(2, should.NOT.BeLessThanOrEqualTo, 1) // both ints + assert.Fail(1, should.NOT.BeLessThanOrEqualTo, 2) + assert.Fail(1, should.NOT.BeLessThanOrEqualTo, 1) + + assert.Fail(float32(1.0), should.NOT.BeLessThanOrEqualTo, float64(2)) // both floats + assert.Pass(2.0, should.NOT.BeLessThanOrEqualTo, 1.0) + assert.Fail(2.0, should.NOT.BeLessThanOrEqualTo, 2.0) + + assert.Fail(int32(1), should.NOT.BeLessThanOrEqualTo, int64(2)) // both signed + assert.Pass(int32(2), should.NOT.BeLessThanOrEqualTo, int64(1)) + assert.Fail(int32(2), should.NOT.BeLessThanOrEqualTo, int64(2)) + + assert.Fail(uint32(1), should.NOT.BeLessThanOrEqualTo, uint64(2)) // both unsigned + assert.Pass(uint32(2), should.NOT.BeLessThanOrEqualTo, uint64(1)) + assert.Fail(uint32(2), should.NOT.BeLessThanOrEqualTo, uint64(2)) + + assert.Fail(int32(1), should.NOT.BeLessThanOrEqualTo, uint32(2)) // signed and unsigned + assert.Pass(int32(2), should.NOT.BeLessThanOrEqualTo, uint32(1)) + assert.Fail(int32(2), should.NOT.BeLessThanOrEqualTo, uint32(2)) + // if actual < 0: true + // (because by definition the expected value, an unsigned value can't be < 0) + const reallyBig uint64 = math.MaxUint64 + assert.Fail(-1, should.NOT.BeLessThanOrEqualTo, reallyBig) + + assert.Fail(uint32(1), should.NOT.BeLessThanOrEqualTo, int32(2)) // unsigned and signed + assert.Pass(uint32(2), should.NOT.BeLessThanOrEqualTo, int32(1)) + assert.Fail(uint32(2), should.NOT.BeLessThanOrEqualTo, int32(2)) + // if actual > math.MaxInt64: false + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Pass(tooBig, should.NOT.BeLessThanOrEqualTo, 42) + + assert.Fail(1.0, should.NOT.BeLessThanOrEqualTo, 2) // float and integer + assert.Pass(2.0, should.NOT.BeLessThanOrEqualTo, 1) + assert.Fail(2.0, should.NOT.BeLessThanOrEqualTo, 2) + + assert.Fail(1, should.NOT.BeLessThanOrEqualTo, 2.0) // integer and float + assert.Pass(2, should.NOT.BeLessThanOrEqualTo, 1.0) + assert.Fail(2, should.NOT.BeLessThanOrEqualTo, 2.0) + +} diff --git a/v2/should/be_less_than_test.go b/v2/should/be_less_than_test.go new file mode 100644 index 0000000..0e537b7 --- /dev/null +++ b/v2/should/be_less_than_test.go @@ -0,0 +1,102 @@ +package should_test + +import ( + "math" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeLessThan(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.BeLessThan) + assert.ExpectedCountInvalid("actual", should.BeLessThan, "expected", "required") + assert.TypeMismatch(true, should.BeLessThan, 1) + assert.TypeMismatch(1, should.BeLessThan, true) + + assert.Fail("b", should.BeLessThan, "a") // both strings + assert.Pass("a", should.BeLessThan, "b") + + assert.Fail(1, should.BeLessThan, 1) // both ints + assert.Pass(1, should.BeLessThan, 2) + + assert.Pass(float32(1.0), should.BeLessThan, float64(2)) // both floats + assert.Fail(2.0, should.BeLessThan, 1.0) + + assert.Pass(int32(1), should.BeLessThan, int64(2)) // both signed + assert.Fail(int32(2), should.BeLessThan, int64(1)) + + assert.Pass(uint32(1), should.BeLessThan, uint64(2)) // both unsigned + assert.Fail(uint32(2), should.BeLessThan, uint64(1)) + + assert.Pass(int32(1), should.BeLessThan, uint32(2)) // signed and unsigned + assert.Fail(int32(2), should.BeLessThan, uint32(1)) + // if actual < 0: true + // (because by definition the expected value, an unsigned value can't be < 0) + const reallyBig uint64 = math.MaxUint64 + assert.Pass(-1, should.BeLessThan, reallyBig) + + assert.Pass(uint32(1), should.BeLessThan, int32(2)) // unsigned and signed + assert.Fail(uint32(2), should.BeLessThan, int32(1)) + // if actual > math.MaxInt64: false + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Fail(tooBig, should.BeLessThan, 42) + + assert.Pass(1.0, should.BeLessThan, 2) // float and integer + assert.Fail(2.0, should.BeLessThan, 1) + + assert.Pass(1.0, should.BeLessThan, uint(2)) // float and unsigned integer + assert.Fail(2.0, should.BeLessThan, uint(1)) + + assert.Pass(1, should.BeLessThan, 2.0) // integer and float + assert.Fail(2, should.BeLessThan, 1.0) + + assert.Pass(uint(1), should.BeLessThan, 2.0) // unsigned integer and float + assert.Fail(uint(2), should.BeLessThan, 1.0) +} + +func TestShouldNOTBeLessThan(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual-but-missing-expected", should.NOT.BeLessThan) + assert.ExpectedCountInvalid("actual", should.NOT.BeLessThan, "expected", "required") + assert.TypeMismatch(true, should.NOT.BeLessThan, 1) + assert.TypeMismatch(1, should.NOT.BeLessThan, true) + + assert.Pass("b", should.NOT.BeLessThan, "a") // both strings + assert.Fail("a", should.NOT.BeLessThan, "b") + + assert.Pass(1, should.NOT.BeLessThan, 1) // both ints + assert.Fail(1, should.NOT.BeLessThan, 2) + + assert.Fail(float32(1.0), should.NOT.BeLessThan, float64(2)) // both floats + assert.Pass(2.0, should.NOT.BeLessThan, 1.0) + + assert.Fail(int32(1), should.NOT.BeLessThan, int64(2)) // both signed + assert.Pass(int32(2), should.NOT.BeLessThan, int64(1)) + + assert.Fail(uint32(1), should.NOT.BeLessThan, uint64(2)) // both unsigned + assert.Pass(uint32(2), should.NOT.BeLessThan, uint64(1)) + + assert.Fail(int32(1), should.NOT.BeLessThan, uint32(2)) // signed and unsigned + assert.Pass(int32(2), should.NOT.BeLessThan, uint32(1)) + // if actual < 0: false + // (because by definition the expected value, an unsigned value can't be < 0) + const reallyBig uint64 = math.MaxUint64 + assert.Fail(-1, should.NOT.BeLessThan, reallyBig) + + assert.Fail(uint32(1), should.NOT.BeLessThan, int32(2)) // unsigned and signed + assert.Pass(uint32(2), should.NOT.BeLessThan, int32(1)) + // if actual > math.MaxInt64: true + // (because by definition the expected value, a signed value can't be > math.MaxInt64) + const tooBig uint64 = math.MaxInt64 + 1 + assert.Pass(tooBig, should.NOT.BeLessThan, 42) + + assert.Fail(1.0, should.NOT.BeLessThan, 2) // float and integer + assert.Pass(2.0, should.NOT.BeLessThan, 1) + + assert.Fail(1, should.NOT.BeLessThan, 2.0) // integer and float + assert.Pass(2, should.NOT.BeLessThan, 1.0) +} diff --git a/v2/should/be_nil.go b/v2/should/be_nil.go new file mode 100644 index 0000000..90b24cc --- /dev/null +++ b/v2/should/be_nil.go @@ -0,0 +1,48 @@ +package should + +import ( + "errors" + "reflect" +) + +// BeNil verifies that actual is the nil value. +func BeNil(actual any, expected ...any) error { + err := validateExpected(0, expected) + if err != nil { + return err + } + + if actual == nil || interfaceHasNilValue(actual) { + return nil + } + + return failure("got %#v, want ", actual) +} +func interfaceHasNilValue(actual any) bool { + value := reflect.ValueOf(actual) + kind := value.Kind() + nillable := kind == reflect.Slice || + kind == reflect.Chan || + kind == reflect.Func || + kind == reflect.Ptr || + kind == reflect.Map + + // Careful: reflect.Value.IsNil() will panic unless it's + // an interface, chan, map, func, slice, or ptr + // Reference: http://golang.org/pkg/reflect/#Value.IsNil + return nillable && value.IsNil() +} + +// BeNil negated! +func (negated) BeNil(actual any, expected ...any) error { + err := BeNil(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("got nil, want non-") +} diff --git a/v2/should/be_nil_test.go b/v2/should/be_nil_test.go new file mode 100644 index 0000000..3937eca --- /dev/null +++ b/v2/should/be_nil_test.go @@ -0,0 +1,31 @@ +package should_test + +import ( + "errors" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeNil(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeNil, "EXTRA") + + assert.Pass(nil, should.BeNil) + assert.Pass([]string(nil), should.BeNil) + assert.Pass((*string)(nil), should.BeNil) + assert.Fail(notNil, should.BeNil) +} + +func TestShouldNotBeNil(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.BeNil, "EXTRA") + + assert.Fail(nil, should.NOT.BeNil) + assert.Fail([]string(nil), should.NOT.BeNil) + assert.Pass(notNil, should.NOT.BeNil) +} + +var notNil = errors.New("not nil") diff --git a/v2/should/be_true.go b/v2/should/be_true.go new file mode 100644 index 0000000..8dfdb39 --- /dev/null +++ b/v2/should/be_true.go @@ -0,0 +1,20 @@ +package should + +// BeTrue verifies that actual is the boolean true value. +func BeTrue(actual any, expected ...any) error { + err := validateExpected(0, expected) + if err != nil { + return err + } + + err = validateType(actual, *new(bool)) + if err != nil { + return err + } + + boolean := actual.(bool) + if !boolean { + return failure("got , want ") + } + return nil +} diff --git a/v2/should/be_true_test.go b/v2/should/be_true_test.go new file mode 100644 index 0000000..49b6b03 --- /dev/null +++ b/v2/should/be_true_test.go @@ -0,0 +1,18 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldBeTrue(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.BeTrue, "EXTRA") + + assert.TypeMismatch(1, should.BeTrue) + + assert.Fail(false, should.BeTrue) + assert.Pass(true, should.BeTrue) +} diff --git a/v2/should/contain.go b/v2/should/contain.go new file mode 100644 index 0000000..e07cd5d --- /dev/null +++ b/v2/should/contain.go @@ -0,0 +1,87 @@ +package should + +import ( + "errors" + "reflect" + "strings" +) + +// Contain determines whether actual contains expected[0]. +// The actual value may be a map, array, slice, or string: +// - In the case of maps the expected value is assumed to be a map key. +// - In the case of slices and arrays the expected value is assumed to be a member. +// - In the case of strings the expected value may be a rune or substring. +func Contain(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + err = validateKind(actual, containerKinds...) + if err != nil { + return err + } + + actualValue := reflect.ValueOf(actual) + EXPECTED := expected[0] + + switch reflect.TypeOf(actual).Kind() { + case reflect.Map: + expectedValue := reflect.ValueOf(EXPECTED) + value := actualValue.MapIndex(expectedValue) + if value.IsValid() { + return nil + } + case reflect.Array, reflect.Slice: + for i := 0; i < actualValue.Len(); i++ { + item := actualValue.Index(i).Interface() + if Equal(EXPECTED, item) == nil { + return nil + } + } + case reflect.String: + err = validateKind(EXPECTED, reflect.String, reflectRune) + if err != nil { + return err + } + + expectedRune, ok := EXPECTED.(rune) + if ok { + EXPECTED = string(expectedRune) + } + + full := actual.(string) + sub := EXPECTED.(string) + if strings.Contains(full, sub) { + return nil + } + } + + return failure("\n"+ + " item absent: %#v\n"+ + " within: %#v", + EXPECTED, + actual, + ) +} + +// Contain (negated!) +func (negated) Contain(actual any, expected ...any) error { + err := Contain(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + "item found: %#v\n"+ + "within: %#v", + expected[0], + actual, + ) +} + +const reflectRune = reflect.Int32 diff --git a/v2/should/contain_test.go b/v2/should/contain_test.go new file mode 100644 index 0000000..3037dee --- /dev/null +++ b/v2/should/contain_test.go @@ -0,0 +1,64 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldContain(t *testing.T) { + assert := NewAssertion(t) + assert.ExpectedCountInvalid("actual", should.Contain) + assert.ExpectedCountInvalid("actual", should.Contain, "EXPECTED", "EXTRA") + + assert.KindMismatch("string", should.Contain, false) + assert.KindMismatch(1, should.Contain, "hi") + + // strings: + assert.Fail("", should.Contain, "no") + assert.Pass("integrate", should.Contain, "rat") + assert.Pass("abc", should.Contain, 'b') + + // slices: + assert.Fail([]byte("abc"), should.Contain, 'd') + assert.Pass([]byte("abc"), should.Contain, 'b') + assert.Pass([]byte("abc"), should.Contain, 98) + + // arrays: + assert.Fail([3]byte{'a', 'b', 'c'}, should.Contain, 'd') + assert.Pass([3]byte{'a', 'b', 'c'}, should.Contain, 'b') + assert.Pass([3]byte{'a', 'b', 'c'}, should.Contain, 98) + + // maps: + assert.Fail(map[rune]int{'a': 1}, should.Contain, 'b') + assert.Pass(map[rune]int{'a': 1}, should.Contain, 'a') +} + +func TestShouldNotContain(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.Contain) + assert.ExpectedCountInvalid("actual", should.NOT.Contain, "EXPECTED", "EXTRA") + + assert.KindMismatch(false, should.NOT.Contain, "string") + assert.KindMismatch("hi", should.NOT.Contain, 1) + + // strings: + assert.Pass("", should.NOT.Contain, "no") + assert.Fail("integrate", should.NOT.Contain, "rat") + assert.Fail("abc", should.NOT.Contain, 'b') + + // slices: + assert.Pass([]byte("abc"), should.NOT.Contain, 'd') + assert.Fail([]byte("abc"), should.NOT.Contain, 'b') + assert.Fail([]byte("abc"), should.NOT.Contain, 98) + + // arrays: + assert.Pass([3]byte{'a', 'b', 'c'}, should.NOT.Contain, 'd') + assert.Fail([3]byte{'a', 'b', 'c'}, should.NOT.Contain, 'b') + assert.Fail([3]byte{'a', 'b', 'c'}, should.NOT.Contain, 98) + + // maps: + assert.Pass(map[rune]int{'a': 1}, should.NOT.Contain, 'b') + assert.Fail(map[rune]int{'a': 1}, should.NOT.Contain, 'a') +} diff --git a/v2/should/end_with.go b/v2/should/end_with.go new file mode 100644 index 0000000..5fb703b --- /dev/null +++ b/v2/should/end_with.go @@ -0,0 +1,57 @@ +package should + +import ( + "reflect" + "strings" +) + +// EndWith verifies that actual ends with expected[0]. +// The actual value may be an array, slice, or string. +func EndWith(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + err = validateKind(actual, orderedContainerKinds...) + if err != nil { + return err + } + + actualValue := reflect.ValueOf(actual) + EXPECTED := expected[0] + + switch reflect.TypeOf(actual).Kind() { + case reflect.Array, reflect.Slice: + if actualValue.Len() == 0 { + break + } + last := actualValue.Index(actualValue.Len() - 1).Interface() + if Equal(EXPECTED, last) == nil { + return nil + } + case reflect.String: + err = validateKind(EXPECTED, reflect.String, reflectRune) + if err != nil { + return err + } + + expectedRune, ok := EXPECTED.(rune) + if ok { + EXPECTED = string(expectedRune) + } + + full := actual.(string) + prefix := EXPECTED.(string) + if strings.HasSuffix(full, prefix) { + return nil + } + } + + return failure("\n"+ + " proposed prefix: %#v\n"+ + " not a prefix of: %#v", + EXPECTED, + actual, + ) +} diff --git a/v2/should/end_with_test.go b/v2/should/end_with_test.go new file mode 100644 index 0000000..7b9502d --- /dev/null +++ b/v2/should/end_with_test.go @@ -0,0 +1,34 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldEndWith(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.EndWith) + assert.ExpectedCountInvalid("actual", should.EndWith, "EXPECTED", "EXTRA") + + assert.KindMismatch("string", should.EndWith, false) + assert.KindMismatch(1, should.EndWith, "hi") + + // strings: + assert.Fail("", should.EndWith, "no") + assert.Pass("abc", should.EndWith, 'c') + assert.Pass("integrate", should.EndWith, "ate") + + // slices: + assert.Fail([]byte{}, should.EndWith, 'b') + assert.Fail([]byte(nil), should.EndWith, 'b') + assert.Fail([]byte("abc"), should.EndWith, 'b') + assert.Pass([]byte("abc"), should.EndWith, 'c') + assert.Pass([]byte("abc"), should.EndWith, 99) + + // arrays: + assert.Fail([3]byte{'a', 'b', 'c'}, should.EndWith, 'b') + assert.Pass([3]byte{'a', 'b', 'c'}, should.EndWith, 'c') + assert.Pass([3]byte{'a', 'b', 'c'}, should.EndWith, 99) +} diff --git a/v2/should/equal.go b/v2/should/equal.go new file mode 100644 index 0000000..e2a2371 --- /dev/null +++ b/v2/should/equal.go @@ -0,0 +1,199 @@ +package should + +import ( + "errors" + "fmt" + "math" + "reflect" + "strings" + "time" + + "github.com/smarty/gunit/v2/should/internal/go-diff/diffmatchpatch" + "github.com/smarty/gunit/v2/should/internal/go-render/render" +) + +// Equal verifies that the actual value is equal to the expected value. +// It uses reflect.DeepEqual in most cases, but also compares numerics +// regardless of specific type and compares time.Time values using the +// time.Equal method. +func Equal(actual any, EXPECTED ...any) error { + err := validateExpected(1, EXPECTED) + if err != nil { + return err + } + + expected := EXPECTED[0] + + for _, spec := range equalitySpecs { + if !spec.assertable(actual, expected) { + continue + } + if spec.passes(actual, expected) { + return nil + } + break + } + return failure(report(actual, expected)) +} + +// Equal negated! +func (negated) Equal(actual any, expected ...any) error { + err := Equal(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not equal: %#v\n"+ + " (but it did)", + expected[0], + actual, + ) +} + +var equalitySpecs = []specification{ + numericEquality{}, + timeEquality{}, + deepEquality{}, +} + +func report(a, b any) string { + builder := new(strings.Builder) + builder.WriteString(simpleDiff(a, b)) + builder.WriteString(prettyDiff(a, b)) + builder.WriteString("\n") + return builder.String() +} + +func simpleDiff(a, b any) string { + aType := fmt.Sprintf("(%v)", reflect.TypeOf(a)) + bType := fmt.Sprintf("(%v)", reflect.TypeOf(b)) + longestType := int(math.Max(float64(len(aType)), float64(len(bType)))) + aType += strings.Repeat(" ", longestType-len(aType)) + bType += strings.Repeat(" ", longestType-len(bType)) + aFormat := fmt.Sprintf(format(a), a) + bFormat := fmt.Sprintf(format(b), b) + + builder := new(strings.Builder) + typeDiff := diff(bType, aType) + valueDiff := diff(bFormat, aFormat) + + _, _ = fmt.Fprintf(builder, "\n") + _, _ = fmt.Fprintf(builder, "Expected: %s %s\n", bType, bFormat) + _, _ = fmt.Fprintf(builder, "Actual: %s %s\n", aType, aFormat) + _, _ = fmt.Fprintf(builder, " %s %s", typeDiff, valueDiff) + + if firstDiffIndex := strings.Index(valueDiff, "^"); firstDiffIndex > 40 { + start := firstDiffIndex - 20 + _, _ = fmt.Fprintf(builder, "\nInitial discrepancy at index %d:\n", firstDiffIndex) + _, _ = fmt.Fprintf(builder, "... %s\n", bFormat[start:]) + _, _ = fmt.Fprintf(builder, "... %s\n", aFormat[start:]) + _, _ = fmt.Fprintf(builder, " %s", valueDiff[start:]) + } + return builder.String() +} + +func prettyDiff(actual, expected any) string { + diff := diffmatchpatch.New() + diffs := diff.DiffMain(render.Render(expected), render.Render(actual), false) + if prettyDiffIsLikelyToBeHelpful(diffs) { + return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs)) + } + return "" +} + +// prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains +// more 'equal' segments than 'deleted'/'inserted' segments. +func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool { + equal, deleted, inserted := measureDiffTypeLengths(diffs) + return equal > deleted && equal > inserted +} + +func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) { + for _, segment := range diffs { + switch segment.Type { + case diffmatchpatch.DiffEqual: + equal += len(segment.Text) + case diffmatchpatch.DiffDelete: + deleted += len(segment.Text) + case diffmatchpatch.DiffInsert: + inserted += len(segment.Text) + } + } + return equal, deleted, inserted +} + +func format(v any) string { + if isNumeric(v) || isTime(v) { + return "%v" + } else { + return "%#v" + } +} +func diff(a, b string) string { + result := new(strings.Builder) + for x := 0; x < len(a) && x < len(b); x++ { + if x >= len(a) || x >= len(b) || a[x] != b[x] { + result.WriteString("^") + } else { + result.WriteString(" ") + } + } + return result.String() +} + +// deepEquality compares any two values using reflect.DeepEqual. +// https://golang.org/pkg/reflect/#DeepEqual +type deepEquality struct{} + +func (deepEquality) assertable(a, b any) bool { + return reflect.TypeOf(a) == reflect.TypeOf(b) +} +func (deepEquality) passes(a, b any) bool { + return reflect.DeepEqual(a, b) +} + +// numericEquality compares numeric values using the built-in equality +// operator (`==`). Values of differing numeric reflect.Kind are each +// converted to the type of the other and are compared with `==` in both +// directions, with one exception: two mixed integers (one signed and one +// unsigned) are always unequal in the case that the unsigned value is +// greater than math.MaxInt64. https://golang.org/pkg/reflect/#Kind +type numericEquality struct{} + +func (numericEquality) assertable(a, b any) bool { + return isNumeric(a) && isNumeric(b) +} +func (numericEquality) passes(a, b any) bool { + aValue := reflect.ValueOf(a) + bValue := reflect.ValueOf(b) + if isUnsignedInteger(a) && isSignedInteger(b) && aValue.Uint() >= math.MaxInt64 { + return false + } + if isSignedInteger(a) && isUnsignedInteger(b) && bValue.Uint() >= math.MaxInt64 { + return false + } + aAsB := aValue.Convert(bValue.Type()).Interface() + bAsA := bValue.Convert(aValue.Type()).Interface() + return a == bAsA && b == aAsB +} + +// timeEquality compares values both of type time.Time using their Equal method. +// https://golang.org/pkg/time/#Time.Equal +type timeEquality struct{} + +func (timeEquality) assertable(a, b any) bool { + return isTime(a) && isTime(b) +} +func (timeEquality) passes(a, b any) bool { + return a.(time.Time).Equal(b.(time.Time)) +} +func isTime(v any) bool { + _, ok := v.(time.Time) + return ok +} diff --git a/v2/should/equal_test.go b/v2/should/equal_test.go new file mode 100644 index 0000000..4b441af --- /dev/null +++ b/v2/should/equal_test.go @@ -0,0 +1,48 @@ +package should_test + +import ( + "math" + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldEqual(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.Equal) + assert.ExpectedCountInvalid("actual", should.Equal, "EXPECTED", "EXTRA") + + assert.Fail(1, should.Equal, 2) + assert.Pass(1, should.Equal, 1) + assert.Pass(1, should.Equal, uint(1)) + + now := time.Now() + assert.Pass(now.UTC(), should.Equal, now.In(time.Local)) + assert.Fail(time.Now(), should.Equal, time.Now()) + + assert.Fail(struct{ A string }{}, should.Equal, struct{ B string }{}) + assert.Pass(struct{ A string }{}, should.Equal, struct{ A string }{}) + + assert.Fail([]byte("hi"), should.Equal, []byte("bye")) + assert.Pass([]byte("hi"), should.Equal, []byte("hi")) + + const MAX uint64 = math.MaxUint64 + assert.Fail(-1, should.Equal, MAX) + assert.Fail(MAX, should.Equal, -1) + + assert.Pass(returnsNilInterface(), should.Equal, nil) +} + +func TestShouldNotEqual(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.Equal) + assert.ExpectedCountInvalid("actual", should.NOT.Equal, "EXPECTED", "EXTRA") + + assert.Fail(1, should.NOT.Equal, 1) + assert.Pass(1, should.NOT.Equal, 2) +} + +func returnsNilInterface() any { return nil } diff --git a/v2/should/errors.go b/v2/should/errors.go new file mode 100644 index 0000000..1bd7d97 --- /dev/null +++ b/v2/should/errors.go @@ -0,0 +1,64 @@ +package should + +import ( + "errors" + "fmt" + "os" + "runtime/debug" + "strconv" + "strings" +) + +var ( + ErrExpectedCountInvalid = errors.New("expected count invalid") + ErrTypeMismatch = errors.New("type mismatch") + ErrKindMismatch = errors.New("kind mismatch") + ErrAssertionFailure = errors.New("assertion failure") + ErrFatalAssertionFailure = errors.New("fatal") +) + +func failure(format string, args ...any) error { + trace := stack(readLines, string(debug.Stack())) + if len(trace) > 0 { + format += "\nStack: (filtered)\n%s" + args = append(args, trace) + } + return wrap(ErrAssertionFailure, format, args...) +} +func stack(readLines func(string) []string, stackTrace string) string { + lines := strings.Split(stackTrace, "\n") + var filtered []string + for x := 1; x < len(lines)-1; x += 2 { + fileLineRaw := lines[x+1] + if strings.Contains(fileLineRaw, "_test.go:") { + filtered = append(filtered, lines[x], fileLineRaw) + line, ok := readSourceCodeLine(readLines, fileLineRaw) + if ok { + filtered = append(filtered, " "+line) + } + + } + } + if len(filtered) == 0 { + return "" + } + return "> " + strings.Join(filtered, "\n> ") +} +func readLines(path string) []string { + content, _ := os.ReadFile(path) + return strings.Split(string(content), "\n") +} +func readSourceCodeLine(readLines func(string) []string, fileLineRaw string) (string, bool) { + fileLineJoined := strings.Fields(strings.TrimSpace(fileLineRaw))[0] + fileLine := strings.Split(fileLineJoined, ":") + sourceCodeLines := readLines(fileLine[0]) + lineNumber, _ := strconv.Atoi(fileLine[1]) + lineNumber-- + if len(sourceCodeLines) <= lineNumber { + return "", false + } + return sourceCodeLines[lineNumber], true +} +func wrap(inner error, format string, args ...any) error { + return fmt.Errorf("%w: "+fmt.Sprintf(format, args...), inner) +} diff --git a/v2/should/errors_test.go b/v2/should/errors_test.go new file mode 100644 index 0000000..fe94d9b --- /dev/null +++ b/v2/should/errors_test.go @@ -0,0 +1,38 @@ +package should + +import ( + "runtime" + "runtime/debug" + "strings" + "testing" +) + +func TestStack(t *testing.T) { + actual := stack(readLines, string(debug.Stack())) // Look for me in expected + _, thisFile, _, _ := runtime.Caller(0) + if !strings.Contains(actual, thisFile) { + t.Error("Missing this file in stack trace.") + } + if !strings.Contains(actual, "Look for me in expected") { + t.Error("Missing expected string 'Look for me in expected'") + } +} +func TestStack_FailureToReadFileInStackTrace(t *testing.T) { + actual := stack(fakeReadLines, string(debug.Stack())) // Don't look for me in expected + _, thisFile, _, _ := runtime.Caller(0) + if !strings.Contains(actual, thisFile) { + t.Error("Missing this file in stack trace.") + } + if strings.Contains(actual, "Don't look for me in expected") { + t.Error("Hmm, the string wasn't supposed to be there...") + } +} +func TestStack_NoFilteredLines(t *testing.T) { + actual := stack(fakeReadLines, "nothing to see here") + if actual != "" { + t.Error("Hmm, with no stack trace, no output should have been returned...") + } +} +func fakeReadLines(string) []string { + return nil +} diff --git a/v2/should/expected.go b/v2/should/expected.go new file mode 100644 index 0000000..b9dfba8 --- /dev/null +++ b/v2/should/expected.go @@ -0,0 +1,40 @@ +package should + +import "reflect" + +func validateExpected(count int, expected []any) error { + length := len(expected) + if length == count { + return nil + } + + s := pluralize(length) + return wrap(ErrExpectedCountInvalid, "got %d value%s, want %d", length, s, count) +} + +func pluralize(count int) string { + if count == 1 { + return "" + } + return "s" +} + +func validateType(actual, expected any) error { + ACTUAL := reflect.TypeOf(actual) + EXPECTED := reflect.TypeOf(expected) + if ACTUAL == EXPECTED { + return nil + } + return wrap(ErrTypeMismatch, "got %s, want %s", ACTUAL, EXPECTED) +} + +func validateKind(actual any, kinds ...reflect.Kind) error { + value := reflect.ValueOf(actual) + kind := value.Kind() + for _, k := range kinds { + if k == kind { + return nil + } + } + return wrap(ErrKindMismatch, "got %s, want one of %v", kind, kinds) +} diff --git a/v2/should/happen_after.go b/v2/should/happen_after.go new file mode 100644 index 0000000..0c383aa --- /dev/null +++ b/v2/should/happen_after.go @@ -0,0 +1,20 @@ +package should + +import "time" + +// HappenAfter ensures that the first time value happens after the second. +func HappenAfter(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + err = validateType(actual, time.Time{}) + if err != nil { + return err + } + err = validateType(expected[0], time.Time{}) + if err != nil { + return err + } + return BeGreaterThan(actual, expected[0]) +} diff --git a/v2/should/happen_after_test.go b/v2/should/happen_after_test.go new file mode 100644 index 0000000..a5550e1 --- /dev/null +++ b/v2/should/happen_after_test.go @@ -0,0 +1,21 @@ +package should_test + +import ( + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldHappenAfter(t *testing.T) { + assert := NewAssertion(t) + + assert.TypeMismatch(1, should.HappenAfter, time.Now()) + assert.TypeMismatch(time.Now(), should.HappenAfter, 1) + + assert.ExpectedCountInvalid(time.Now(), should.HappenAfter) + assert.ExpectedCountInvalid(time.Now(), should.HappenAfter, time.Now(), time.Now()) + + assert.Fail(time.Now(), should.HappenAfter, time.Now()) + assert.Pass(time.Now().Add(time.Second), should.HappenAfter, time.Now()) +} diff --git a/v2/should/happen_before.go b/v2/should/happen_before.go new file mode 100644 index 0000000..a7a55c6 --- /dev/null +++ b/v2/should/happen_before.go @@ -0,0 +1,20 @@ +package should + +import "time" + +// HappenBefore ensures that the first time value happens before the second. +func HappenBefore(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + err = validateType(actual, time.Time{}) + if err != nil { + return err + } + err = validateType(expected[0], time.Time{}) + if err != nil { + return err + } + return BeLessThan(actual, expected[0]) +} diff --git a/v2/should/happen_before_test.go b/v2/should/happen_before_test.go new file mode 100644 index 0000000..b3e5d23 --- /dev/null +++ b/v2/should/happen_before_test.go @@ -0,0 +1,21 @@ +package should_test + +import ( + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldHappenBefore(t *testing.T) { + assert := NewAssertion(t) + + assert.TypeMismatch(1, should.HappenBefore, time.Now()) + assert.TypeMismatch(time.Now(), should.HappenBefore, 1) + + assert.ExpectedCountInvalid(time.Now(), should.HappenBefore) + assert.ExpectedCountInvalid(time.Now(), should.HappenBefore, time.Now(), time.Now()) + + assert.Fail(time.Now().Add(time.Second), should.HappenBefore, time.Now()) + assert.Pass(time.Now(), should.HappenBefore, time.Now()) +} diff --git a/v2/should/happen_on.go b/v2/should/happen_on.go new file mode 100644 index 0000000..28f4d0b --- /dev/null +++ b/v2/should/happen_on.go @@ -0,0 +1,44 @@ +package should + +import ( + "errors" + "time" +) + +// HappenOn ensures that two time values happen at the same instant. +// See the time.Time.Equal method for the details. +// This function defers to Equal to do the work. +func HappenOn(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + err = validateType(actual, time.Time{}) + if err != nil { + return err + } + err = validateType(expected[0], time.Time{}) + if err != nil { + return err + } + return Equal(actual, expected...) +} + +// HappenOn negated! +func (negated) HappenOn(actual any, expected ...any) error { + err := HappenOn(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + if err != nil { + return err + } + + return failure("\n"+ + " expected: %#v\n"+ + " to not equal: %#v\n"+ + " (but it did)", + expected[0], + actual, + ) +} diff --git a/v2/should/happen_on_test.go b/v2/should/happen_on_test.go new file mode 100644 index 0000000..a6de443 --- /dev/null +++ b/v2/should/happen_on_test.go @@ -0,0 +1,36 @@ +package should_test + +import ( + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldHappenOn(t *testing.T) { + assert := NewAssertion(t) + + assert.TypeMismatch(1, should.HappenOn, time.Now()) + assert.TypeMismatch(time.Now(), should.HappenOn, 1) + + assert.ExpectedCountInvalid(time.Now(), should.HappenOn) + assert.ExpectedCountInvalid(time.Now(), should.HappenOn, time.Now(), time.Now()) + + now := time.Now() + assert.Pass(now.UTC(), should.HappenOn, now.In(time.Local)) + assert.Fail(time.Now(), should.HappenOn, time.Now()) +} + +func TestShouldNOTHappenOn(t *testing.T) { + assert := NewAssertion(t) + + assert.TypeMismatch(1, should.NOT.HappenOn, time.Now()) + assert.TypeMismatch(time.Now(), should.NOT.HappenOn, 1) + + assert.ExpectedCountInvalid(time.Now(), should.NOT.HappenOn) + assert.ExpectedCountInvalid(time.Now(), should.NOT.HappenOn, time.Now(), time.Now()) + + now := time.Now() + assert.Fail(now.UTC(), should.NOT.HappenOn, now.In(time.Local)) + assert.Pass(time.Now(), should.NOT.HappenOn, time.Now()) +} diff --git a/v2/should/happen_within.go b/v2/should/happen_within.go new file mode 100644 index 0000000..0529d60 --- /dev/null +++ b/v2/should/happen_within.go @@ -0,0 +1,41 @@ +package should + +import "time" + +// HappenWithin ensures that the first time value happens within +// a specified duration of the other time value. +// The actual value should be a time.Time. +// The first expected value should be a time.Duration. +// The second expected value should be a time.Time. +func HappenWithin(actual any, expected ...any) error { + err := validateExpected(2, expected) + if err != nil { + return err + } + err = validateType(actual, time.Time{}) + if err != nil { + return err + } + err = validateType(expected[0], time.Nanosecond) + if err != nil { + return err + } + err = validateType(expected[1], time.Time{}) + if err != nil { + return err + } + a := actual.(time.Time) + b := expected[1].(time.Time) + diff := a.Sub(b).Abs() + EXPECTED := expected[0].(time.Duration) + if diff > EXPECTED { + return failure("\n"+ + "Actual: %s\n"+ + "Target: %s\n"+ + "Max: %s\n"+ + "Diff: %s", + a, b, EXPECTED, diff, + ) + } + return nil +} diff --git a/v2/should/happen_within_test.go b/v2/should/happen_within_test.go new file mode 100644 index 0000000..e5abd15 --- /dev/null +++ b/v2/should/happen_within_test.go @@ -0,0 +1,22 @@ +package should_test + +import ( + "testing" + "time" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldHappenWithin(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid(time.Now(), should.HappenWithin) + assert.ExpectedCountInvalid(time.Now(), should.HappenWithin, time.Nanosecond) + + assert.TypeMismatch(1, should.HappenWithin, time.Nanosecond, time.Now()) + assert.TypeMismatch(time.Now(), should.HappenWithin, 1, time.Now()) + assert.TypeMismatch(time.Now(), should.HappenWithin, time.Nanosecond, 1) + + assert.Fail(time.Now(), should.HappenWithin, time.Nanosecond, time.Now().Truncate(time.Millisecond)) + assert.Pass(time.Now(), should.HappenWithin, time.Second, time.Now()) +} diff --git a/v2/should/have_length.go b/v2/should/have_length.go new file mode 100644 index 0000000..1dbad96 --- /dev/null +++ b/v2/should/have_length.go @@ -0,0 +1,29 @@ +package should + +import "reflect" + +// HaveLength uses reflection to verify that len(actual) == 0. +func HaveLength(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + err = validateKind(actual, kindsWithLength...) + if err != nil { + return err + } + + err = validateKind(expected[0], kindSlice(signedIntegerKinds)...) + if err != nil { + return err + } + + expectedLength := reflect.ValueOf(expected[0]).Int() + actualLength := int64(reflect.ValueOf(actual).Len()) + if actualLength == expectedLength { + return nil + } + + return failure("got length of %d, want %d", actualLength, expectedLength) +} diff --git a/v2/should/have_length_test.go b/v2/should/have_length_test.go new file mode 100644 index 0000000..f6ab390 --- /dev/null +++ b/v2/should/have_length_test.go @@ -0,0 +1,35 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldHaveLength(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.HaveLength, " EXPECTED", "EXTRA") + assert.KindMismatch(true, should.HaveLength, 0) + + assert.KindMismatch(42, should.HaveLength, 0) + assert.KindMismatch("", should.HaveLength, "") + + assert.Pass([]string(nil), should.HaveLength, 0) + assert.Pass([]string{}, should.HaveLength, 0) + assert.Pass([]string{""}, should.HaveLength, 1) + assert.Fail([]string{""}, should.HaveLength, 2) + + assert.Pass([0]string{}, should.HaveLength, 0) // The only possible empty array! + assert.Fail([1]string{}, should.HaveLength, 2) + + assert.Pass(chan string(nil), should.HaveLength, 0) + assert.Fail(nonEmptyChannel(), should.HaveLength, 2) + + assert.Pass(map[string]string{"": ""}, should.HaveLength, 1) + assert.Fail(map[string]string{"": ""}, should.HaveLength, 2) + + assert.Pass("", should.HaveLength, 0) + assert.Pass("123", should.HaveLength, 3) + assert.Fail("123", should.HaveLength, 4) +} diff --git a/v2/should/internal/go-diff/.gitignore b/v2/should/internal/go-diff/.gitignore new file mode 100644 index 0000000..0026861 --- /dev/null +++ b/v2/should/internal/go-diff/.gitignore @@ -0,0 +1,22 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe diff --git a/v2/should/internal/go-diff/.travis.yml b/v2/should/internal/go-diff/.travis.yml new file mode 100644 index 0000000..85868de --- /dev/null +++ b/v2/should/internal/go-diff/.travis.yml @@ -0,0 +1,27 @@ +language: go + +os: + - linux + - osx + +go: + - 1.8.x + - 1.9.x + +sudo: false + +env: + global: + # Coveralls.io + - secure: OGYOsFNXNarEZ5yA4/M6ZdVguD0jL8vXgXrbLzjcpkKcq8ObHSCtNINoUlnNf6l6Z92kPnuV+LSm7jKTojBlov4IwgiY1ACbvg921SdjxYkg1AiwHTRTLR1g/esX8RdaBpJ0TOcXOFFsYMRVvl5sxxtb0tXSuUrT+Ch4SUCY7X8= + +install: + - make install-dependencies + - make install-tools + - make install + +script: + - make lint + - make test-with-coverage + - gover + - if [ "$TRAVIS_SECURE_ENV_VARS" = "true" ]; then goveralls -coverprofile=gover.coverprofile -service=travis-ci -repotoken $COVERALLS_TOKEN; fi diff --git a/v2/should/internal/go-diff/APACHE-LICENSE-2.0 b/v2/should/internal/go-diff/APACHE-LICENSE-2.0 new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/v2/should/internal/go-diff/APACHE-LICENSE-2.0 @@ -0,0 +1,177 @@ + + 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 diff --git a/v2/should/internal/go-diff/AUTHORS b/v2/should/internal/go-diff/AUTHORS new file mode 100644 index 0000000..2d7bb2b --- /dev/null +++ b/v2/should/internal/go-diff/AUTHORS @@ -0,0 +1,25 @@ +# This is the official list of go-diff authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. + +# Names should be added to this file as +# Name or Organization +# The email address is not required for organizations. + +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/v2/should/internal/go-diff/CONTRIBUTORS b/v2/should/internal/go-diff/CONTRIBUTORS new file mode 100644 index 0000000..369e3d5 --- /dev/null +++ b/v2/should/internal/go-diff/CONTRIBUTORS @@ -0,0 +1,32 @@ +# This is the official list of people who can contribute +# (and typically have contributed) code to the go-diff +# repository. +# +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, ACME Inc. employees would be listed here +# but not in AUTHORS, because ACME Inc. would hold the copyright. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file. +# +# Names should be added to this file like so: +# Name +# +# Please keep the list sorted. + +Danny Yoo +James Kolb +Jonathan Amsterdam +Markus Zimmermann +Matt Kovars +Örjan Persson +Osman Masood +Robert Carlsen +Rory Flynn +Sergi Mansilla +Shatrugna Sadhu +Shawn Smith +Stas Maksimov +Tor Arvid Lund +Zac Bergquist diff --git a/v2/should/internal/go-diff/LICENSE b/v2/should/internal/go-diff/LICENSE new file mode 100644 index 0000000..937942c --- /dev/null +++ b/v2/should/internal/go-diff/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2012-2016 The go-diff Authors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + diff --git a/v2/should/internal/go-diff/Makefile b/v2/should/internal/go-diff/Makefile new file mode 100644 index 0000000..e013f0b --- /dev/null +++ b/v2/should/internal/go-diff/Makefile @@ -0,0 +1,44 @@ +.PHONY: all clean clean-coverage install install-dependencies install-tools lint test test-verbose test-with-coverage + +export ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)) +export PKG := github.com/sergi/go-diff +export ROOT_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) + +$(eval $(ARGS):;@:) # turn arguments into do-nothing targets +export ARGS + +ifdef ARGS + PKG_TEST := $(ARGS) +else + PKG_TEST := $(PKG)/... +endif + +all: install-tools install-dependencies install lint test + +clean: + go clean -i $(PKG)/... + go clean -i -race $(PKG)/... +clean-coverage: + find $(ROOT_DIR) | grep .coverprofile | xargs rm +install: + go install -v $(PKG)/... +install-dependencies: + go get -t -v $(PKG)/... + go build -v $(PKG)/... +install-tools: + # Install linting tools + go get -u -v github.com/golang/lint/... + go get -u -v github.com/kisielk/errcheck/... + + # Install code coverage tools + go get -u -v github.com/onsi/ginkgo/ginkgo/... + go get -u -v github.com/modocache/gover/... + go get -u -v github.com/mattn/goveralls/... +lint: + $(ROOT_DIR)/scripts/lint.sh +test: + go test -race -test.timeout 120s $(PKG_TEST) +test-verbose: + go test -race -test.timeout 120s -v $(PKG_TEST) +test-with-coverage: + ginkgo -r -cover -race -skipPackage="testdata" diff --git a/v2/should/internal/go-diff/README.md b/v2/should/internal/go-diff/README.md new file mode 100644 index 0000000..597437b --- /dev/null +++ b/v2/should/internal/go-diff/README.md @@ -0,0 +1,84 @@ +# go-diff [![GoDoc](https://godoc.org/github.com/sergi/go-diff?status.png)](https://godoc.org/github.com/sergi/go-diff/diffmatchpatch) [![Build Status](https://travis-ci.org/sergi/go-diff.svg?branch=master)](https://travis-ci.org/sergi/go-diff) [![Coverage Status](https://coveralls.io/repos/sergi/go-diff/badge.png?branch=master)](https://coveralls.io/r/sergi/go-diff?branch=master) + +go-diff offers algorithms to perform operations required for synchronizing plain text: + +- Compare two texts and return their differences. +- Perform fuzzy matching of text. +- Apply patches onto text. + +## Installation + +```bash +go get -u github.com/sergi/go-diff/... +``` + +## Usage + +The following example compares two texts and writes out the differences to standard output. + +```go +package main + +import ( + "fmt" + + "github.com/sergi/go-diff/diffmatchpatch" +) + +const ( + text1 = "Lorem ipsum dolor." + text2 = "Lorem dolor sit amet." +) + +func main() { + dmp := diffmatchpatch.New() + + diffs := dmp.DiffMain(text1, text2, false) + + fmt.Println(dmp.DiffPrettyText(diffs)) +} +``` + +## Found a bug or are you missing a feature in go-diff? + +Please make sure to have the latest version of go-diff. If the problem still persists go through the [open issues](https://github.com/sergi/go-diff/issues) in the tracker first. If you cannot find your request just open up a [new issue](https://github.com/sergi/go-diff/issues/new). + +## How to contribute? + +You want to contribute to go-diff? GREAT! If you are here because of a bug you want to fix or a feature you want to add, you can just read on. Otherwise we have a list of [open issues in the tracker](https://github.com/sergi/go-diff/issues). Just choose something you think you can work on and discuss your plans in the issue by commenting on it. + +Please make sure that every behavioral change is accompanied by test cases. Additionally, every contribution must pass the `lint` and `test` Makefile targets which can be run using the following commands in the repository root directory. + +```bash +make lint +make test +``` + +After your contribution passes these commands, [create a PR](https://help.github.com/articles/creating-a-pull-request/) and we will review your contribution. + +## Origins + +go-diff is a Go language port of Neil Fraser's google-diff-match-patch code. His original code is available at [http://code.google.com/p/google-diff-match-patch/](http://code.google.com/p/google-diff-match-patch/). + +## Copyright and License + +The original Google Diff, Match and Patch Library is licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0). The full terms of that license are included here in the [APACHE-LICENSE-2.0](/APACHE-LICENSE-2.0) file. + +Diff, Match and Patch Library + +> Written by Neil Fraser +> Copyright (c) 2006 Google Inc. +> + +This Go version of Diff, Match and Patch Library is licensed under the [MIT License](http://www.opensource.org/licenses/MIT) (a.k.a. the Expat License) which is included here in the [LICENSE](/LICENSE) file. + +Go version of Diff, Match and Patch Library + +> Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +> + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/v2/should/internal/go-diff/diffmatchpatch/diff.go b/v2/should/internal/go-diff/diffmatchpatch/diff.go new file mode 100644 index 0000000..cb25b43 --- /dev/null +++ b/v2/should/internal/go-diff/diffmatchpatch/diff.go @@ -0,0 +1,1345 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "fmt" + "html" + "math" + "net/url" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" +) + +// Operation defines the operation of a diff item. +type Operation int8 + +//go:generate stringer -type=Operation -trimprefix=Diff + +const ( + // DiffDelete item represents a delete diff. + DiffDelete Operation = -1 + // DiffInsert item represents an insert diff. + DiffInsert Operation = 1 + // DiffEqual item represents an equal diff. + DiffEqual Operation = 0 +) + +// Diff represents one diff operation +type Diff struct { + Type Operation + Text string +} + +// splice removes amount elements from slice at index index, replacing them with elements. +func splice(slice []Diff, index int, amount int, elements ...Diff) []Diff { + if len(elements) == amount { + // Easy case: overwrite the relevant items. + copy(slice[index:], elements) + return slice + } + if len(elements) < amount { + // Fewer new items than old. + // Copy in the new items. + copy(slice[index:], elements) + // Shift the remaining items left. + copy(slice[index+len(elements):], slice[index+amount:]) + // Calculate the new end of the slice. + end := len(slice) - amount + len(elements) + // Zero stranded elements at end so that they can be garbage collected. + tail := slice[end:] + for i := range tail { + tail[i] = Diff{} + } + return slice[:end] + } + // More new items than old. + // Make room in slice for new elements. + // There's probably an even more efficient way to do this, + // but this is simple and clear. + need := len(slice) - amount + len(elements) + for len(slice) < need { + slice = append(slice, Diff{}) + } + // Shift slice elements right to make room for new elements. + copy(slice[index+len(elements):], slice[index+amount:]) + // Copy in new elements. + copy(slice[index:], elements) + return slice +} + +// DiffMain finds the differences between two texts. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMain(text1, text2 string, checklines bool) []Diff { + return dmp.DiffMainRunes([]rune(text1), []rune(text2), checklines) +} + +// DiffMainRunes finds the differences between two rune sequences. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +func (dmp *DiffMatchPatch) DiffMainRunes(text1, text2 []rune, checklines bool) []Diff { + var deadline time.Time + if dmp.DiffTimeout > 0 { + deadline = time.Now().Add(dmp.DiffTimeout) + } + return dmp.diffMainRunes(text1, text2, checklines, deadline) +} + +func (dmp *DiffMatchPatch) diffMainRunes(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + if runesEqual(text1, text2) { + var diffs []Diff + if len(text1) > 0 { + diffs = append(diffs, Diff{DiffEqual, string(text1)}) + } + return diffs + } + // Trim off common prefix (speedup). + commonlength := commonPrefixLength(text1, text2) + commonprefix := text1[:commonlength] + text1 = text1[commonlength:] + text2 = text2[commonlength:] + + // Trim off common suffix (speedup). + commonlength = commonSuffixLength(text1, text2) + commonsuffix := text1[len(text1)-commonlength:] + text1 = text1[:len(text1)-commonlength] + text2 = text2[:len(text2)-commonlength] + + // Compute the diff on the middle block. + diffs := dmp.diffCompute(text1, text2, checklines, deadline) + + // Restore the prefix and suffix. + if len(commonprefix) != 0 { + diffs = append([]Diff{Diff{DiffEqual, string(commonprefix)}}, diffs...) + } + if len(commonsuffix) != 0 { + diffs = append(diffs, Diff{DiffEqual, string(commonsuffix)}) + } + + return dmp.DiffCleanupMerge(diffs) +} + +// diffCompute finds the differences between two rune slices. Assumes that the texts do not have any common prefix or suffix. +func (dmp *DiffMatchPatch) diffCompute(text1, text2 []rune, checklines bool, deadline time.Time) []Diff { + diffs := []Diff{} + if len(text1) == 0 { + // Just add some text (speedup). + return append(diffs, Diff{DiffInsert, string(text2)}) + } else if len(text2) == 0 { + // Just delete some text (speedup). + return append(diffs, Diff{DiffDelete, string(text1)}) + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if i := runesIndex(longtext, shorttext); i != -1 { + op := DiffInsert + // Swap insertions for deletions if diff is reversed. + if len(text1) > len(text2) { + op = DiffDelete + } + // Shorter text is inside the longer text (speedup). + return []Diff{ + Diff{op, string(longtext[:i])}, + Diff{DiffEqual, string(shorttext)}, + Diff{op, string(longtext[i+len(shorttext):])}, + } + } else if len(shorttext) == 1 { + // Single character string. + // After the previous speedup, the character can't be an equality. + return []Diff{ + Diff{DiffDelete, string(text1)}, + Diff{DiffInsert, string(text2)}, + } + // Check to see if the problem can be split in two. + } else if hm := dmp.diffHalfMatch(text1, text2); hm != nil { + // A half-match was found, sort out the return data. + text1A := hm[0] + text1B := hm[1] + text2A := hm[2] + text2B := hm[3] + midCommon := hm[4] + // Send both pairs off for separate processing. + diffsA := dmp.diffMainRunes(text1A, text2A, checklines, deadline) + diffsB := dmp.diffMainRunes(text1B, text2B, checklines, deadline) + // Merge the results. + diffs := diffsA + diffs = append(diffs, Diff{DiffEqual, string(midCommon)}) + diffs = append(diffs, diffsB...) + return diffs + } else if checklines && len(text1) > 100 && len(text2) > 100 { + return dmp.diffLineMode(text1, text2, deadline) + } + return dmp.diffBisect(text1, text2, deadline) +} + +// diffLineMode does a quick line-level diff on both []runes, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) diffLineMode(text1, text2 []rune, deadline time.Time) []Diff { + // Scan the text on a line-by-line basis first. + text1, text2, linearray := dmp.diffLinesToRunes(text1, text2) + + diffs := dmp.diffMainRunes(text1, text2, false, deadline) + + // Convert the diff back to original text. + diffs = dmp.DiffCharsToLines(diffs, linearray) + // Eliminate freak matches (e.g. blank lines) + diffs = dmp.DiffCleanupSemantic(diffs) + + // Rediff any replacement blocks, this time character-by-character. + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + + pointer := 0 + countDelete := 0 + countInsert := 0 + + // NOTE: Rune slices are slower than using strings in this case. + textDelete := "" + textInsert := "" + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert += diffs[pointer].Text + case DiffDelete: + countDelete++ + textDelete += diffs[pointer].Text + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete >= 1 && countInsert >= 1 { + // Delete the offending records and add the merged ones. + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert) + + pointer = pointer - countDelete - countInsert + a := dmp.diffMainRunes([]rune(textDelete), []rune(textInsert), false, deadline) + for j := len(a) - 1; j >= 0; j-- { + diffs = splice(diffs, pointer, 0, a[j]) + } + pointer = pointer + len(a) + } + + countInsert = 0 + countDelete = 0 + textDelete = "" + textInsert = "" + } + pointer++ + } + + return diffs[:len(diffs)-1] // Remove the dummy entry at the end. +} + +// DiffBisect finds the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. +// If an invalid UTF-8 sequence is encountered, it will be replaced by the Unicode replacement character. +// See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) DiffBisect(text1, text2 string, deadline time.Time) []Diff { + // Unused in this code, but retained for interface compatibility. + return dmp.diffBisect([]rune(text1), []rune(text2), deadline) +} + +// diffBisect finds the 'middle snake' of a diff, splits the problem in two and returns the recursively constructed diff. +// See Myers's 1986 paper: An O(ND) Difference Algorithm and Its Variations. +func (dmp *DiffMatchPatch) diffBisect(runes1, runes2 []rune, deadline time.Time) []Diff { + // Cache the text lengths to prevent multiple calls. + runes1Len, runes2Len := len(runes1), len(runes2) + + maxD := (runes1Len + runes2Len + 1) / 2 + vOffset := maxD + vLength := 2 * maxD + + v1 := make([]int, vLength) + v2 := make([]int, vLength) + for i := range v1 { + v1[i] = -1 + v2[i] = -1 + } + v1[vOffset+1] = 0 + v2[vOffset+1] = 0 + + delta := runes1Len - runes2Len + // If the total number of characters is odd, then the front path will collide with the reverse path. + front := (delta%2 != 0) + // Offsets for start and end of k loop. Prevents mapping of space beyond the grid. + k1start := 0 + k1end := 0 + k2start := 0 + k2end := 0 + for d := 0; d < maxD; d++ { + // Bail out if deadline is reached. + if !deadline.IsZero() && d%16 == 0 && time.Now().After(deadline) { + break + } + + // Walk the front path one step. + for k1 := -d + k1start; k1 <= d-k1end; k1 += 2 { + k1Offset := vOffset + k1 + var x1 int + + if k1 == -d || (k1 != d && v1[k1Offset-1] < v1[k1Offset+1]) { + x1 = v1[k1Offset+1] + } else { + x1 = v1[k1Offset-1] + 1 + } + + y1 := x1 - k1 + for x1 < runes1Len && y1 < runes2Len { + if runes1[x1] != runes2[y1] { + break + } + x1++ + y1++ + } + v1[k1Offset] = x1 + if x1 > runes1Len { + // Ran off the right of the graph. + k1end += 2 + } else if y1 > runes2Len { + // Ran off the bottom of the graph. + k1start += 2 + } else if front { + k2Offset := vOffset + delta - k1 + if k2Offset >= 0 && k2Offset < vLength && v2[k2Offset] != -1 { + // Mirror x2 onto top-left coordinate system. + x2 := runes1Len - v2[k2Offset] + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + // Walk the reverse path one step. + for k2 := -d + k2start; k2 <= d-k2end; k2 += 2 { + k2Offset := vOffset + k2 + var x2 int + if k2 == -d || (k2 != d && v2[k2Offset-1] < v2[k2Offset+1]) { + x2 = v2[k2Offset+1] + } else { + x2 = v2[k2Offset-1] + 1 + } + var y2 = x2 - k2 + for x2 < runes1Len && y2 < runes2Len { + if runes1[runes1Len-x2-1] != runes2[runes2Len-y2-1] { + break + } + x2++ + y2++ + } + v2[k2Offset] = x2 + if x2 > runes1Len { + // Ran off the left of the graph. + k2end += 2 + } else if y2 > runes2Len { + // Ran off the top of the graph. + k2start += 2 + } else if !front { + k1Offset := vOffset + delta - k2 + if k1Offset >= 0 && k1Offset < vLength && v1[k1Offset] != -1 { + x1 := v1[k1Offset] + y1 := vOffset + x1 - k1Offset + // Mirror x2 onto top-left coordinate system. + x2 = runes1Len - x2 + if x1 >= x2 { + // Overlap detected. + return dmp.diffBisectSplit(runes1, runes2, x1, y1, deadline) + } + } + } + } + } + // Diff took too long and hit the deadline or number of diffs equals number of characters, no commonality at all. + return []Diff{ + Diff{DiffDelete, string(runes1)}, + Diff{DiffInsert, string(runes2)}, + } +} + +func (dmp *DiffMatchPatch) diffBisectSplit(runes1, runes2 []rune, x, y int, + deadline time.Time) []Diff { + runes1a := runes1[:x] + runes2a := runes2[:y] + runes1b := runes1[x:] + runes2b := runes2[y:] + + // Compute both diffs serially. + diffs := dmp.diffMainRunes(runes1a, runes2a, false, deadline) + diffsb := dmp.diffMainRunes(runes1b, runes2b, false, deadline) + + return append(diffs, diffsb...) +} + +// DiffLinesToChars splits two texts into a list of strings, and educes the texts to a string of hashes where each Unicode character represents one line. +// It's slightly faster to call DiffLinesToRunes first, followed by DiffMainRunes. +func (dmp *DiffMatchPatch) DiffLinesToChars(text1, text2 string) (string, string, []string) { + chars1, chars2, lineArray := dmp.DiffLinesToRunes(text1, text2) + return string(chars1), string(chars2), lineArray +} + +// DiffLinesToRunes splits two texts into a list of runes. Each rune represents one line. +func (dmp *DiffMatchPatch) DiffLinesToRunes(text1, text2 string) ([]rune, []rune, []string) { + // '\x00' is a valid character, but various debuggers don't like it. So we'll insert a junk entry to avoid generating a null character. + lineArray := []string{""} // e.g. lineArray[4] == 'Hello\n' + lineHash := map[string]int{} // e.g. lineHash['Hello\n'] == 4 + + chars1 := dmp.diffLinesToRunesMunge(text1, &lineArray, lineHash) + chars2 := dmp.diffLinesToRunesMunge(text2, &lineArray, lineHash) + + return chars1, chars2, lineArray +} + +func (dmp *DiffMatchPatch) diffLinesToRunes(text1, text2 []rune) ([]rune, []rune, []string) { + return dmp.DiffLinesToRunes(string(text1), string(text2)) +} + +// diffLinesToRunesMunge splits a text into an array of strings, and reduces the texts to a []rune where each Unicode character represents one line. +// We use strings instead of []runes as input mainly because you can't use []rune as a map key. +func (dmp *DiffMatchPatch) diffLinesToRunesMunge(text string, lineArray *[]string, lineHash map[string]int) []rune { + // Walk the text, pulling out a substring for each line. text.split('\n') would would temporarily double our memory footprint. Modifying text would create many large strings to garbage collect. + lineStart := 0 + lineEnd := -1 + runes := []rune{} + + for lineEnd < len(text)-1 { + lineEnd = indexOf(text, "\n", lineStart) + + if lineEnd == -1 { + lineEnd = len(text) - 1 + } + + line := text[lineStart : lineEnd+1] + lineStart = lineEnd + 1 + lineValue, ok := lineHash[line] + + if ok { + runes = append(runes, rune(lineValue)) + } else { + *lineArray = append(*lineArray, line) + lineHash[line] = len(*lineArray) - 1 + runes = append(runes, rune(len(*lineArray)-1)) + } + } + + return runes +} + +// DiffCharsToLines rehydrates the text in a diff from a string of line hashes to real lines of text. +func (dmp *DiffMatchPatch) DiffCharsToLines(diffs []Diff, lineArray []string) []Diff { + hydrated := make([]Diff, 0, len(diffs)) + for _, aDiff := range diffs { + chars := aDiff.Text + text := make([]string, len(chars)) + + for i, r := range chars { + text[i] = lineArray[r] + } + + aDiff.Text = strings.Join(text, "") + hydrated = append(hydrated, aDiff) + } + return hydrated +} + +// DiffCommonPrefix determines the common prefix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonPrefix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonPrefixLength([]rune(text1), []rune(text2)) +} + +// DiffCommonSuffix determines the common suffix length of two strings. +func (dmp *DiffMatchPatch) DiffCommonSuffix(text1, text2 string) int { + // Unused in this code, but retained for interface compatibility. + return commonSuffixLength([]rune(text1), []rune(text2)) +} + +// commonPrefixLength returns the length of the common prefix of two rune slices. +func commonPrefixLength(text1, text2 []rune) int { + // Linear search. See comment in commonSuffixLength. + n := 0 + for ; n < len(text1) && n < len(text2); n++ { + if text1[n] != text2[n] { + return n + } + } + return n +} + +// commonSuffixLength returns the length of the common suffix of two rune slices. +func commonSuffixLength(text1, text2 []rune) int { + // Use linear search rather than the binary search discussed at https://neil.fraser.name/news/2007/10/09/. + // See discussion at https://github.com/sergi/go-diff/issues/54. + i1 := len(text1) + i2 := len(text2) + for n := 0; ; n++ { + i1-- + i2-- + if i1 < 0 || i2 < 0 || text1[i1] != text2[i2] { + return n + } + } +} + +// DiffCommonOverlap determines if the suffix of one string is the prefix of another. +func (dmp *DiffMatchPatch) DiffCommonOverlap(text1 string, text2 string) int { + // Cache the text lengths to prevent multiple calls. + text1Length := len(text1) + text2Length := len(text2) + // Eliminate the null case. + if text1Length == 0 || text2Length == 0 { + return 0 + } + // Truncate the longer string. + if text1Length > text2Length { + text1 = text1[text1Length-text2Length:] + } else if text1Length < text2Length { + text2 = text2[0:text1Length] + } + textLength := int(math.Min(float64(text1Length), float64(text2Length))) + // Quick check for the worst case. + if text1 == text2 { + return textLength + } + + // Start by looking for a single character match and increase length until no match is found. Performance analysis: http://neil.fraser.name/news/2010/11/04/ + best := 0 + length := 1 + for { + pattern := text1[textLength-length:] + found := strings.Index(text2, pattern) + if found == -1 { + break + } + length += found + if found == 0 || text1[textLength-length:] == text2[0:length] { + best = length + length++ + } + } + + return best +} + +// DiffHalfMatch checks whether the two texts share a substring which is at least half the length of the longer text. This speedup can produce non-minimal diffs. +func (dmp *DiffMatchPatch) DiffHalfMatch(text1, text2 string) []string { + // Unused in this code, but retained for interface compatibility. + runeSlices := dmp.diffHalfMatch([]rune(text1), []rune(text2)) + if runeSlices == nil { + return nil + } + + result := make([]string, len(runeSlices)) + for i, r := range runeSlices { + result[i] = string(r) + } + return result +} + +func (dmp *DiffMatchPatch) diffHalfMatch(text1, text2 []rune) [][]rune { + if dmp.DiffTimeout <= 0 { + // Don't risk returning a non-optimal diff if we have unlimited time. + return nil + } + + var longtext, shorttext []rune + if len(text1) > len(text2) { + longtext = text1 + shorttext = text2 + } else { + longtext = text2 + shorttext = text1 + } + + if len(longtext) < 4 || len(shorttext)*2 < len(longtext) { + return nil // Pointless. + } + + // First check if the second quarter is the seed for a half-match. + hm1 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+3)/4)) + + // Check again based on the third quarter. + hm2 := dmp.diffHalfMatchI(longtext, shorttext, int(float64(len(longtext)+1)/2)) + + hm := [][]rune{} + if hm1 == nil && hm2 == nil { + return nil + } else if hm2 == nil { + hm = hm1 + } else if hm1 == nil { + hm = hm2 + } else { + // Both matched. Select the longest. + if len(hm1[4]) > len(hm2[4]) { + hm = hm1 + } else { + hm = hm2 + } + } + + // A half-match was found, sort out the return data. + if len(text1) > len(text2) { + return hm + } + + return [][]rune{hm[2], hm[3], hm[0], hm[1], hm[4]} +} + +// diffHalfMatchI checks if a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? +// Returns a slice containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle, or null if there was no match. +func (dmp *DiffMatchPatch) diffHalfMatchI(l, s []rune, i int) [][]rune { + var bestCommonA []rune + var bestCommonB []rune + var bestCommonLen int + var bestLongtextA []rune + var bestLongtextB []rune + var bestShorttextA []rune + var bestShorttextB []rune + + // Start with a 1/4 length substring at position i as a seed. + seed := l[i : i+len(l)/4] + + for j := runesIndexOf(s, seed, 0); j != -1; j = runesIndexOf(s, seed, j+1) { + prefixLength := commonPrefixLength(l[i:], s[j:]) + suffixLength := commonSuffixLength(l[:i], s[:j]) + + if bestCommonLen < suffixLength+prefixLength { + bestCommonA = s[j-suffixLength : j] + bestCommonB = s[j : j+prefixLength] + bestCommonLen = len(bestCommonA) + len(bestCommonB) + bestLongtextA = l[:i-suffixLength] + bestLongtextB = l[i+prefixLength:] + bestShorttextA = s[:j-suffixLength] + bestShorttextB = s[j+prefixLength:] + } + } + + if bestCommonLen*2 < len(l) { + return nil + } + + return [][]rune{ + bestLongtextA, + bestLongtextB, + bestShorttextA, + bestShorttextB, + append(bestCommonA, bestCommonB...), + } +} + +// DiffCleanupSemantic reduces the number of edits by eliminating semantically trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupSemantic(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + equalities := make([]int, 0, len(diffs)) + + var lastequality string + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer int // Index of current position. + // Number of characters that changed prior to the equality. + var lengthInsertions1, lengthDeletions1 int + // Number of characters that changed after the equality. + var lengthInsertions2, lengthDeletions2 int + + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { + // Equality found. + equalities = append(equalities, pointer) + lengthInsertions1 = lengthInsertions2 + lengthDeletions1 = lengthDeletions2 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = diffs[pointer].Text + } else { + // An insertion or deletion. + + if diffs[pointer].Type == DiffInsert { + lengthInsertions2 += len(diffs[pointer].Text) + } else { + lengthDeletions2 += len(diffs[pointer].Text) + } + // Eliminate an equality that is smaller or equal to the edits on both sides of it. + difference1 := int(math.Max(float64(lengthInsertions1), float64(lengthDeletions1))) + difference2 := int(math.Max(float64(lengthInsertions2), float64(lengthDeletions2))) + if len(lastequality) > 0 && + (len(lastequality) <= difference1) && + (len(lastequality) <= difference2) { + // Duplicate record. + insPoint := equalities[len(equalities)-1] + diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities[:len(equalities)-1] + + if len(equalities) > 0 { + equalities = equalities[:len(equalities)-1] + } + pointer = -1 + if len(equalities) > 0 { + pointer = equalities[len(equalities)-1] + } + + lengthInsertions1 = 0 // Reset the counters. + lengthDeletions1 = 0 + lengthInsertions2 = 0 + lengthDeletions2 = 0 + lastequality = "" + changes = true + } + } + pointer++ + } + + // Normalize the diff. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + diffs = dmp.DiffCleanupSemanticLossless(diffs) + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1 + for pointer < len(diffs) { + if diffs[pointer-1].Type == DiffDelete && + diffs[pointer].Type == DiffInsert { + deletion := diffs[pointer-1].Text + insertion := diffs[pointer].Text + overlapLength1 := dmp.DiffCommonOverlap(deletion, insertion) + overlapLength2 := dmp.DiffCommonOverlap(insertion, deletion) + if overlapLength1 >= overlapLength2 { + if float64(overlapLength1) >= float64(len(deletion))/2 || + float64(overlapLength1) >= float64(len(insertion))/2 { + + // Overlap found. Insert an equality and trim the surrounding edits. + diffs = splice(diffs, pointer, 0, Diff{DiffEqual, insertion[:overlapLength1]}) + diffs[pointer-1].Text = + deletion[0 : len(deletion)-overlapLength1] + diffs[pointer+1].Text = insertion[overlapLength1:] + pointer++ + } + } else { + if float64(overlapLength2) >= float64(len(deletion))/2 || + float64(overlapLength2) >= float64(len(insertion))/2 { + // Reverse overlap found. Insert an equality and swap and trim the surrounding edits. + overlap := Diff{DiffEqual, deletion[:overlapLength2]} + diffs = splice(diffs, pointer, 0, overlap) + diffs[pointer-1].Type = DiffInsert + diffs[pointer-1].Text = insertion[0 : len(insertion)-overlapLength2] + diffs[pointer+1].Type = DiffDelete + diffs[pointer+1].Text = deletion[overlapLength2:] + pointer++ + } + } + pointer++ + } + pointer++ + } + + return diffs +} + +// Define some regex patterns for matching boundaries. +var ( + nonAlphaNumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]`) + whitespaceRegex = regexp.MustCompile(`\s`) + linebreakRegex = regexp.MustCompile(`[\r\n]`) + blanklineEndRegex = regexp.MustCompile(`\n\r?\n$`) + blanklineStartRegex = regexp.MustCompile(`^\r?\n\r?\n`) +) + +// diffCleanupSemanticScore computes a score representing whether the internal boundary falls on logical boundaries. +// Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables. +func diffCleanupSemanticScore(one, two string) int { + if len(one) == 0 || len(two) == 0 { + // Edges are the best. + return 6 + } + + // Each port of this function behaves slightly differently due to subtle differences in each language's definition of things like 'whitespace'. Since this function's purpose is largely cosmetic, the choice has been made to use each language's native features rather than force total conformity. + rune1, _ := utf8.DecodeLastRuneInString(one) + rune2, _ := utf8.DecodeRuneInString(two) + char1 := string(rune1) + char2 := string(rune2) + + nonAlphaNumeric1 := nonAlphaNumericRegex.MatchString(char1) + nonAlphaNumeric2 := nonAlphaNumericRegex.MatchString(char2) + whitespace1 := nonAlphaNumeric1 && whitespaceRegex.MatchString(char1) + whitespace2 := nonAlphaNumeric2 && whitespaceRegex.MatchString(char2) + lineBreak1 := whitespace1 && linebreakRegex.MatchString(char1) + lineBreak2 := whitespace2 && linebreakRegex.MatchString(char2) + blankLine1 := lineBreak1 && blanklineEndRegex.MatchString(one) + blankLine2 := lineBreak2 && blanklineEndRegex.MatchString(two) + + if blankLine1 || blankLine2 { + // Five points for blank lines. + return 5 + } else if lineBreak1 || lineBreak2 { + // Four points for line breaks. + return 4 + } else if nonAlphaNumeric1 && !whitespace1 && whitespace2 { + // Three points for end of sentences. + return 3 + } else if whitespace1 || whitespace2 { + // Two points for whitespace. + return 2 + } else if nonAlphaNumeric1 || nonAlphaNumeric2 { + // One point for non-alphanumeric. + return 1 + } + return 0 +} + +// DiffCleanupSemanticLossless looks for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. +// E.g: The cat came. -> The cat came. +func (dmp *DiffMatchPatch) DiffCleanupSemanticLossless(diffs []Diff) []Diff { + pointer := 1 + + // Intentionally ignore the first and last element (don't need checking). + for pointer < len(diffs)-1 { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + + // This is a single edit surrounded by equalities. + equality1 := diffs[pointer-1].Text + edit := diffs[pointer].Text + equality2 := diffs[pointer+1].Text + + // First, shift the edit as far left as possible. + commonOffset := dmp.DiffCommonSuffix(equality1, edit) + if commonOffset > 0 { + commonString := edit[len(edit)-commonOffset:] + equality1 = equality1[0 : len(equality1)-commonOffset] + edit = commonString + edit[:len(edit)-commonOffset] + equality2 = commonString + equality2 + } + + // Second, step character by character right, looking for the best fit. + bestEquality1 := equality1 + bestEdit := edit + bestEquality2 := equality2 + bestScore := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + + for len(edit) != 0 && len(equality2) != 0 { + _, sz := utf8.DecodeRuneInString(edit) + if len(equality2) < sz || edit[:sz] != equality2[:sz] { + break + } + equality1 += edit[:sz] + edit = edit[sz:] + equality2[:sz] + equality2 = equality2[sz:] + score := diffCleanupSemanticScore(equality1, edit) + + diffCleanupSemanticScore(edit, equality2) + // The >= encourages trailing rather than leading whitespace on edits. + if score >= bestScore { + bestScore = score + bestEquality1 = equality1 + bestEdit = edit + bestEquality2 = equality2 + } + } + + if diffs[pointer-1].Text != bestEquality1 { + // We have an improvement, save it back to the diff. + if len(bestEquality1) != 0 { + diffs[pointer-1].Text = bestEquality1 + } else { + diffs = splice(diffs, pointer-1, 1) + pointer-- + } + + diffs[pointer].Text = bestEdit + if len(bestEquality2) != 0 { + diffs[pointer+1].Text = bestEquality2 + } else { + diffs = append(diffs[:pointer+1], diffs[pointer+2:]...) + pointer-- + } + } + } + pointer++ + } + + return diffs +} + +// DiffCleanupEfficiency reduces the number of edits by eliminating operationally trivial equalities. +func (dmp *DiffMatchPatch) DiffCleanupEfficiency(diffs []Diff) []Diff { + changes := false + // Stack of indices where equalities are found. + type equality struct { + data int + next *equality + } + var equalities *equality + // Always equal to equalities[equalitiesLength-1][1] + lastequality := "" + pointer := 0 // Index of current position. + // Is there an insertion operation before the last equality. + preIns := false + // Is there a deletion operation before the last equality. + preDel := false + // Is there an insertion operation after the last equality. + postIns := false + // Is there a deletion operation after the last equality. + postDel := false + for pointer < len(diffs) { + if diffs[pointer].Type == DiffEqual { // Equality found. + if len(diffs[pointer].Text) < dmp.DiffEditCost && + (postIns || postDel) { + // Candidate found. + equalities = &equality{ + data: pointer, + next: equalities, + } + preIns = postIns + preDel = postDel + lastequality = diffs[pointer].Text + } else { + // Not a candidate, and can never become one. + equalities = nil + lastequality = "" + } + postIns = false + postDel = false + } else { // An insertion or deletion. + if diffs[pointer].Type == DiffDelete { + postDel = true + } else { + postIns = true + } + + // Five types to be split: + // ABXYCD + // AXCD + // ABXC + // AXCD + // ABXC + var sumPres int + if preIns { + sumPres++ + } + if preDel { + sumPres++ + } + if postIns { + sumPres++ + } + if postDel { + sumPres++ + } + if len(lastequality) > 0 && + ((preIns && preDel && postIns && postDel) || + ((len(lastequality) < dmp.DiffEditCost/2) && sumPres == 3)) { + + insPoint := equalities.data + + // Duplicate record. + diffs = splice(diffs, insPoint, 0, Diff{DiffDelete, lastequality}) + + // Change second copy to insert. + diffs[insPoint+1].Type = DiffInsert + // Throw away the equality we just deleted. + equalities = equalities.next + lastequality = "" + + if preIns && preDel { + // No changes made which could affect previous entry, keep going. + postIns = true + postDel = true + equalities = nil + } else { + if equalities != nil { + equalities = equalities.next + } + if equalities != nil { + pointer = equalities.data + } else { + pointer = -1 + } + postIns = false + postDel = false + } + changes = true + } + } + pointer++ + } + + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffCleanupMerge reorders and merges like edit sections. Merge equalities. +// Any edit section can move as long as it doesn't cross an equality. +func (dmp *DiffMatchPatch) DiffCleanupMerge(diffs []Diff) []Diff { + // Add a dummy entry at the end. + diffs = append(diffs, Diff{DiffEqual, ""}) + pointer := 0 + countDelete := 0 + countInsert := 0 + commonlength := 0 + textDelete := []rune(nil) + textInsert := []rune(nil) + + for pointer < len(diffs) { + switch diffs[pointer].Type { + case DiffInsert: + countInsert++ + textInsert = append(textInsert, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffDelete: + countDelete++ + textDelete = append(textDelete, []rune(diffs[pointer].Text)...) + pointer++ + break + case DiffEqual: + // Upon reaching an equality, check for prior redundancies. + if countDelete+countInsert > 1 { + if countDelete != 0 && countInsert != 0 { + // Factor out any common prefixies. + commonlength = commonPrefixLength(textInsert, textDelete) + if commonlength != 0 { + x := pointer - countDelete - countInsert + if x > 0 && diffs[x-1].Type == DiffEqual { + diffs[x-1].Text += string(textInsert[:commonlength]) + } else { + diffs = append([]Diff{Diff{DiffEqual, string(textInsert[:commonlength])}}, diffs...) + pointer++ + } + textInsert = textInsert[commonlength:] + textDelete = textDelete[commonlength:] + } + // Factor out any common suffixies. + commonlength = commonSuffixLength(textInsert, textDelete) + if commonlength != 0 { + insertIndex := len(textInsert) - commonlength + deleteIndex := len(textDelete) - commonlength + diffs[pointer].Text = string(textInsert[insertIndex:]) + diffs[pointer].Text + textInsert = textInsert[:insertIndex] + textDelete = textDelete[:deleteIndex] + } + } + // Delete the offending records and add the merged ones. + if countDelete == 0 { + diffs = splice(diffs, pointer-countInsert, + countDelete+countInsert, + Diff{DiffInsert, string(textInsert)}) + } else if countInsert == 0 { + diffs = splice(diffs, pointer-countDelete, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}) + } else { + diffs = splice(diffs, pointer-countDelete-countInsert, + countDelete+countInsert, + Diff{DiffDelete, string(textDelete)}, + Diff{DiffInsert, string(textInsert)}) + } + + pointer = pointer - countDelete - countInsert + 1 + if countDelete != 0 { + pointer++ + } + if countInsert != 0 { + pointer++ + } + } else if pointer != 0 && diffs[pointer-1].Type == DiffEqual { + // Merge this equality with the previous one. + diffs[pointer-1].Text += diffs[pointer].Text + diffs = append(diffs[:pointer], diffs[pointer+1:]...) + } else { + pointer++ + } + countInsert = 0 + countDelete = 0 + textDelete = nil + textInsert = nil + break + } + } + + if len(diffs[len(diffs)-1].Text) == 0 { + diffs = diffs[0 : len(diffs)-1] // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities which can be shifted sideways to eliminate an equality. E.g: ABAC -> ABAC + changes := false + pointer = 1 + // Intentionally ignore the first and last element (don't need checking). + for pointer < (len(diffs) - 1) { + if diffs[pointer-1].Type == DiffEqual && + diffs[pointer+1].Type == DiffEqual { + // This is a single edit surrounded by equalities. + if strings.HasSuffix(diffs[pointer].Text, diffs[pointer-1].Text) { + // Shift the edit over the previous equality. + diffs[pointer].Text = diffs[pointer-1].Text + + diffs[pointer].Text[:len(diffs[pointer].Text)-len(diffs[pointer-1].Text)] + diffs[pointer+1].Text = diffs[pointer-1].Text + diffs[pointer+1].Text + diffs = splice(diffs, pointer-1, 1) + changes = true + } else if strings.HasPrefix(diffs[pointer].Text, diffs[pointer+1].Text) { + // Shift the edit over the next equality. + diffs[pointer-1].Text += diffs[pointer+1].Text + diffs[pointer].Text = + diffs[pointer].Text[len(diffs[pointer+1].Text):] + diffs[pointer+1].Text + diffs = splice(diffs, pointer+1, 1) + changes = true + } + } + pointer++ + } + + // If shifts were made, the diff needs reordering and another shift sweep. + if changes { + diffs = dmp.DiffCleanupMerge(diffs) + } + + return diffs +} + +// DiffXIndex returns the equivalent location in s2. +func (dmp *DiffMatchPatch) DiffXIndex(diffs []Diff, loc int) int { + chars1 := 0 + chars2 := 0 + lastChars1 := 0 + lastChars2 := 0 + lastDiff := Diff{} + for i := 0; i < len(diffs); i++ { + aDiff := diffs[i] + if aDiff.Type != DiffInsert { + // Equality or deletion. + chars1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + // Equality or insertion. + chars2 += len(aDiff.Text) + } + if chars1 > loc { + // Overshot the location. + lastDiff = aDiff + break + } + lastChars1 = chars1 + lastChars2 = chars2 + } + if lastDiff.Type == DiffDelete { + // The location was deleted. + return lastChars2 + } + // Add the remaining character length. + return lastChars2 + (loc - lastChars1) +} + +// DiffPrettyHtml converts a []Diff into a pretty HTML report. +// It is intended as an example from which to write one's own display functions. +func (dmp *DiffMatchPatch) DiffPrettyHtml(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := strings.Replace(html.EscapeString(diff.Text), "\n", "¶
", -1) + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffDelete: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + case DiffEqual: + _, _ = buff.WriteString("") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("") + } + } + return buff.String() +} + +// DiffPrettyText converts a []Diff into a colored text report. +func (dmp *DiffMatchPatch) DiffPrettyText(diffs []Diff) string { + var buff bytes.Buffer + for _, diff := range diffs { + text := diff.Text + + switch diff.Type { + case DiffInsert: + _, _ = buff.WriteString("\x1b[32m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffDelete: + _, _ = buff.WriteString("\x1b[31m") + _, _ = buff.WriteString(text) + _, _ = buff.WriteString("\x1b[0m") + case DiffEqual: + _, _ = buff.WriteString(text) + } + } + + return buff.String() +} + +// DiffText1 computes and returns the source text (all equalities and deletions). +func (dmp *DiffMatchPatch) DiffText1(diffs []Diff) string { + //StringBuilder text = new StringBuilder() + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffInsert { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffText2 computes and returns the destination text (all equalities and insertions). +func (dmp *DiffMatchPatch) DiffText2(diffs []Diff) string { + var text bytes.Buffer + + for _, aDiff := range diffs { + if aDiff.Type != DiffDelete { + _, _ = text.WriteString(aDiff.Text) + } + } + return text.String() +} + +// DiffLevenshtein computes the Levenshtein distance that is the number of inserted, deleted or substituted characters. +func (dmp *DiffMatchPatch) DiffLevenshtein(diffs []Diff) int { + levenshtein := 0 + insertions := 0 + deletions := 0 + + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + insertions += utf8.RuneCountInString(aDiff.Text) + case DiffDelete: + deletions += utf8.RuneCountInString(aDiff.Text) + case DiffEqual: + // A deletion and an insertion is one substitution. + levenshtein += max(insertions, deletions) + insertions = 0 + deletions = 0 + } + } + + levenshtein += max(insertions, deletions) + return levenshtein +} + +// DiffToDelta crushes the diff into an encoded string which describes the operations required to transform text1 into text2. +// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. +func (dmp *DiffMatchPatch) DiffToDelta(diffs []Diff) string { + var text bytes.Buffer + for _, aDiff := range diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\t") + break + case DiffDelete: + _, _ = text.WriteString("-") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + case DiffEqual: + _, _ = text.WriteString("=") + _, _ = text.WriteString(strconv.Itoa(utf8.RuneCountInString(aDiff.Text))) + _, _ = text.WriteString("\t") + break + } + } + delta := text.String() + if len(delta) != 0 { + // Strip off trailing tab character. + delta = delta[0 : utf8.RuneCountInString(delta)-1] + delta = unescaper.Replace(delta) + } + return delta +} + +// DiffFromDelta given the original text1, and an encoded string which describes the operations required to transform text1 into text2, comAdde the full diff. +func (dmp *DiffMatchPatch) DiffFromDelta(text1 string, delta string) (diffs []Diff, err error) { + i := 0 + runes := []rune(text1) + + for _, token := range strings.Split(delta, "\t") { + if len(token) == 0 { + // Blank tokens are ok (from a trailing \t). + continue + } + + // Each token begins with a one character parameter which specifies the operation of this token (delete, insert, equality). + param := token[1:] + + switch op := token[0]; op { + case '+': + // Decode would Diff all "+" to " " + param = strings.Replace(param, "+", "%2b", -1) + param, err = url.QueryUnescape(param) + if err != nil { + return nil, err + } + if !utf8.ValidString(param) { + return nil, fmt.Errorf("invalid UTF-8 token: %q", param) + } + + diffs = append(diffs, Diff{DiffInsert, param}) + case '=', '-': + n, err := strconv.ParseInt(param, 10, 0) + if err != nil { + return nil, err + } else if n < 0 { + return nil, errors.New("Negative number in DiffFromDelta: " + param) + } + + i += int(n) + // Break out if we are out of bounds, go1.6 can't handle this very well + if i > len(runes) { + break + } + // Remember that string slicing is by byte - we want by rune here. + text := string(runes[i-int(n) : i]) + + if op == '=' { + diffs = append(diffs, Diff{DiffEqual, text}) + } else { + diffs = append(diffs, Diff{DiffDelete, text}) + } + default: + // Anything else is an error. + return nil, errors.New("Invalid diff operation in DiffFromDelta: " + string(token[0])) + } + } + + if i != len(runes) { + return nil, fmt.Errorf("Delta length (%v) is different from source text length (%v)", i, len(text1)) + } + + return diffs, nil +} diff --git a/v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go b/v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go new file mode 100644 index 0000000..d3acc32 --- /dev/null +++ b/v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go @@ -0,0 +1,46 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +// Package diffmatchpatch offers robust algorithms to perform the operations required for synchronizing plain text. +package diffmatchpatch + +import ( + "time" +) + +// DiffMatchPatch holds the configuration for diff-match-patch operations. +type DiffMatchPatch struct { + // Number of seconds to map a diff before giving up (0 for infinity). + DiffTimeout time.Duration + // Cost of an empty edit operation in terms of edit characters. + DiffEditCost int + // How far to search for a match (0 = exact location, 1000+ = broad match). A match this many characters away from the expected location will add 1.0 to the score (0.0 is a perfect match). + MatchDistance int + // When deleting a large block of text (over ~64 characters), how close do the contents have to be to match the expected contents. (0.0 = perfection, 1.0 = very loose). Note that MatchThreshold controls how closely the end points of a delete need to match. + PatchDeleteThreshold float64 + // Chunk size for context length. + PatchMargin int + // The number of bits in an int. + MatchMaxBits int + // At what point is no match declared (0.0 = perfection, 1.0 = very loose). + MatchThreshold float64 +} + +// New creates a new DiffMatchPatch object with default parameters. +func New() *DiffMatchPatch { + // Defaults. + return &DiffMatchPatch{ + DiffTimeout: time.Second, + DiffEditCost: 4, + MatchThreshold: 0.5, + MatchDistance: 1000, + PatchDeleteThreshold: 0.5, + PatchMargin: 4, + MatchMaxBits: 32, + } +} diff --git a/v2/should/internal/go-diff/diffmatchpatch/match.go b/v2/should/internal/go-diff/diffmatchpatch/match.go new file mode 100644 index 0000000..17374e1 --- /dev/null +++ b/v2/should/internal/go-diff/diffmatchpatch/match.go @@ -0,0 +1,160 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "math" +) + +// MatchMain locates the best instance of 'pattern' in 'text' near 'loc'. +// Returns -1 if no match found. +func (dmp *DiffMatchPatch) MatchMain(text, pattern string, loc int) int { + // Check for null inputs not needed since null can't be passed in C#. + + loc = int(math.Max(0, math.Min(float64(loc), float64(len(text))))) + if text == pattern { + // Shortcut (potentially not guaranteed by the algorithm) + return 0 + } else if len(text) == 0 { + // Nothing to match. + return -1 + } else if loc+len(pattern) <= len(text) && text[loc:loc+len(pattern)] == pattern { + // Perfect match at the perfect spot! (Includes case of null pattern) + return loc + } + // Do a fuzzy compare. + return dmp.MatchBitap(text, pattern, loc) +} + +// MatchBitap locates the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. +// Returns -1 if no match was found. +func (dmp *DiffMatchPatch) MatchBitap(text, pattern string, loc int) int { + // Initialise the alphabet. + s := dmp.MatchAlphabet(pattern) + + // Highest score beyond which we give up. + scoreThreshold := dmp.MatchThreshold + // Is there a nearby exact match? (speedup) + bestLoc := indexOf(text, pattern, loc) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + // What about in the other direction? (speedup) + bestLoc = lastIndexOf(text, pattern, loc+len(pattern)) + if bestLoc != -1 { + scoreThreshold = math.Min(dmp.matchBitapScore(0, bestLoc, loc, + pattern), scoreThreshold) + } + } + + // Initialise the bit arrays. + matchmask := 1 << uint((len(pattern) - 1)) + bestLoc = -1 + + var binMin, binMid int + binMax := len(pattern) + len(text) + lastRd := []int{} + for d := 0; d < len(pattern); d++ { + // Scan for the best match; each iteration allows for one more error. Run a binary search to determine how far from 'loc' we can stray at this error level. + binMin = 0 + binMid = binMax + for binMin < binMid { + if dmp.matchBitapScore(d, loc+binMid, loc, pattern) <= scoreThreshold { + binMin = binMid + } else { + binMax = binMid + } + binMid = (binMax-binMin)/2 + binMin + } + // Use the result from this iteration as the maximum for the next. + binMax = binMid + start := int(math.Max(1, float64(loc-binMid+1))) + finish := int(math.Min(float64(loc+binMid), float64(len(text))) + float64(len(pattern))) + + rd := make([]int, finish+2) + rd[finish+1] = (1 << uint(d)) - 1 + + for j := finish; j >= start; j-- { + var charMatch int + if len(text) <= j-1 { + // Out of range. + charMatch = 0 + } else if _, ok := s[text[j-1]]; !ok { + charMatch = 0 + } else { + charMatch = s[text[j-1]] + } + + if d == 0 { + // First pass: exact match. + rd[j] = ((rd[j+1] << 1) | 1) & charMatch + } else { + // Subsequent passes: fuzzy match. + rd[j] = ((rd[j+1]<<1)|1)&charMatch | (((lastRd[j+1] | lastRd[j]) << 1) | 1) | lastRd[j+1] + } + if (rd[j] & matchmask) != 0 { + score := dmp.matchBitapScore(d, j-1, loc, pattern) + // This match will almost certainly be better than any existing match. But check anyway. + if score <= scoreThreshold { + // Told you so. + scoreThreshold = score + bestLoc = j - 1 + if bestLoc > loc { + // When passing loc, don't exceed our current distance from loc. + start = int(math.Max(1, float64(2*loc-bestLoc))) + } else { + // Already passed loc, downhill from here on in. + break + } + } + } + } + if dmp.matchBitapScore(d+1, loc, loc, pattern) > scoreThreshold { + // No hope for a (better) match at greater error levels. + break + } + lastRd = rd + } + return bestLoc +} + +// matchBitapScore computes and returns the score for a match with e errors and x location. +func (dmp *DiffMatchPatch) matchBitapScore(e, x, loc int, pattern string) float64 { + accuracy := float64(e) / float64(len(pattern)) + proximity := math.Abs(float64(loc - x)) + if dmp.MatchDistance == 0 { + // Dodge divide by zero error. + if proximity == 0 { + return accuracy + } + + return 1.0 + } + return accuracy + (proximity / float64(dmp.MatchDistance)) +} + +// MatchAlphabet initialises the alphabet for the Bitap algorithm. +func (dmp *DiffMatchPatch) MatchAlphabet(pattern string) map[byte]int { + s := map[byte]int{} + charPattern := []byte(pattern) + for _, c := range charPattern { + _, ok := s[c] + if !ok { + s[c] = 0 + } + } + i := 0 + + for _, c := range charPattern { + value := s[c] | int(uint(1)<= Operation(len(_Operation_index)-1) { + return fmt.Sprintf("Operation(%d)", i+-1) + } + return _Operation_name[_Operation_index[i]:_Operation_index[i+1]] +} diff --git a/v2/should/internal/go-diff/diffmatchpatch/patch.go b/v2/should/internal/go-diff/diffmatchpatch/patch.go new file mode 100644 index 0000000..80b8abf --- /dev/null +++ b/v2/should/internal/go-diff/diffmatchpatch/patch.go @@ -0,0 +1,556 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "bytes" + "errors" + "math" + "net/url" + "regexp" + "strconv" + "strings" +) + +// Patch represents one patch operation. +type Patch struct { + diffs []Diff + Start1 int + Start2 int + Length1 int + Length2 int +} + +// String emulates GNU diff's format. +// Header: @@ -382,8 +481,9 @@ +// Indices are printed as 1-based, not 0-based. +func (p *Patch) String() string { + var coords1, coords2 string + + if p.Length1 == 0 { + coords1 = strconv.Itoa(p.Start1) + ",0" + } else if p.Length1 == 1 { + coords1 = strconv.Itoa(p.Start1 + 1) + } else { + coords1 = strconv.Itoa(p.Start1+1) + "," + strconv.Itoa(p.Length1) + } + + if p.Length2 == 0 { + coords2 = strconv.Itoa(p.Start2) + ",0" + } else if p.Length2 == 1 { + coords2 = strconv.Itoa(p.Start2 + 1) + } else { + coords2 = strconv.Itoa(p.Start2+1) + "," + strconv.Itoa(p.Length2) + } + + var text bytes.Buffer + _, _ = text.WriteString("@@ -" + coords1 + " +" + coords2 + " @@\n") + + // Escape the body of the patch with %xx notation. + for _, aDiff := range p.diffs { + switch aDiff.Type { + case DiffInsert: + _, _ = text.WriteString("+") + case DiffDelete: + _, _ = text.WriteString("-") + case DiffEqual: + _, _ = text.WriteString(" ") + } + + _, _ = text.WriteString(strings.Replace(url.QueryEscape(aDiff.Text), "+", " ", -1)) + _, _ = text.WriteString("\n") + } + + return unescaper.Replace(text.String()) +} + +// PatchAddContext increases the context until it is unique, but doesn't let the pattern expand beyond MatchMaxBits. +func (dmp *DiffMatchPatch) PatchAddContext(patch Patch, text string) Patch { + if len(text) == 0 { + return patch + } + + pattern := text[patch.Start2 : patch.Start2+patch.Length1] + padding := 0 + + // Look for the first and last matches of pattern in text. If two different matches are found, increase the pattern length. + for strings.Index(text, pattern) != strings.LastIndex(text, pattern) && + len(pattern) < dmp.MatchMaxBits-2*dmp.PatchMargin { + padding += dmp.PatchMargin + maxStart := max(0, patch.Start2-padding) + minEnd := min(len(text), patch.Start2+patch.Length1+padding) + pattern = text[maxStart:minEnd] + } + // Add one chunk for good luck. + padding += dmp.PatchMargin + + // Add the prefix. + prefix := text[max(0, patch.Start2-padding):patch.Start2] + if len(prefix) != 0 { + patch.diffs = append([]Diff{Diff{DiffEqual, prefix}}, patch.diffs...) + } + // Add the suffix. + suffix := text[patch.Start2+patch.Length1 : min(len(text), patch.Start2+patch.Length1+padding)] + if len(suffix) != 0 { + patch.diffs = append(patch.diffs, Diff{DiffEqual, suffix}) + } + + // Roll back the start points. + patch.Start1 -= len(prefix) + patch.Start2 -= len(prefix) + // Extend the lengths. + patch.Length1 += len(prefix) + len(suffix) + patch.Length2 += len(prefix) + len(suffix) + + return patch +} + +// PatchMake computes a list of patches. +func (dmp *DiffMatchPatch) PatchMake(opt ...any) []Patch { + if len(opt) == 1 { + diffs, _ := opt[0].([]Diff) + text1 := dmp.DiffText1(diffs) + return dmp.PatchMake(text1, diffs) + } else if len(opt) == 2 { + text1 := opt[0].(string) + switch t := opt[1].(type) { + case string: + diffs := dmp.DiffMain(text1, t, true) + if len(diffs) > 2 { + diffs = dmp.DiffCleanupSemantic(diffs) + diffs = dmp.DiffCleanupEfficiency(diffs) + } + return dmp.PatchMake(text1, diffs) + case []Diff: + return dmp.patchMake2(text1, t) + } + } else if len(opt) == 3 { + return dmp.PatchMake(opt[0], opt[2]) + } + return []Patch{} +} + +// patchMake2 computes a list of patches to turn text1 into text2. +// text2 is not provided, diffs are the delta between text1 and text2. +func (dmp *DiffMatchPatch) patchMake2(text1 string, diffs []Diff) []Patch { + // Check for null inputs not needed since null can't be passed in C#. + patches := []Patch{} + if len(diffs) == 0 { + return patches // Get rid of the null case. + } + + patch := Patch{} + charCount1 := 0 // Number of characters into the text1 string. + charCount2 := 0 // Number of characters into the text2 string. + // Start with text1 (prepatchText) and apply the diffs until we arrive at text2 (postpatchText). We recreate the patches one by one to determine context info. + prepatchText := text1 + postpatchText := text1 + + for i, aDiff := range diffs { + if len(patch.diffs) == 0 && aDiff.Type != DiffEqual { + // A new patch starts here. + patch.Start1 = charCount1 + patch.Start2 = charCount2 + } + + switch aDiff.Type { + case DiffInsert: + patch.diffs = append(patch.diffs, aDiff) + patch.Length2 += len(aDiff.Text) + postpatchText = postpatchText[:charCount2] + + aDiff.Text + postpatchText[charCount2:] + case DiffDelete: + patch.Length1 += len(aDiff.Text) + patch.diffs = append(patch.diffs, aDiff) + postpatchText = postpatchText[:charCount2] + postpatchText[charCount2+len(aDiff.Text):] + case DiffEqual: + if len(aDiff.Text) <= 2*dmp.PatchMargin && + len(patch.diffs) != 0 && i != len(diffs)-1 { + // Small equality inside a patch. + patch.diffs = append(patch.diffs, aDiff) + patch.Length1 += len(aDiff.Text) + patch.Length2 += len(aDiff.Text) + } + if len(aDiff.Text) >= 2*dmp.PatchMargin { + // Time for a new patch. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + patch = Patch{} + // Unlike Unidiff, our patch lists have a rolling context. http://code.google.com/p/google-diff-match-patch/wiki/Unidiff Update prepatch text & pos to reflect the application of the just completed patch. + prepatchText = postpatchText + charCount1 = charCount2 + } + } + } + + // Update the current character count. + if aDiff.Type != DiffInsert { + charCount1 += len(aDiff.Text) + } + if aDiff.Type != DiffDelete { + charCount2 += len(aDiff.Text) + } + } + + // Pick up the leftover patch if not empty. + if len(patch.diffs) != 0 { + patch = dmp.PatchAddContext(patch, prepatchText) + patches = append(patches, patch) + } + + return patches +} + +// PatchDeepCopy returns an array that is identical to a given an array of patches. +func (dmp *DiffMatchPatch) PatchDeepCopy(patches []Patch) []Patch { + patchesCopy := []Patch{} + for _, aPatch := range patches { + patchCopy := Patch{} + for _, aDiff := range aPatch.diffs { + patchCopy.diffs = append(patchCopy.diffs, Diff{ + aDiff.Type, + aDiff.Text, + }) + } + patchCopy.Start1 = aPatch.Start1 + patchCopy.Start2 = aPatch.Start2 + patchCopy.Length1 = aPatch.Length1 + patchCopy.Length2 = aPatch.Length2 + patchesCopy = append(patchesCopy, patchCopy) + } + return patchesCopy +} + +// PatchApply merges a set of patches onto the text. Returns a patched text, as well as an array of true/false values indicating which patches were applied. +func (dmp *DiffMatchPatch) PatchApply(patches []Patch, text string) (string, []bool) { + if len(patches) == 0 { + return text, []bool{} + } + + // Deep copy the patches so that no changes are made to originals. + patches = dmp.PatchDeepCopy(patches) + + nullPadding := dmp.PatchAddPadding(patches) + text = nullPadding + text + nullPadding + patches = dmp.PatchSplitMax(patches) + + x := 0 + // delta keeps track of the offset between the expected and actual location of the previous patch. If there are patches expected at positions 10 and 20, but the first patch was found at 12, delta is 2 and the second patch has an effective expected position of 22. + delta := 0 + results := make([]bool, len(patches)) + for _, aPatch := range patches { + expectedLoc := aPatch.Start2 + delta + text1 := dmp.DiffText1(aPatch.diffs) + var startLoc int + endLoc := -1 + if len(text1) > dmp.MatchMaxBits { + // PatchSplitMax will only provide an oversized pattern in the case of a monster delete. + startLoc = dmp.MatchMain(text, text1[:dmp.MatchMaxBits], expectedLoc) + if startLoc != -1 { + endLoc = dmp.MatchMain(text, + text1[len(text1)-dmp.MatchMaxBits:], expectedLoc+len(text1)-dmp.MatchMaxBits) + if endLoc == -1 || startLoc >= endLoc { + // Can't find valid trailing context. Drop this patch. + startLoc = -1 + } + } + } else { + startLoc = dmp.MatchMain(text, text1, expectedLoc) + } + if startLoc == -1 { + // No match found. :( + results[x] = false + // Subtract the delta for this failed patch from subsequent patches. + delta -= aPatch.Length2 - aPatch.Length1 + } else { + // Found a match. :) + results[x] = true + delta = startLoc - expectedLoc + var text2 string + if endLoc == -1 { + text2 = text[startLoc:int(math.Min(float64(startLoc+len(text1)), float64(len(text))))] + } else { + text2 = text[startLoc:int(math.Min(float64(endLoc+dmp.MatchMaxBits), float64(len(text))))] + } + if text1 == text2 { + // Perfect match, just shove the Replacement text in. + text = text[:startLoc] + dmp.DiffText2(aPatch.diffs) + text[startLoc+len(text1):] + } else { + // Imperfect match. Run a diff to get a framework of equivalent indices. + diffs := dmp.DiffMain(text1, text2, false) + if len(text1) > dmp.MatchMaxBits && float64(dmp.DiffLevenshtein(diffs))/float64(len(text1)) > dmp.PatchDeleteThreshold { + // The end points match, but the content is unacceptably bad. + results[x] = false + } else { + diffs = dmp.DiffCleanupSemanticLossless(diffs) + index1 := 0 + for _, aDiff := range aPatch.diffs { + if aDiff.Type != DiffEqual { + index2 := dmp.DiffXIndex(diffs, index1) + if aDiff.Type == DiffInsert { + // Insertion + text = text[:startLoc+index2] + aDiff.Text + text[startLoc+index2:] + } else if aDiff.Type == DiffDelete { + // Deletion + startIndex := startLoc + index2 + text = text[:startIndex] + + text[startIndex+dmp.DiffXIndex(diffs, index1+len(aDiff.Text))-index2:] + } + } + if aDiff.Type != DiffDelete { + index1 += len(aDiff.Text) + } + } + } + } + } + x++ + } + // Strip the padding off. + text = text[len(nullPadding) : len(nullPadding)+(len(text)-2*len(nullPadding))] + return text, results +} + +// PatchAddPadding adds some padding on text start and end so that edges can match something. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchAddPadding(patches []Patch) string { + paddingLength := dmp.PatchMargin + nullPadding := "" + for x := 1; x <= paddingLength; x++ { + nullPadding += string(rune(x)) + } + + // Bump all the patches forward. + for i := range patches { + patches[i].Start1 += paddingLength + patches[i].Start2 += paddingLength + } + + // Add some padding on start of first diff. + if len(patches[0].diffs) == 0 || patches[0].diffs[0].Type != DiffEqual { + // Add nullPadding equality. + patches[0].diffs = append([]Diff{Diff{DiffEqual, nullPadding}}, patches[0].diffs...) + patches[0].Start1 -= paddingLength // Should be 0. + patches[0].Start2 -= paddingLength // Should be 0. + patches[0].Length1 += paddingLength + patches[0].Length2 += paddingLength + } else if paddingLength > len(patches[0].diffs[0].Text) { + // Grow first equality. + extraLength := paddingLength - len(patches[0].diffs[0].Text) + patches[0].diffs[0].Text = nullPadding[len(patches[0].diffs[0].Text):] + patches[0].diffs[0].Text + patches[0].Start1 -= extraLength + patches[0].Start2 -= extraLength + patches[0].Length1 += extraLength + patches[0].Length2 += extraLength + } + + // Add some padding on end of last diff. + last := len(patches) - 1 + if len(patches[last].diffs) == 0 || patches[last].diffs[len(patches[last].diffs)-1].Type != DiffEqual { + // Add nullPadding equality. + patches[last].diffs = append(patches[last].diffs, Diff{DiffEqual, nullPadding}) + patches[last].Length1 += paddingLength + patches[last].Length2 += paddingLength + } else if paddingLength > len(patches[last].diffs[len(patches[last].diffs)-1].Text) { + // Grow last equality. + lastDiff := patches[last].diffs[len(patches[last].diffs)-1] + extraLength := paddingLength - len(lastDiff.Text) + patches[last].diffs[len(patches[last].diffs)-1].Text += nullPadding[:extraLength] + patches[last].Length1 += extraLength + patches[last].Length2 += extraLength + } + + return nullPadding +} + +// PatchSplitMax looks through the patches and breaks up any which are longer than the maximum limit of the match algorithm. +// Intended to be called only from within patchApply. +func (dmp *DiffMatchPatch) PatchSplitMax(patches []Patch) []Patch { + patchSize := dmp.MatchMaxBits + for x := 0; x < len(patches); x++ { + if patches[x].Length1 <= patchSize { + continue + } + bigpatch := patches[x] + // Remove the big old patch. + patches = append(patches[:x], patches[x+1:]...) + x-- + + Start1 := bigpatch.Start1 + Start2 := bigpatch.Start2 + precontext := "" + for len(bigpatch.diffs) != 0 { + // Create one of several smaller patches. + patch := Patch{} + empty := true + patch.Start1 = Start1 - len(precontext) + patch.Start2 = Start2 - len(precontext) + if len(precontext) != 0 { + patch.Length1 = len(precontext) + patch.Length2 = len(precontext) + patch.diffs = append(patch.diffs, Diff{DiffEqual, precontext}) + } + for len(bigpatch.diffs) != 0 && patch.Length1 < patchSize-dmp.PatchMargin { + diffType := bigpatch.diffs[0].Type + diffText := bigpatch.diffs[0].Text + if diffType == DiffInsert { + // Insertions are harmless. + patch.Length2 += len(diffText) + Start2 += len(diffText) + patch.diffs = append(patch.diffs, bigpatch.diffs[0]) + bigpatch.diffs = bigpatch.diffs[1:] + empty = false + } else if diffType == DiffDelete && len(patch.diffs) == 1 && patch.diffs[0].Type == DiffEqual && len(diffText) > 2*patchSize { + // This is a large deletion. Let it pass in one chunk. + patch.Length1 += len(diffText) + Start1 += len(diffText) + empty = false + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + bigpatch.diffs = bigpatch.diffs[1:] + } else { + // Deletion or equality. Only take as much as we can stomach. + diffText = diffText[:min(len(diffText), patchSize-patch.Length1-dmp.PatchMargin)] + + patch.Length1 += len(diffText) + Start1 += len(diffText) + if diffType == DiffEqual { + patch.Length2 += len(diffText) + Start2 += len(diffText) + } else { + empty = false + } + patch.diffs = append(patch.diffs, Diff{diffType, diffText}) + if diffText == bigpatch.diffs[0].Text { + bigpatch.diffs = bigpatch.diffs[1:] + } else { + bigpatch.diffs[0].Text = + bigpatch.diffs[0].Text[len(diffText):] + } + } + } + // Compute the head context for the next patch. + precontext = dmp.DiffText2(patch.diffs) + precontext = precontext[max(0, len(precontext)-dmp.PatchMargin):] + + postcontext := "" + // Append the end context for this patch. + if len(dmp.DiffText1(bigpatch.diffs)) > dmp.PatchMargin { + postcontext = dmp.DiffText1(bigpatch.diffs)[:dmp.PatchMargin] + } else { + postcontext = dmp.DiffText1(bigpatch.diffs) + } + + if len(postcontext) != 0 { + patch.Length1 += len(postcontext) + patch.Length2 += len(postcontext) + if len(patch.diffs) != 0 && patch.diffs[len(patch.diffs)-1].Type == DiffEqual { + patch.diffs[len(patch.diffs)-1].Text += postcontext + } else { + patch.diffs = append(patch.diffs, Diff{DiffEqual, postcontext}) + } + } + if !empty { + x++ + patches = append(patches[:x], append([]Patch{patch}, patches[x:]...)...) + } + } + } + return patches +} + +// PatchToText takes a list of patches and returns a textual representation. +func (dmp *DiffMatchPatch) PatchToText(patches []Patch) string { + var text bytes.Buffer + for _, aPatch := range patches { + _, _ = text.WriteString(aPatch.String()) + } + return text.String() +} + +// PatchFromText parses a textual representation of patches and returns a List of Patch objects. +func (dmp *DiffMatchPatch) PatchFromText(textline string) ([]Patch, error) { + patches := []Patch{} + if len(textline) == 0 { + return patches, nil + } + text := strings.Split(textline, "\n") + textPointer := 0 + patchHeader := regexp.MustCompile("^@@ -(\\d+),?(\\d*) \\+(\\d+),?(\\d*) @@$") + + var patch Patch + var sign uint8 + var line string + for textPointer < len(text) { + + if !patchHeader.MatchString(text[textPointer]) { + return patches, errors.New("Invalid patch string: " + text[textPointer]) + } + + patch = Patch{} + m := patchHeader.FindStringSubmatch(text[textPointer]) + + patch.Start1, _ = strconv.Atoi(m[1]) + if len(m[2]) == 0 { + patch.Start1-- + patch.Length1 = 1 + } else if m[2] == "0" { + patch.Length1 = 0 + } else { + patch.Start1-- + patch.Length1, _ = strconv.Atoi(m[2]) + } + + patch.Start2, _ = strconv.Atoi(m[3]) + + if len(m[4]) == 0 { + patch.Start2-- + patch.Length2 = 1 + } else if m[4] == "0" { + patch.Length2 = 0 + } else { + patch.Start2-- + patch.Length2, _ = strconv.Atoi(m[4]) + } + textPointer++ + + for textPointer < len(text) { + if len(text[textPointer]) > 0 { + sign = text[textPointer][0] + } else { + textPointer++ + continue + } + + line = text[textPointer][1:] + line = strings.Replace(line, "+", "%2b", -1) + line, _ = url.QueryUnescape(line) + if sign == '-' { + // Deletion. + patch.diffs = append(patch.diffs, Diff{DiffDelete, line}) + } else if sign == '+' { + // Insertion. + patch.diffs = append(patch.diffs, Diff{DiffInsert, line}) + } else if sign == ' ' { + // Minor equality. + patch.diffs = append(patch.diffs, Diff{DiffEqual, line}) + } else if sign == '@' { + // Start of next patch. + break + } else { + // WTF? + return patches, errors.New("Invalid patch mode '" + string(sign) + "' in: " + string(line)) + } + textPointer++ + } + + patches = append(patches, patch) + } + return patches, nil +} diff --git a/v2/should/internal/go-diff/diffmatchpatch/stringutil.go b/v2/should/internal/go-diff/diffmatchpatch/stringutil.go new file mode 100644 index 0000000..265f29c --- /dev/null +++ b/v2/should/internal/go-diff/diffmatchpatch/stringutil.go @@ -0,0 +1,88 @@ +// Copyright (c) 2012-2016 The go-diff authors. All rights reserved. +// https://github.com/sergi/go-diff +// See the included LICENSE file for license details. +// +// go-diff is a Go implementation of Google's Diff, Match, and Patch library +// Original library is Copyright (c) 2006 Google Inc. +// http://code.google.com/p/google-diff-match-patch/ + +package diffmatchpatch + +import ( + "strings" + "unicode/utf8" +) + +// unescaper unescapes selected chars for compatibility with JavaScript's encodeURI. +// In speed critical applications this could be dropped since the receiving application will certainly decode these fine. Note that this function is case-sensitive. Thus "%3F" would not be unescaped. But this is ok because it is only called with the output of HttpUtility.UrlEncode which returns lowercase hex. Example: "%3f" -> "?", "%24" -> "$", etc. +var unescaper = strings.NewReplacer( + "%21", "!", "%7E", "~", "%27", "'", + "%28", "(", "%29", ")", "%3B", ";", + "%2F", "/", "%3F", "?", "%3A", ":", + "%40", "@", "%26", "&", "%3D", "=", + "%2B", "+", "%24", "$", "%2C", ",", "%23", "#", "%2A", "*") + +// indexOf returns the first index of pattern in str, starting at str[i]. +func indexOf(str string, pattern string, i int) int { + if i > len(str)-1 { + return -1 + } + if i <= 0 { + return strings.Index(str, pattern) + } + ind := strings.Index(str[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +// lastIndexOf returns the last index of pattern in str, starting at str[i]. +func lastIndexOf(str string, pattern string, i int) int { + if i < 0 { + return -1 + } + if i >= len(str) { + return strings.LastIndex(str, pattern) + } + _, size := utf8.DecodeRuneInString(str[i:]) + return strings.LastIndex(str[:i+size], pattern) +} + +// runesIndexOf returns the index of pattern in target, starting at target[i]. +func runesIndexOf(target, pattern []rune, i int) int { + if i > len(target)-1 { + return -1 + } + if i <= 0 { + return runesIndex(target, pattern) + } + ind := runesIndex(target[i:], pattern) + if ind == -1 { + return -1 + } + return ind + i +} + +func runesEqual(r1, r2 []rune) bool { + if len(r1) != len(r2) { + return false + } + for i, c := range r1 { + if c != r2[i] { + return false + } + } + return true +} + +// runesIndex is the equivalent of strings.Index for rune slices. +func runesIndex(r1, r2 []rune) int { + last := len(r1) - len(r2) + for i := 0; i <= last; i++ { + if runesEqual(r1[i:i+len(r2)], r2) { + return i + } + } + return -1 +} diff --git a/v2/should/internal/go-diff/scripts/lint.sh b/v2/should/internal/go-diff/scripts/lint.sh new file mode 100755 index 0000000..3dad05f --- /dev/null +++ b/v2/should/internal/go-diff/scripts/lint.sh @@ -0,0 +1,22 @@ +#!/bin/sh + +if [ -z ${PKG+x} ]; then echo "PKG is not set"; exit 1; fi +if [ -z ${ROOT_DIR+x} ]; then echo "ROOT_DIR is not set"; exit 1; fi + +echo "gofmt:" +OUT=$(gofmt -l $ROOT_DIR) +if [ $(echo "$OUT\c" | wc -l) -ne 0 ]; then echo "$OUT"; PROBLEM=1; fi + +echo "errcheck:" +OUT=$(errcheck $PKG/...) +if [ $(echo "$OUT\c" | wc -l) -ne 0 ]; then echo "$OUT"; PROBLEM=1; fi + +echo "go vet:" +OUT=$(go tool vet -all=true -v=true $ROOT_DIR 2>&1 | grep --invert-match -E "(Checking file|\%p of wrong type|can't check non-constant format)") +if [ $(echo "$OUT\c" | wc -l) -ne 0 ]; then echo "$OUT"; PROBLEM=1; fi + +echo "golint:" +OUT=$(golint $PKG/... | grep --invert-match -E "(method DiffPrettyHtml should be DiffPrettyHTML)") +if [ $(echo "$OUT\c" | wc -l) -ne 0 ]; then echo "$OUT"; PROBLEM=1; fi + +if [ -n "$PROBLEM" ]; then exit 1; fi diff --git a/v2/should/internal/go-diff/testdata/speedtest1.txt b/v2/should/internal/go-diff/testdata/speedtest1.txt new file mode 100644 index 0000000..54b438f --- /dev/null +++ b/v2/should/internal/go-diff/testdata/speedtest1.txt @@ -0,0 +1,230 @@ +This is a '''list of newspapers published by [[Journal Register Company]]'''. + +The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]] and [[Pennsylvania]], organized in six geographic "clusters":[http://www.journalregister.com/newspapers.html Journal Register Company: Our Newspapers], accessed February 10, 2008. + +== Capital-Saratoga == +Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]] +* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]] +* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]] +* Weeklies: +** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]] +** ''Rome Observer'' of [[Rome, New York]] +** ''Life & Times of Utica'' of [[Utica, New York]] + +== Connecticut == +Five dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com]. + +* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]] +* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]] +* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]] + +* [[New Haven Register#Competitors|Elm City Newspapers]] {{WS|ctcentral.com}} +** ''The Advertiser'' of [[East Haven, Connecticut|East Haven]] +** ''Hamden Chronicle'' of [[Hamden, Connecticut|Hamden]] +** ''Milford Weekly'' of [[Milford, Connecticut|Milford]] +** ''The Orange Bulletin'' of [[Orange, Connecticut|Orange]] +** ''The Post'' of [[North Haven, Connecticut|North Haven]] +** ''Shelton Weekly'' of [[Shelton, Connecticut|Shelton]] +** ''The Stratford Bard'' of [[Stratford, Connecticut|Stratford]] +** ''Wallingford Voice'' of [[Wallingford, Connecticut|Wallingford]] +** ''West Haven News'' of [[West Haven, Connecticut|West Haven]] +* Housatonic Publications +** ''The New Milford Times'' {{WS|newmilfordtimes.com}} of [[New Milford, Connecticut|New Milford]] +** ''The Brookfield Journal'' of [[Brookfield, Connecticut|Brookfield]] +** ''The Kent Good Times Dispatch'' of [[Kent, Connecticut|Kent]] +** ''The Bethel Beacon'' of [[Bethel, Connecticut|Bethel]] +** ''The Litchfield Enquirer'' of [[Litchfield, Connecticut|Litchfield]] +** ''Litchfield County Times'' of [[Litchfield, Connecticut|Litchfield]] +* Imprint Newspapers {{WS|imprintnewspapers.com}} +** ''West Hartford News'' of [[West Hartford, Connecticut|West Hartford]] +** ''Windsor Journal'' of [[Windsor, Connecticut|Windsor]] +** ''Windsor Locks Journal'' of [[Windsor Locks, Connecticut|Windsor Locks]] +** ''Avon Post'' of [[Avon, Connecticut|Avon]] +** ''Farmington Post'' of [[Farmington, Connecticut|Farmington]] +** ''Simsbury Post'' of [[Simsbury, Connecticut|Simsbury]] +** ''Tri-Town Post'' of [[Burlington, Connecticut|Burlington]], [[Canton, Connecticut|Canton]] and [[Harwinton, Connecticut|Harwinton]] +* Minuteman Publications +** ''[[Fairfield Minuteman]]'' of [[Fairfield, Connecticut|Fairfield]] +** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]] +* Shoreline Newspapers weeklies: +** ''Branford Review'' of [[Branford, Connecticut|Branford]] +** ''Clinton Recorder'' of [[Clinton, Connecticut|Clinton]] +** ''The Dolphin'' of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]] +** ''Main Street News'' {{WS|ctmainstreetnews.com}} of [[Essex, Connecticut|Essex]] +** ''Pictorial Gazette'' of [[Old Saybrook, Connecticut|Old Saybrook]] +** ''Regional Express'' of [[Colchester, Connecticut|Colchester]] +** ''Regional Standard'' of [[Colchester, Connecticut|Colchester]] +** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]] +** ''Shore View East'' of [[Madison, Connecticut|Madison]] +** ''Shore View West'' of [[Guilford, Connecticut|Guilford]] +* Other weeklies: +** ''Registro'' {{WS|registroct.com}} of [[New Haven, Connecticut|New Haven]] +** ''Thomaston Express'' {{WS|thomastownexpress.com}} of [[Thomaston, Connecticut|Thomaston]] +** ''Foothills Traders'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton + +== Michigan == +Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com] +* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]] +* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]] +* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]] +* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]] +* Heritage Newspapers {{WS|heritage.com}} +** ''Belleville View'' +** ''Ile Camera'' +** ''Monroe Guardian'' +** ''Ypsilanti Courier'' +** ''News-Herald'' +** ''Press & Guide'' +** ''Chelsea Standard & Dexter Leader'' +** ''Manchester Enterprise'' +** ''Milan News-Leader'' +** ''Saline Reporter'' +* Independent Newspapers {{WS|sourcenewspapers.com}} +** ''Advisor'' +** ''Source'' +* Morning Star {{WS|morningstarpublishing.com}} +** ''Alma Reminder'' +** ''Alpena Star'' +** ''Antrim County News'' +** ''Carson City Reminder'' +** ''The Leader & Kalkaskian'' +** ''Ogemaw/Oscoda County Star'' +** ''Petoskey/Charlevoix Star'' +** ''Presque Isle Star'' +** ''Preview Community Weekly'' +** ''Roscommon County Star'' +** ''St. Johns Reminder'' +** ''Straits Area Star'' +** ''The (Edmore) Advertiser'' +* Voice Newspapers {{WS|voicenews.com}} +** ''Armada Times'' +** ''Bay Voice'' +** ''Blue Water Voice'' +** ''Downriver Voice'' +** ''Macomb Township Voice'' +** ''North Macomb Voice'' +** ''Weekend Voice'' +** ''Suburban Lifestyles'' {{WS|suburbanlifestyles.com}} + +== Mid-Hudson == +One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]] + +== Ohio == +Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com]. + +* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]] +* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]] + +== Philadelphia area == +Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com]. + +* ''The Daily Local'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]] +* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos +* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]] +* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania|Phoenixville]] +* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]] +* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]] +* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]] + +* Weeklies +** ''El Latino Expreso'' of [[Trenton, New Jersey]] +** ''La Voz'' of [[Norristown, Pennsylvania]] +** ''The Village News'' of [[Downingtown, Pennsylvania]] +** ''The Times Record'' of [[Kennett Square, Pennsylvania]] +** ''The Tri-County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]] +** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}}of [[Havertown, Pennsylvania]] +** ''Main Line Times'' {{WS|mainlinetimes.com}}of [[Ardmore, Pennsylvania]] +** ''Penny Pincher'' of [[Pottstown, Pennsylvania]] +** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]] +* Chesapeake Publishing {{WS|pa8newsgroup.com}} +** ''Solanco Sun Ledger'' of [[Quarryville, Pennsylvania]] +** ''Columbia Ledger'' of [[Columbia, Pennsylvania]] +** ''Coatesville Ledger'' of [[Downingtown, Pennsylvania]] +** ''Parkesburg Post Ledger'' of [[Quarryville, Pennsylvania]] +** ''Downingtown Ledger'' of [[Downingtown, Pennsylvania]] +** ''The Kennett Paper'' of [[Kennett Square, Pennsylvania]] +** ''Avon Grove Sun'' of [[West Grove, Pennsylvania]] +** ''Oxford Tribune'' of [[Oxford, Pennsylvania]] +** ''Elizabethtown Chronicle'' of [[Elizabethtown, Pennsylvania]] +** ''Donegal Ledger'' of [[Donegal, Pennsylvania]] +** ''Chadds Ford Post'' of [[Chadds Ford, Pennsylvania]] +** ''The Central Record'' of [[Medford, New Jersey]] +** ''Maple Shade Progress'' of [[Maple Shade, New Jersey]] +* Intercounty Newspapers {{WS|buckslocalnews.com}} +** ''The Review'' of Roxborough, Pennsylvania +** ''The Recorder'' of [[Conshohocken, Pennsylvania]] +** ''The Leader'' of [[Mount Airy, Pennsylvania|Mount Airy]] and West Oak Lake, Pennsylvania +** ''The Pennington Post'' of [[Pennington, New Jersey]] +** ''The Bristol Pilot'' of [[Bristol, Pennsylvania]] +** ''Yardley News'' of [[Yardley, Pennsylvania]] +** ''New Hope Gazette'' of [[New Hope, Pennsylvania]] +** ''Doylestown Patriot'' of [[Doylestown, Pennsylvania]] +** ''Newtown Advance'' of [[Newtown, Pennsylvania]] +** ''The Plain Dealer'' of [[Williamstown, New Jersey]] +** ''News Report'' of [[Sewell, New Jersey]] +** ''Record Breeze'' of [[Berlin, New Jersey]] +** ''Newsweekly'' of [[Moorestown, New Jersey]] +** ''Haddon Herald'' of [[Haddonfield, New Jersey]] +** ''New Egypt Press'' of [[New Egypt, New Jersey]] +** ''Community News'' of [[Pemberton, New Jersey]] +** ''Plymouth Meeting Journal'' of [[Plymouth Meeting, Pennsylvania]] +** ''Lafayette Hill Journal'' of [[Lafayette Hill, Pennsylvania]] +* Montgomery Newspapers {{WS|montgomerynews.com}} +** ''Ambler Gazette'' of [[Ambler, Pennsylvania]] +** ''Central Bucks Life'' of [[Bucks County, Pennsylvania]] +** ''The Colonial'' of [[Plymouth Meeting, Pennsylvania]] +** ''Glenside News'' of [[Glenside, Pennsylvania]] +** ''The Globe'' of [[Lower Moreland Township, Pennsylvania]] +** ''Main Line Life'' of [[Ardmore, Pennsylvania]] +** ''Montgomery Life'' of [[Fort Washington, Pennsylvania]] +** ''North Penn Life'' of [[Lansdale, Pennsylvania]] +** ''Perkasie News Herald'' of [[Perkasie, Pennsylvania]] +** ''Public Spirit'' of [[Hatboro, Pennsylvania]] +** ''Souderton Independent'' of [[Souderton, Pennsylvania]] +** ''Springfield Sun'' of [[Springfield, Pennsylvania]] +** ''Spring-Ford Reporter'' of [[Royersford, Pennsylvania]] +** ''Times Chronicle'' of [[Jenkintown, Pennsylvania]] +** ''Valley Item'' of [[Perkiomenville, Pennsylvania]] +** ''Willow Grove Guide'' of [[Willow Grove, Pennsylvania]] +* News Gleaner Publications (closed December 2008) {{WS|newsgleaner.com}} +** ''Life Newspapers'' of [[Philadelphia, Pennsylvania]] +* Suburban Publications +** ''The Suburban & Wayne Times'' {{WS|waynesuburban.com}} of [[Wayne, Pennsylvania]] +** ''The Suburban Advertiser'' of [[Exton, Pennsylvania]] +** ''The King of Prussia Courier'' of [[King of Prussia, Pennsylvania]] +* Press Newspapers {{WS|countypressonline.com}} +** ''County Press'' of [[Newtown Square, Pennsylvania]] +** ''Garnet Valley Press'' of [[Glen Mills, Pennsylvania]] +** ''Haverford Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009) +** ''Hometown Press'' of [[Glen Mills, Pennsylvania]] (closed January 2009) +** ''Media Press'' of [[Newtown Square, Pennsylvania]] (closed January 2009) +** ''Springfield Press'' of [[Springfield, Pennsylvania]] +* Berks-Mont Newspapers {{WS|berksmontnews.com}} +** ''The Boyertown Area Times'' of [[Boyertown, Pennsylvania]] +** ''The Kutztown Area Patriot'' of [[Kutztown, Pennsylvania]] +** ''The Hamburg Area Item'' of [[Hamburg, Pennsylvania]] +** ''The Southern Berks News'' of [[Exeter Township, Berks County, Pennsylvania]] +** ''The Free Press'' of [[Quakertown, Pennsylvania]] +** ''The Saucon News'' of [[Quakertown, Pennsylvania]] +** ''Westside Weekly'' of [[Reading, Pennsylvania]] + +* Magazines +** ''Bucks Co. Town & Country Living'' +** ''Chester Co. Town & Country Living'' +** ''Montomgery Co. Town & Country Living'' +** ''Garden State Town & Country Living'' +** ''Montgomery Homes'' +** ''Philadelphia Golfer'' +** ''Parents Express'' +** ''Art Matters'' + +{{JRC}} + +==References== + + +[[Category:Journal Register publications|*]] diff --git a/v2/should/internal/go-diff/testdata/speedtest2.txt b/v2/should/internal/go-diff/testdata/speedtest2.txt new file mode 100644 index 0000000..8f25a80 --- /dev/null +++ b/v2/should/internal/go-diff/testdata/speedtest2.txt @@ -0,0 +1,188 @@ +This is a '''list of newspapers published by [[Journal Register Company]]'''. + +The company owns daily and weekly newspapers, other print media properties and newspaper-affiliated local Websites in the [[U.S.]] states of [[Connecticut]], [[Michigan]], [[New York]], [[Ohio]], [[Pennsylvania]] and [[New Jersey]], organized in six geographic "clusters":[http://www.journalregister.com/publications.html Journal Register Company: Our Publications], accessed April 21, 2010. + +== Capital-Saratoga == +Three dailies, associated weeklies and [[pennysaver]]s in greater [[Albany, New York]]; also [http://www.capitalcentral.com capitalcentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''The Oneida Daily Dispatch'' {{WS|oneidadispatch.com}} of [[Oneida, New York]] +* ''[[The Record (Troy)|The Record]]'' {{WS|troyrecord.com}} of [[Troy, New York]] +* ''[[The Saratogian]]'' {{WS|saratogian.com}} of [[Saratoga Springs, New York]] +* Weeklies: +** ''Community News'' {{WS|cnweekly.com}} weekly of [[Clifton Park, New York]] +** ''Rome Observer'' {{WS|romeobserver.com}} of [[Rome, New York]] +** ''WG Life '' {{WS|saratogian.com/wglife/}} of [[Wilton, New York]] +** ''Ballston Spa Life '' {{WS|saratogian.com/bspalife}} of [[Ballston Spa, New York]] +** ''Greenbush Life'' {{WS|troyrecord.com/greenbush}} of [[Troy, New York]] +** ''Latham Life'' {{WS|troyrecord.com/latham}} of [[Latham, New York]] +** ''River Life'' {{WS|troyrecord.com/river}} of [[Troy, New York]] + +== Connecticut == +Three dailies, associated weeklies and [[pennysaver]]s in the state of [[Connecticut]]; also [http://www.ctcentral.com CTcentral.com], [http://www.ctcarsandtrucks.com CTCarsAndTrucks.com] and [http://www.jobsinct.com JobsInCT.com]. + +* ''The Middletown Press'' {{WS|middletownpress.com}} of [[Middletown, Connecticut|Middletown]] +* ''[[New Haven Register]]'' {{WS|newhavenregister.com}} of [[New Haven, Connecticut|New Haven]] +* ''The Register Citizen'' {{WS|registercitizen.com}} of [[Torrington, Connecticut|Torrington]] + +* Housatonic Publications +** ''The Housatonic Times'' {{WS|housatonictimes.com}} of [[New Milford, Connecticut|New Milford]] +** ''Litchfield County Times'' {{WS|countytimes.com}} of [[Litchfield, Connecticut|Litchfield]] + +* Minuteman Publications +** ''[[Fairfield Minuteman]]'' {{WS|fairfieldminuteman.com}}of [[Fairfield, Connecticut|Fairfield]] +** ''The Westport Minuteman'' {{WS|westportminuteman.com}} of [[Westport, Connecticut|Westport]] + +* Shoreline Newspapers +** ''The Dolphin'' {{WS|dolphin-news.com}} of [[Naval Submarine Base New London]] in [[New London, Connecticut|New London]] +** ''Shoreline Times'' {{WS|shorelinetimes.com}} of [[Guilford, Connecticut|Guilford]] + +* Foothills Media Group {{WS|foothillsmediagroup.com}} +** ''Thomaston Express'' {{WS|thomastonexpress.com}} of [[Thomaston, Connecticut|Thomaston]] +** ''Good News About Torrington'' {{WS|goodnewsabouttorrington.com}} of [[Torrington, Connecticut|Torrington]] +** ''Granby News'' {{WS|foothillsmediagroup.com/granby}} of [[Granby, Connecticut|Granby]] +** ''Canton News'' {{WS|foothillsmediagroup.com/canton}} of [[Canton, Connecticut|Canton]] +** ''Avon News'' {{WS|foothillsmediagroup.com/avon}} of [[Avon, Connecticut|Avon]] +** ''Simsbury News'' {{WS|foothillsmediagroup.com/simsbury}} of [[Simsbury, Connecticut|Simsbury]] +** ''Litchfield News'' {{WS|foothillsmediagroup.com/litchfield}} of [[Litchfield, Connecticut|Litchfield]] +** ''Foothills Trader'' {{WS|foothillstrader.com}} of Torrington, Bristol, Canton + +* Other weeklies +** ''The Milford-Orange Bulletin'' {{WS|ctbulletin.com}} of [[Orange, Connecticut|Orange]] +** ''The Post-Chronicle'' {{WS|ctpostchronicle.com}} of [[North Haven, Connecticut|North Haven]] +** ''West Hartford News'' {{WS|westhartfordnews.com}} of [[West Hartford, Connecticut|West Hartford]] + +* Magazines +** ''The Connecticut Bride'' {{WS|connecticutmag.com}} +** ''Connecticut Magazine'' {{WS|theconnecticutbride.com}} +** ''Passport Magazine'' {{WS|passport-mag.com}} + +== Michigan == +Four dailies, associated weeklies and [[pennysaver]]s in the state of [[Michigan]]; also [http://www.micentralhomes.com MIcentralhomes.com] and [http://www.micentralautos.com MIcentralautos.com] +* ''[[Oakland Press]]'' {{WS|theoaklandpress.com}} of [[Oakland, Michigan|Oakland]] +* ''Daily Tribune'' {{WS|dailytribune.com}} of [[Royal Oak, Michigan|Royal Oak]] +* ''Macomb Daily'' {{WS|macombdaily.com}} of [[Mt. Clemens, Michigan|Mt. Clemens]] +* ''[[Morning Sun]]'' {{WS|themorningsun.com}} of [[Mount Pleasant, Michigan|Mount Pleasant]] + +* Heritage Newspapers {{WS|heritage.com}} +** ''Belleville View'' {{WS|bellevilleview.com}} +** ''Ile Camera'' {{WS|thenewsherald.com/ile_camera}} +** ''Monroe Guardian'' {{WS|monreguardian.com}} +** ''Ypsilanti Courier'' {{WS|ypsilanticourier.com}} +** ''News-Herald'' {{WS|thenewsherald.com}} +** ''Press & Guide'' {{WS|pressandguide.com}} +** ''Chelsea Standard & Dexter Leader'' {{WS|chelseastandard.com}} +** ''Manchester Enterprise'' {{WS|manchesterguardian.com}} +** ''Milan News-Leader'' {{WS|milannews.com}} +** ''Saline Reporter'' {{WS|salinereporter.com}} +* Independent Newspapers +** ''Advisor'' {{WS|sourcenewspapers.com}} +** ''Source'' {{WS|sourcenewspapers.com}} +* Morning Star {{WS|morningstarpublishing.com}} +** ''The Leader & Kalkaskian'' {{WS|leaderandkalkaskian.com}} +** ''Grand Traverse Insider'' {{WS|grandtraverseinsider.com}} +** ''Alma Reminder'' +** ''Alpena Star'' +** ''Ogemaw/Oscoda County Star'' +** ''Presque Isle Star'' +** ''St. Johns Reminder'' + +* Voice Newspapers {{WS|voicenews.com}} +** ''Armada Times'' +** ''Bay Voice'' +** ''Blue Water Voice'' +** ''Downriver Voice'' +** ''Macomb Township Voice'' +** ''North Macomb Voice'' +** ''Weekend Voice'' + +== Mid-Hudson == +One daily, associated magazines in the [[Hudson River Valley]] of [[New York]]; also [http://www.midhudsoncentral.com MidHudsonCentral.com] and [http://www.jobsinnewyork.com JobsInNewYork.com]. + +* ''[[Daily Freeman]]'' {{WS|dailyfreeman.com}} of [[Kingston, New York]] +* ''Las Noticias'' {{WS|lasnoticiasny.com}} of [[Kingston, New York]] + +== Ohio == +Two dailies, associated magazines and three shared Websites, all in the state of [[Ohio]]: [http://www.allaroundcleveland.com AllAroundCleveland.com], [http://www.allaroundclevelandcars.com AllAroundClevelandCars.com] and [http://www.allaroundclevelandjobs.com AllAroundClevelandJobs.com]. + +* ''[[The News-Herald (Ohio)|The News-Herald]]'' {{WS|news-herald.com}} of [[Willoughby, Ohio|Willoughby]] +* ''[[The Morning Journal]]'' {{WS|morningjournal.com}} of [[Lorain, Ohio|Lorain]] +* ''El Latino Expreso'' {{WS|lorainlatino.com}} of [[Lorain, Ohio|Lorain]] + +== Philadelphia area == +Seven dailies and associated weeklies and magazines in [[Pennsylvania]] and [[New Jersey]], and associated Websites: [http://www.allaroundphilly.com AllAroundPhilly.com], [http://www.jobsinnj.com JobsInNJ.com], [http://www.jobsinpa.com JobsInPA.com], and [http://www.phillycarsearch.com PhillyCarSearch.com]. + +* ''[[The Daily Local News]]'' {{WS|dailylocal.com}} of [[West Chester, Pennsylvania|West Chester]] +* ''[[Delaware County Daily and Sunday Times]] {{WS|delcotimes.com}} of Primos [[Upper Darby Township, Pennsylvania]] +* ''[[The Mercury (Pennsylvania)|The Mercury]]'' {{WS|pottstownmercury.com}} of [[Pottstown, Pennsylvania|Pottstown]] +* ''[[The Reporter (Lansdale)|The Reporter]]'' {{WS|thereporteronline.com}} of [[Lansdale, Pennsylvania|Lansdale]] +* ''The Times Herald'' {{WS|timesherald.com}} of [[Norristown, Pennsylvania|Norristown]] +* ''[[The Trentonian]]'' {{WS|trentonian.com}} of [[Trenton, New Jersey]] + +* Weeklies +* ''The Phoenix'' {{WS|phoenixvillenews.com}} of [[Phoenixville, Pennsylvania]] +** ''El Latino Expreso'' {{WS|njexpreso.com}} of [[Trenton, New Jersey]] +** ''La Voz'' {{WS|lavozpa.com}} of [[Norristown, Pennsylvania]] +** ''The Tri County Record'' {{WS|tricountyrecord.com}} of [[Morgantown, Pennsylvania]] +** ''Penny Pincher'' {{WS|pennypincherpa.com}}of [[Pottstown, Pennsylvania]] + +* Chesapeake Publishing {{WS|southernchestercountyweeklies.com}} +** ''The Kennett Paper'' {{WS|kennettpaper.com}} of [[Kennett Square, Pennsylvania]] +** ''Avon Grove Sun'' {{WS|avongrovesun.com}} of [[West Grove, Pennsylvania]] +** ''The Central Record'' {{WS|medfordcentralrecord.com}} of [[Medford, New Jersey]] +** ''Maple Shade Progress'' {{WS|mapleshadeprogress.com}} of [[Maple Shade, New Jersey]] + +* Intercounty Newspapers {{WS|buckslocalnews.com}} {{WS|southjerseylocalnews.com}} +** ''The Pennington Post'' {{WS|penningtonpost.com}} of [[Pennington, New Jersey]] +** ''The Bristol Pilot'' {{WS|bristolpilot.com}} of [[Bristol, Pennsylvania]] +** ''Yardley News'' {{WS|yardleynews.com}} of [[Yardley, Pennsylvania]] +** ''Advance of Bucks County'' {{WS|advanceofbucks.com}} of [[Newtown, Pennsylvania]] +** ''Record Breeze'' {{WS|recordbreeze.com}} of [[Berlin, New Jersey]] +** ''Community News'' {{WS|sjcommunitynews.com}} of [[Pemberton, New Jersey]] + +* Montgomery Newspapers {{WS|montgomerynews.com}} +** ''Ambler Gazette'' {{WS|amblergazette.com}} of [[Ambler, Pennsylvania]] +** ''The Colonial'' {{WS|colonialnews.com}} of [[Plymouth Meeting, Pennsylvania]] +** ''Glenside News'' {{WS|glensidenews.com}} of [[Glenside, Pennsylvania]] +** ''The Globe'' {{WS|globenewspaper.com}} of [[Lower Moreland Township, Pennsylvania]] +** ''Montgomery Life'' {{WS|montgomerylife.com}} of [[Fort Washington, Pennsylvania]] +** ''North Penn Life'' {{WS|northpennlife.com}} of [[Lansdale, Pennsylvania]] +** ''Perkasie News Herald'' {{WS|perkasienewsherald.com}} of [[Perkasie, Pennsylvania]] +** ''Public Spirit'' {{WS|thepublicspirit.com}} of [[Hatboro, Pennsylvania]] +** ''Souderton Independent'' {{WS|soudertonindependent.com}} of [[Souderton, Pennsylvania]] +** ''Springfield Sun'' {{WS|springfieldsun.com}} of [[Springfield, Pennsylvania]] +** ''Spring-Ford Reporter'' {{WS|springfordreporter.com}} of [[Royersford, Pennsylvania]] +** ''Times Chronicle'' {{WS|thetimeschronicle.com}} of [[Jenkintown, Pennsylvania]] +** ''Valley Item'' {{WS|valleyitem.com}} of [[Perkiomenville, Pennsylvania]] +** ''Willow Grove Guide'' {{WS|willowgroveguide.com}} of [[Willow Grove, Pennsylvania]] +** ''The Review'' {{WS|roxreview.com}} of [[Roxborough, Philadelphia, Pennsylvania]] + +* Main Line Media News {{WS|mainlinemedianews.com}} +** ''Main Line Times'' {{WS|mainlinetimes.com}} of [[Ardmore, Pennsylvania]] +** ''Main Line Life'' {{WS|mainlinelife.com}} of [[Ardmore, Pennsylvania]] +** ''The King of Prussia Courier'' {{WS|kingofprussiacourier.com}} of [[King of Prussia, Pennsylvania]] + +* Delaware County News Network {{WS|delconewsnetwork.com}} +** ''News of Delaware County'' {{WS|newsofdelawarecounty.com}} of [[Havertown, Pennsylvania]] +** ''County Press'' {{WS|countypressonline.com}} of [[Newtown Square, Pennsylvania]] +** ''Garnet Valley Press'' {{WS|countypressonline.com}} of [[Glen Mills, Pennsylvania]] +** ''Springfield Press'' {{WS|countypressonline.com}} of [[Springfield, Pennsylvania]] +** ''Town Talk'' {{WS|towntalknews.com}} of [[Ridley, Pennsylvania]] + +* Berks-Mont Newspapers {{WS|berksmontnews.com}} +** ''The Boyertown Area Times'' {{WS|berksmontnews.com/boyertown_area_times}} of [[Boyertown, Pennsylvania]] +** ''The Kutztown Area Patriot'' {{WS|berksmontnews.com/kutztown_area_patriot}} of [[Kutztown, Pennsylvania]] +** ''The Hamburg Area Item'' {{WS|berksmontnews.com/hamburg_area_item}} of [[Hamburg, Pennsylvania]] +** ''The Southern Berks News'' {{WS|berksmontnews.com/southern_berks_news}} of [[Exeter Township, Berks County, Pennsylvania]] +** ''Community Connection'' {{WS|berksmontnews.com/community_connection}} of [[Boyertown, Pennsylvania]] + +* Magazines +** ''Bucks Co. Town & Country Living'' {{WS|buckscountymagazine.com}} +** ''Parents Express'' {{WS|parents-express.com}} +** ''Real Men, Rednecks'' {{WS|realmenredneck.com}} + +{{JRC}} + +==References== + + +[[Category:Journal Register publications|*]] diff --git a/v2/should/internal/go-render/.travis.yml b/v2/should/internal/go-render/.travis.yml new file mode 100644 index 0000000..5a19a5f --- /dev/null +++ b/v2/should/internal/go-render/.travis.yml @@ -0,0 +1,21 @@ +# Copyright (c) 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# {sudo: required, dist: trusty} is the magic incantation to pick the trusty +# beta environment, which is the only environment we can get that has >4GB +# memory. Currently the `go test -race` tests that we run will peak at just +# over 4GB, which results in everything getting OOM-killed. +sudo: required +dist: trusty + +language: go + +go: +- 1.4.2 + +before_install: + - go get github.com/maruel/pre-commit-go/cmd/pcg + +script: + - pcg diff --git a/v2/should/internal/go-render/LICENSE b/v2/should/internal/go-render/LICENSE new file mode 100644 index 0000000..6280ff0 --- /dev/null +++ b/v2/should/internal/go-render/LICENSE @@ -0,0 +1,27 @@ +// Copyright (c) 2015 The Chromium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/v2/should/internal/go-render/PRESUBMIT.py b/v2/should/internal/go-render/PRESUBMIT.py new file mode 100644 index 0000000..d05f0cd --- /dev/null +++ b/v2/should/internal/go-render/PRESUBMIT.py @@ -0,0 +1,109 @@ +# Copyright 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Top-level presubmit script. + +See https://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for +details on the presubmit API built into depot_tools. +""" + +import os +import sys + + +def PreCommitGo(input_api, output_api, pcg_mode): + """Run go-specific checks via pre-commit-go (pcg) if it's in PATH.""" + if input_api.is_committing: + error_type = output_api.PresubmitError + else: + error_type = output_api.PresubmitPromptWarning + + exe = 'pcg.exe' if sys.platform == 'win32' else 'pcg' + pcg = None + for p in os.environ['PATH'].split(os.pathsep): + pcg = os.path.join(p, exe) + if os.access(pcg, os.X_OK): + break + else: + return [ + error_type( + 'pre-commit-go executable (pcg) could not be found in PATH. All Go ' + 'checks are skipped. See https://github.com/maruel/pre-commit-go.') + ] + + cmd = [pcg, 'run', '-m', ','.join(pcg_mode)] + if input_api.verbose: + cmd.append('-v') + # pcg can figure out what files to check on its own based on upstream ref, + # but on PRESUBMIT try builder upsteram isn't set, and it's just 1 commit. + if os.getenv('PRESUBMIT_BUILDER', ''): + cmd.extend(['-r', 'HEAD~1']) + return input_api.RunTests([ + input_api.Command( + name='pre-commit-go: %s' % ', '.join(pcg_mode), + cmd=cmd, + kwargs={}, + message=error_type), + ]) + + +def header(input_api): + """Returns the expected license header regexp for this project.""" + current_year = int(input_api.time.strftime('%Y')) + allowed_years = (str(s) for s in reversed(xrange(2011, current_year + 1))) + years_re = '(' + '|'.join(allowed_years) + ')' + license_header = ( + r'.*? Copyright %(year)s The Chromium Authors\. ' + r'All rights reserved\.\n' + r'.*? Use of this source code is governed by a BSD-style license ' + r'that can be\n' + r'.*? found in the LICENSE file\.(?: \*/)?\n' + ) % { + 'year': years_re, + } + return license_header + + +def source_file_filter(input_api): + """Returns filter that selects source code files only.""" + bl = list(input_api.DEFAULT_BLACK_LIST) + [ + r'.+\.pb\.go$', + r'.+_string\.go$', + ] + wl = list(input_api.DEFAULT_WHITE_LIST) + [ + r'.+\.go$', + ] + return lambda x: input_api.FilterSourceFile(x, white_list=wl, black_list=bl) + + +def CommonChecks(input_api, output_api): + results = [] + results.extend( + input_api.canned_checks.CheckChangeHasNoStrayWhitespace( + input_api, output_api, + source_file_filter=source_file_filter(input_api))) + results.extend( + input_api.canned_checks.CheckLicense( + input_api, output_api, header(input_api), + source_file_filter=source_file_filter(input_api))) + return results + + +def CheckChangeOnUpload(input_api, output_api): + results = CommonChecks(input_api, output_api) + results.extend(PreCommitGo(input_api, output_api, ['lint', 'pre-commit'])) + return results + + +def CheckChangeOnCommit(input_api, output_api): + results = CommonChecks(input_api, output_api) + results.extend(input_api.canned_checks.CheckChangeHasDescription( + input_api, output_api)) + results.extend(input_api.canned_checks.CheckDoNotSubmitInDescription( + input_api, output_api)) + results.extend(input_api.canned_checks.CheckDoNotSubmitInFiles( + input_api, output_api)) + results.extend(PreCommitGo( + input_api, output_api, ['continuous-integration'])) + return results diff --git a/v2/should/internal/go-render/README.md b/v2/should/internal/go-render/README.md new file mode 100644 index 0000000..bdf17d7 --- /dev/null +++ b/v2/should/internal/go-render/README.md @@ -0,0 +1,78 @@ +go-render: A verbose recursive Go type-to-string conversion library. +==================================================================== + +[![GoDoc](https://godoc.org/github.com/luci/go-render?status.svg)](https://godoc.org/github.com/luci/go-render) +[![Build Status](https://travis-ci.org/luci/go-render.svg)](https://travis-ci.org/luci/go-render) + +This is not an official Google product. + +## Overview + +The *render* package implements a more verbose form of the standard Go string +formatter, `fmt.Sprintf("%#v", value)`, adding: + - Pointer recursion. Normally, Go stops at the first pointer and prints its + address. The *render* package will recurse and continue to render pointer + values. + - Recursion loop detection. Recursion is nice, but if a recursion path detects + a loop, *render* will note this and move on. + - Custom type name rendering. + - Deterministic key sorting for `string`- and `int`-keyed maps. + - Testing! + +Call `render.Render` and pass it an `any`. + +For example: + +```Go +type customType int +type testStruct struct { + S string + V *map[string]int + I any +} + +a := testStruct{ + S: "hello", + V: &map[string]int{"foo": 0, "bar": 1}, + I: customType(42), +} + +fmt.Println("Render test:") +fmt.Printf("fmt.Printf: %#v\n", a))) +fmt.Printf("render.Render: %s\n", Render(a)) +``` + +Yields: +``` +fmt.Printf: render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42} +render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)} +``` + +This is not intended to be a high-performance library, but it's not terrible +either. + +Contributing +------------ + + * Sign the [Google CLA](https://cla.developers.google.com/clas). + * Make sure your `user.email` and `user.name` are configured in `git config`. + * Install the [pcg](https://github.com/maruel/pre-commit-go) git hook: + `go get -u github.com/maruel/pre-commit-go/cmd/... && pcg` + +Run the following to setup the code review tool and create your first review: + + git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git $HOME/src/depot_tools + export PATH="$PATH:$HOME/src/depot_tools" + cd $GOROOT/github.com/luci/go-render + git checkout -b work origin/master + + # hack hack + + git commit -a -m "This is awesome\nR=joe@example.com" + # This will ask for your Google Account credentials. + git cl upload -s + # Wait for LGTM over email. + # Check the commit queue box in codereview website. + # Wait for the change to be tested and landed automatically. + +Use `git cl help` and `git cl help ` for more details. diff --git a/v2/should/internal/go-render/WATCHLISTS b/v2/should/internal/go-render/WATCHLISTS new file mode 100644 index 0000000..e417208 --- /dev/null +++ b/v2/should/internal/go-render/WATCHLISTS @@ -0,0 +1,26 @@ +# Copyright 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# Watchlist Rules +# Refer: http://dev.chromium.org/developers/contributing-code/watchlists + +{ + + 'WATCHLIST_DEFINITIONS': { + 'all': { + 'filepath': '.+', + }, + }, + + 'WATCHLISTS': { + 'all': [ + # Add yourself here to get explicitly spammed. + 'maruel@chromium.org', + 'tandrii+luci-go@chromium.org', + 'todd@cloudera.com', + 'andrew.wang@cloudera.com', + ], + }, + +} diff --git a/v2/should/internal/go-render/pre-commit-go.yml b/v2/should/internal/go-render/pre-commit-go.yml new file mode 100644 index 0000000..074ee1f --- /dev/null +++ b/v2/should/internal/go-render/pre-commit-go.yml @@ -0,0 +1,78 @@ +# https://github.com/maruel/pre-commit-go configuration file to run checks +# automatically on commit, on push and on continuous integration service after +# a push or on merge of a pull request. +# +# See https://godoc.org/github.com/maruel/pre-commit-go/checks for more +# information. + +min_version: 0.4.7 +modes: + continuous-integration: + checks: + build: + - build_all: false + extra_args: [] + coverage: + - use_global_inference: false + use_coveralls: true + global: + min_coverage: 50 + max_coverage: 100 + per_dir_default: + min_coverage: 1 + max_coverage: 100 + per_dir: {} + gofmt: + - {} + goimports: + - {} + test: + - extra_args: + - -v + - -race + max_duration: 600 + lint: + checks: + golint: + - blacklist: [] + govet: + - blacklist: + - ' composite literal uses unkeyed fields' + max_duration: 15 + pre-commit: + checks: + build: + - build_all: false + extra_args: [] + gofmt: + - {} + test: + - extra_args: + - -short + max_duration: 35 + pre-push: + checks: + coverage: + - use_global_inference: false + use_coveralls: false + global: + min_coverage: 50 + max_coverage: 100 + per_dir_default: + min_coverage: 1 + max_coverage: 100 + per_dir: {} + goimports: + - {} + test: + - extra_args: + - -v + - -race + max_duration: 35 + +ignore_patterns: +- .* +- _* +- '*.pb.go' +- '*_string.go' +- '*-gen.go' diff --git a/v2/should/internal/go-render/render/render.go b/v2/should/internal/go-render/render/render.go new file mode 100644 index 0000000..357b744 --- /dev/null +++ b/v2/should/internal/go-render/render/render.go @@ -0,0 +1,481 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package render + +import ( + "bytes" + "fmt" + "reflect" + "sort" + "strconv" +) + +var builtinTypeMap = map[reflect.Kind]string{ + reflect.Bool: "bool", + reflect.Complex128: "complex128", + reflect.Complex64: "complex64", + reflect.Float32: "float32", + reflect.Float64: "float64", + reflect.Int16: "int16", + reflect.Int32: "int32", + reflect.Int64: "int64", + reflect.Int8: "int8", + reflect.Int: "int", + reflect.String: "string", + reflect.Uint16: "uint16", + reflect.Uint32: "uint32", + reflect.Uint64: "uint64", + reflect.Uint8: "uint8", + reflect.Uint: "uint", + reflect.Uintptr: "uintptr", +} + +var builtinTypeSet = map[string]struct{}{} + +func init() { + for _, v := range builtinTypeMap { + builtinTypeSet[v] = struct{}{} + } +} + +var typeOfString = reflect.TypeOf("") +var typeOfInt = reflect.TypeOf(int(1)) +var typeOfUint = reflect.TypeOf(uint(1)) +var typeOfFloat = reflect.TypeOf(10.1) + +// Render converts a structure to a string representation. Unline the "%#v" +// format string, this resolves pointer types' contents in structs, maps, and +// slices/arrays and prints their field values. +func Render(v any) string { + buf := bytes.Buffer{} + s := (*traverseState)(nil) + s.render(&buf, 0, reflect.ValueOf(v), false) + return buf.String() +} + +// renderPointer is called to render a pointer value. +// +// This is overridable so that the test suite can have deterministic pointer +// values in its expectations. +var renderPointer = func(buf *bytes.Buffer, p uintptr) { + fmt.Fprintf(buf, "0x%016x", p) +} + +// traverseState is used to note and avoid recursion as struct members are being +// traversed. +// +// traverseState is allowed to be nil. Specifically, the root state is nil. +type traverseState struct { + parent *traverseState + ptr uintptr +} + +func (s *traverseState) forkFor(ptr uintptr) *traverseState { + for cur := s; cur != nil; cur = cur.parent { + if ptr == cur.ptr { + return nil + } + } + + fs := &traverseState{ + parent: s, + ptr: ptr, + } + return fs +} + +func (s *traverseState) render(buf *bytes.Buffer, ptrs int, v reflect.Value, implicit bool) { + if v.Kind() == reflect.Invalid { + buf.WriteString("nil") + return + } + vt := v.Type() + + // If the type being rendered is a potentially recursive type (a type that + // can contain itself as a member), we need to avoid recursion. + // + // If we've already seen this type before, mark that this is the case and + // write a recursion placeholder instead of actually rendering it. + // + // If we haven't seen it before, fork our `seen` tracking so any higher-up + // renderers will also render it at least once, then mark that we've seen it + // to avoid recursing on lower layers. + pe := uintptr(0) + vk := vt.Kind() + switch vk { + case reflect.Ptr: + // Since structs and arrays aren't pointers, they can't directly be + // recursed, but they can contain pointers to themselves. Record their + // pointer to avoid this. + switch v.Elem().Kind() { + case reflect.Struct, reflect.Array: + pe = v.Pointer() + } + + case reflect.Slice, reflect.Map: + pe = v.Pointer() + } + if pe != 0 { + s = s.forkFor(pe) + if s == nil { + buf.WriteString("") + return + } + } + + isAnon := func(t reflect.Type) bool { + if t.Name() != "" { + if _, ok := builtinTypeSet[t.Name()]; !ok { + return false + } + } + return t.Kind() != reflect.Interface + } + + switch vk { + case reflect.Struct: + if !implicit { + writeType(buf, ptrs, vt) + } + buf.WriteRune('{') + if rendered, ok := renderTime(v); ok { + buf.WriteString(rendered) + } else { + structAnon := vt.Name() == "" + for i := 0; i < vt.NumField(); i++ { + if i > 0 { + buf.WriteString(", ") + } + anon := structAnon && isAnon(vt.Field(i).Type) + + if !anon { + buf.WriteString(vt.Field(i).Name) + buf.WriteRune(':') + } + + s.render(buf, 0, v.Field(i), anon) + } + } + buf.WriteRune('}') + + case reflect.Slice: + if v.IsNil() { + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteString("(nil)") + } else { + buf.WriteString("nil") + } + return + } + fallthrough + + case reflect.Array: + if !implicit { + writeType(buf, ptrs, vt) + } + anon := vt.Name() == "" && isAnon(vt.Elem()) + buf.WriteString("{") + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, v.Index(i), anon) + } + buf.WriteRune('}') + + case reflect.Map: + if !implicit { + writeType(buf, ptrs, vt) + } + if v.IsNil() { + buf.WriteString("(nil)") + } else { + buf.WriteString("{") + + mkeys := v.MapKeys() + tryAndSortMapKeys(vt, mkeys) + + kt := vt.Key() + keyAnon := typeOfString.ConvertibleTo(kt) || typeOfInt.ConvertibleTo(kt) || typeOfUint.ConvertibleTo(kt) || typeOfFloat.ConvertibleTo(kt) + valAnon := vt.Name() == "" && isAnon(vt.Elem()) + for i, mk := range mkeys { + if i > 0 { + buf.WriteString(", ") + } + + s.render(buf, 0, mk, keyAnon) + buf.WriteString(":") + s.render(buf, 0, v.MapIndex(mk), valAnon) + } + buf.WriteRune('}') + } + + case reflect.Ptr: + ptrs++ + fallthrough + case reflect.Interface: + if v.IsNil() { + writeType(buf, ptrs, v.Type()) + buf.WriteString("(nil)") + } else { + s.render(buf, ptrs, v.Elem(), false) + } + + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + writeType(buf, ptrs, vt) + buf.WriteRune('(') + renderPointer(buf, v.Pointer()) + buf.WriteRune(')') + + default: + tstr := vt.String() + implicit = implicit || (ptrs == 0 && builtinTypeMap[vk] == tstr) + if !implicit { + writeType(buf, ptrs, vt) + buf.WriteRune('(') + } + + switch vk { + case reflect.String: + fmt.Fprintf(buf, "%q", v.String()) + case reflect.Bool: + fmt.Fprintf(buf, "%v", v.Bool()) + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + fmt.Fprintf(buf, "%d", v.Int()) + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + fmt.Fprintf(buf, "%d", v.Uint()) + + case reflect.Float32, reflect.Float64: + fmt.Fprintf(buf, "%g", v.Float()) + + case reflect.Complex64, reflect.Complex128: + fmt.Fprintf(buf, "%g", v.Complex()) + } + + if !implicit { + buf.WriteRune(')') + } + } +} + +func writeType(buf *bytes.Buffer, ptrs int, t reflect.Type) { + parens := ptrs > 0 + switch t.Kind() { + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + parens = true + } + + if parens { + buf.WriteRune('(') + for i := 0; i < ptrs; i++ { + buf.WriteRune('*') + } + } + + switch t.Kind() { + case reflect.Ptr: + if ptrs == 0 { + // This pointer was referenced from within writeType (e.g., as part of + // rendering a list), and so hasn't had its pointer asterisk accounted + // for. + buf.WriteRune('*') + } + writeType(buf, 0, t.Elem()) + + case reflect.Interface: + if n := t.Name(); n != "" { + buf.WriteString(t.String()) + } else { + buf.WriteString("any") + } + + case reflect.Array: + buf.WriteRune('[') + buf.WriteString(strconv.FormatInt(int64(t.Len()), 10)) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + + case reflect.Slice: + if t == reflect.SliceOf(t.Elem()) { + buf.WriteString("[]") + writeType(buf, 0, t.Elem()) + } else { + // Custom slice type, use type name. + buf.WriteString(t.String()) + } + + case reflect.Map: + if t == reflect.MapOf(t.Key(), t.Elem()) { + buf.WriteString("map[") + writeType(buf, 0, t.Key()) + buf.WriteRune(']') + writeType(buf, 0, t.Elem()) + } else { + // Custom map type, use type name. + buf.WriteString(t.String()) + } + + default: + buf.WriteString(t.String()) + } + + if parens { + buf.WriteRune(')') + } +} + +type cmpFn func(a, b reflect.Value) int + +type sortableValueSlice struct { + cmp cmpFn + elements []reflect.Value +} + +func (s sortableValueSlice) Len() int { + return len(s.elements) +} + +func (s sortableValueSlice) Less(i, j int) bool { + return s.cmp(s.elements[i], s.elements[j]) < 0 +} + +func (s sortableValueSlice) Swap(i, j int) { + s.elements[i], s.elements[j] = s.elements[j], s.elements[i] +} + +// cmpForType returns a cmpFn which sorts the data for some type t in the same +// order that a go-native map key is compared for equality. +func cmpForType(t reflect.Type) cmpFn { + switch t.Kind() { + case reflect.String: + return func(av, bv reflect.Value) int { + a, b := av.String(), bv.String() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Bool: + return func(av, bv reflect.Value) int { + a, b := av.Bool(), bv.Bool() + if !a && b { + return -1 + } else if a && !b { + return 1 + } + return 0 + } + + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return func(av, bv reflect.Value) int { + a, b := av.Int(), bv.Int() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, + reflect.Uint64, reflect.Uintptr, reflect.UnsafePointer: + return func(av, bv reflect.Value) int { + a, b := av.Uint(), bv.Uint() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Float32, reflect.Float64: + return func(av, bv reflect.Value) int { + a, b := av.Float(), bv.Float() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Interface: + return func(av, bv reflect.Value) int { + a, b := av.InterfaceData(), bv.InterfaceData() + if a[0] < b[0] { + return -1 + } else if a[0] > b[0] { + return 1 + } + if a[1] < b[1] { + return -1 + } else if a[1] > b[1] { + return 1 + } + return 0 + } + + case reflect.Complex64, reflect.Complex128: + return func(av, bv reflect.Value) int { + a, b := av.Complex(), bv.Complex() + if real(a) < real(b) { + return -1 + } else if real(a) > real(b) { + return 1 + } + if imag(a) < imag(b) { + return -1 + } else if imag(a) > imag(b) { + return 1 + } + return 0 + } + + case reflect.Ptr, reflect.Chan: + return func(av, bv reflect.Value) int { + a, b := av.Pointer(), bv.Pointer() + if a < b { + return -1 + } else if a > b { + return 1 + } + return 0 + } + + case reflect.Struct: + cmpLst := make([]cmpFn, t.NumField()) + for i := range cmpLst { + cmpLst[i] = cmpForType(t.Field(i).Type) + } + return func(a, b reflect.Value) int { + for i, cmp := range cmpLst { + if rslt := cmp(a.Field(i), b.Field(i)); rslt != 0 { + return rslt + } + } + return 0 + } + } + + return nil +} + +func tryAndSortMapKeys(mt reflect.Type, k []reflect.Value) { + if cmp := cmpForType(mt.Key()); cmp != nil { + sort.Sort(sortableValueSlice{cmp, k}) + } +} diff --git a/v2/should/internal/go-render/render/render_test.go b/v2/should/internal/go-render/render/render_test.go new file mode 100644 index 0000000..5cb7c94 --- /dev/null +++ b/v2/should/internal/go-render/render/render_test.go @@ -0,0 +1,281 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package render + +import ( + "bytes" + "fmt" + "reflect" + "regexp" + "runtime" + "testing" + "time" +) + +func init() { + // For testing purposes, pointers will render as "PTR" so that they are + // deterministic. + renderPointer = func(buf *bytes.Buffer, p uintptr) { + buf.WriteString("PTR") + } +} + +func assertRendersLike(t *testing.T, name string, v any, exp string) { + act := Render(v) + if act != exp { + _, _, line, _ := runtime.Caller(1) + t.Errorf("On line #%d, [%s] did not match expectations:\nExpected: %s\nActual : %s\n", line, name, exp, act) + } +} + +func TestRenderList(t *testing.T) { + t.Parallel() + + // Note that we make some of the fields exportable. This is to avoid a fun case + // where the first reflect.Value has a read-only bit set, but follow-on values + // do not, so recursion tests are off by one. + type testStruct struct { + Name string + I any + + m string + } + + type myStringSlice []string + type myStringMap map[string]string + type myIntType int + type myStringType string + type myTypeWithTime struct{ Public, private time.Time } + + var date = time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC) + populatedTimes := myTypeWithTime{date, date} + zeroTimes := myTypeWithTime{} + + s0 := "string0" + s0P := &s0 + mit := myIntType(42) + stringer := fmt.Stringer(nil) + + for i, tc := range []struct { + a any + s string + }{ + {nil, `nil`}, + {make(chan int), `(chan int)(PTR)`}, + {&stringer, `(*fmt.Stringer)(nil)`}, + {123, `123`}, + {"hello", `"hello"`}, + {(*testStruct)(nil), `(*render.testStruct)(nil)`}, + {(**testStruct)(nil), `(**render.testStruct)(nil)`}, + {[]***testStruct(nil), `[]***render.testStruct(nil)`}, + {testStruct{Name: "foo", I: &testStruct{Name: "baz"}}, + `render.testStruct{Name:"foo", I:(*render.testStruct){Name:"baz", I:any(nil), m:""}, m:""}`}, + {[]byte(nil), `[]uint8(nil)`}, + {[]byte{}, `[]uint8{}`}, + {map[string]string(nil), `map[string]string(nil)`}, + {[]*testStruct{ + {Name: "foo"}, + {Name: "bar"}, + }, `[]*render.testStruct{(*render.testStruct){Name:"foo", I:any(nil), m:""}, ` + + `(*render.testStruct){Name:"bar", I:any(nil), m:""}}`}, + {myStringSlice{"foo", "bar"}, `render.myStringSlice{"foo", "bar"}`}, + {myStringMap{"foo": "bar"}, `render.myStringMap{"foo":"bar"}`}, + {myIntType(12), `render.myIntType(12)`}, + {&mit, `(*render.myIntType)(42)`}, + {myStringType("foo"), `render.myStringType("foo")`}, + {zeroTimes, `render.myTypeWithTime{Public:time.Time{0}, private:time.Time{wall:0, ext:0, loc:(*time.Location)(nil)}}`}, + {populatedTimes, `render.myTypeWithTime{Public:time.Time{2000-01-01 00:00:00 +0000 UTC}, private:time.Time{wall:0, ext:63082281600, loc:(*time.Location)(nil)}}`}, + {struct { + a int + b string + }{123, "foo"}, `struct { a int; b string }{123, "foo"}`}, + {[]string{"foo", "foo", "bar", "baz", "qux", "qux"}, + `[]string{"foo", "foo", "bar", "baz", "qux", "qux"}`}, + {[...]int{1, 2, 3}, `[3]int{1, 2, 3}`}, + {map[string]bool{ + "foo": true, + "bar": false, + }, `map[string]bool{"bar":false, "foo":true}`}, + {map[int]string{1: "foo", 2: "bar"}, `map[int]string{1:"foo", 2:"bar"}`}, + {uint32(1337), `1337`}, + {3.14, `3.14`}, + {complex(3, 0.14), `(3+0.14i)`}, + {&s0, `(*string)("string0")`}, + {&s0P, `(**string)("string0")`}, + {[]any{nil, 1, 2, nil}, `[]any{any(nil), 1, 2, any(nil)}`}, + } { + assertRendersLike(t, fmt.Sprintf("Input #%d", i), tc.a, tc.s) + } +} + +func TestRenderRecursiveStruct(t *testing.T) { + type testStruct struct { + Name string + I any + } + + s := &testStruct{ + Name: "recursive", + } + s.I = s + + assertRendersLike(t, "Recursive struct", s, + `(*render.testStruct){Name:"recursive", I:}`) +} + +func TestRenderRecursiveArray(t *testing.T) { + a := [2]any{} + a[0] = &a + a[1] = &a + + assertRendersLike(t, "Recursive array", &a, + `(*[2]any){, }`) +} + +func TestRenderRecursiveMap(t *testing.T) { + m := map[string]any{} + foo := "foo" + m["foo"] = m + m["bar"] = [](*string){&foo, &foo} + v := []map[string]any{m, m} + + assertRendersLike(t, "Recursive map", v, + `[]map[string]any{{`+ + `"bar":[]*string{(*string)("foo"), (*string)("foo")}, `+ + `"foo":}, {`+ + `"bar":[]*string{(*string)("foo"), (*string)("foo")}, `+ + `"foo":}}`) +} + +func TestRenderImplicitType(t *testing.T) { + type namedStruct struct{ a, b int } + type namedInt int + + tcs := []struct { + in any + expect string + }{ + { + []struct{ a, b int }{{1, 2}}, + "[]struct { a int; b int }{{1, 2}}", + }, + { + map[string]struct{ a, b int }{"hi": {1, 2}}, + `map[string]struct { a int; b int }{"hi":{1, 2}}`, + }, + { + map[namedInt]struct{}{10: {}}, + `map[render.namedInt]struct {}{10:{}}`, + }, + { + struct{ a, b int }{1, 2}, + `struct { a int; b int }{1, 2}`, + }, + { + namedStruct{1, 2}, + "render.namedStruct{a:1, b:2}", + }, + } + + for _, tc := range tcs { + assertRendersLike(t, reflect.TypeOf(tc.in).String(), tc.in, tc.expect) + } +} + +func Example() { + type customType int + type testStruct struct { + S string + V *map[string]int + I any + } + + a := testStruct{ + S: "hello", + V: &map[string]int{"foo": 0, "bar": 1}, + I: customType(42), + } + + fmt.Println("Render test:") + fmt.Printf("fmt.Printf: %s\n", sanitizePointer(fmt.Sprintf("%#v", a))) + fmt.Printf("render.Render: %s\n", Render(a)) + // Output: Render test: + // fmt.Printf: render.testStruct{S:"hello", V:(*map[string]int)(0x600dd065), I:42} + // render.Render: render.testStruct{S:"hello", V:(*map[string]int){"bar":1, "foo":0}, I:render.customType(42)} +} + +var pointerRE = regexp.MustCompile(`\(0x[a-f0-9]+\)`) + +func sanitizePointer(s string) string { + return pointerRE.ReplaceAllString(s, "(0x600dd065)") +} + +type chanList []chan int + +func (c chanList) Len() int { return len(c) } +func (c chanList) Swap(i, j int) { c[i], c[j] = c[j], c[i] } +func (c chanList) Less(i, j int) bool { + return reflect.ValueOf(c[i]).Pointer() < reflect.ValueOf(c[j]).Pointer() +} + +func TestMapSortRendering(t *testing.T) { + type namedMapType map[int]struct{ a int } + type mapKey struct{ a, b int } + + chans := make(chanList, 5) + for i := range chans { + chans[i] = make(chan int) + } + + tcs := []struct { + in any + expect string + }{ + { + map[uint32]struct{}{1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}}, + "map[uint32]struct {}{1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}, 7:{}, 8:{}}", + }, + { + map[int8]struct{}{1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}}, + "map[int8]struct {}{1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}, 7:{}, 8:{}}", + }, + { + map[uintptr]struct{}{1: {}, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, 8: {}}, + "map[uintptr]struct {}{1:{}, 2:{}, 3:{}, 4:{}, 5:{}, 6:{}, 7:{}, 8:{}}", + }, + { + namedMapType{10: struct{ a int }{20}}, + "render.namedMapType{10:struct { a int }{20}}", + }, + { + map[mapKey]struct{}{mapKey{3, 1}: {}, mapKey{1, 3}: {}, mapKey{1, 2}: {}, mapKey{2, 1}: {}}, + "map[render.mapKey]struct {}{render.mapKey{a:1, b:2}:{}, render.mapKey{a:1, b:3}:{}, render.mapKey{a:2, b:1}:{}, render.mapKey{a:3, b:1}:{}}", + }, + { + map[float64]struct{}{10.5: {}, 10.15: {}, 1203: {}, 1: {}, 2: {}}, + "map[float64]struct {}{1:{}, 2:{}, 10.15:{}, 10.5:{}, 1203:{}}", + }, + { + map[bool]struct{}{true: {}, false: {}}, + "map[bool]struct {}{false:{}, true:{}}", + }, + { + map[any]struct{}{1: {}, 2: {}, 3: {}, "foo": {}}, + `map[any]struct {}{"foo":{}, 1:{}, 2:{}, 3:{}}`, + }, + { + map[complex64]struct{}{1 + 2i: {}, 2 + 1i: {}, 3 + 1i: {}, 1 + 3i: {}}, + "map[complex64]struct {}{(1+2i):{}, (1+3i):{}, (2+1i):{}, (3+1i):{}}", + }, + { + map[chan int]string{nil: "a", chans[0]: "b", chans[1]: "c", chans[2]: "d", chans[3]: "e", chans[4]: "f"}, + `map[(chan int)]string{(chan int)(PTR):"a", (chan int)(PTR):"b", (chan int)(PTR):"c", (chan int)(PTR):"d", (chan int)(PTR):"e", (chan int)(PTR):"f"}`, + }, + } + + for _, tc := range tcs { + assertRendersLike(t, reflect.TypeOf(tc.in).Name(), tc.in, tc.expect) + } +} diff --git a/v2/should/internal/go-render/render/render_time.go b/v2/should/internal/go-render/render/render_time.go new file mode 100644 index 0000000..990c75d --- /dev/null +++ b/v2/should/internal/go-render/render/render_time.go @@ -0,0 +1,26 @@ +package render + +import ( + "reflect" + "time" +) + +func renderTime(value reflect.Value) (string, bool) { + if instant, ok := convertTime(value); !ok { + return "", false + } else if instant.IsZero() { + return "0", true + } else { + return instant.String(), true + } +} + +func convertTime(value reflect.Value) (t time.Time, ok bool) { + if value.Type() == timeType { + defer func() { recover() }() + t, ok = value.Interface().(time.Time) + } + return +} + +var timeType = reflect.TypeOf(time.Time{}) diff --git a/v2/should/kinds.go b/v2/should/kinds.go new file mode 100644 index 0000000..dba0520 --- /dev/null +++ b/v2/should/kinds.go @@ -0,0 +1,107 @@ +package should + +import "reflect" + +var floatTypes = map[reflect.Kind]struct{}{ + reflect.Float32: {}, + reflect.Float64: {}, +} + +func isFloat(v any) bool { + _, found := floatTypes[reflect.TypeOf(v).Kind()] + return found +} + +func asFloat(a any) float64 { + v := reflect.ValueOf(a) + if isSignedInteger(a) { + return float64(v.Int()) + } + if isUnsignedInteger(a) { + return float64(v.Uint()) + } + return v.Float() +} + +var unsignedIntegerKinds = map[reflect.Kind]struct{}{ + reflect.Uint: {}, + reflect.Uint8: {}, + reflect.Uint16: {}, + reflect.Uint32: {}, + reflect.Uint64: {}, + reflect.Uintptr: {}, +} + +func isUnsignedInteger(v any) bool { + _, found := unsignedIntegerKinds[reflect.TypeOf(v).Kind()] + return found +} + +var signedIntegerKinds = map[reflect.Kind]struct{}{ + reflect.Int: {}, + reflect.Int8: {}, + reflect.Int16: {}, + reflect.Int32: {}, + reflect.Int64: {}, +} + +func isSignedInteger(v any) bool { + _, found := signedIntegerKinds[reflect.TypeOf(v).Kind()] + return found +} + +func isInteger(v any) bool { + return isSignedInteger(v) || isUnsignedInteger(v) +} + +var numericKinds = map[reflect.Kind]struct{}{ + reflect.Int: {}, + reflect.Int8: {}, + reflect.Int16: {}, + reflect.Int32: {}, + reflect.Int64: {}, + reflect.Uint: {}, + reflect.Uint8: {}, + reflect.Uint16: {}, + reflect.Uint32: {}, + reflect.Uint64: {}, + reflect.Float32: {}, + reflect.Float64: {}, +} + +func isNumeric(v any) bool { + of := reflect.TypeOf(v) + if of == nil { + return false + } + _, found := numericKinds[of.Kind()] + return found +} + +var kindsWithLength = []reflect.Kind{ + reflect.Map, + reflect.Chan, + reflect.Array, + reflect.Slice, + reflect.String, +} + +var containerKinds = []reflect.Kind{ + reflect.Map, + reflect.Array, + reflect.Slice, + reflect.String, +} + +var orderedContainerKinds = []reflect.Kind{ + reflect.Array, + reflect.Slice, + reflect.String, +} + +func kindSlice(kinds map[reflect.Kind]struct{}) (result []reflect.Kind) { + for kind := range kinds { + result = append(result, kind) + } + return result +} diff --git a/v2/should/not.go b/v2/should/not.go new file mode 100644 index 0000000..28e7276 --- /dev/null +++ b/v2/should/not.go @@ -0,0 +1,6 @@ +package should + +// NOT (a singleton) constrains all negated assertions to their own namespace. +var NOT negated + +type negated struct{} diff --git a/v2/should/panic.go b/v2/should/panic.go new file mode 100644 index 0000000..b658353 --- /dev/null +++ b/v2/should/panic.go @@ -0,0 +1,46 @@ +package should + +import "errors" + +// Panic invokes the func() provided as actual and recovers from any +// panic. It returns an error if actual() does not result in a panic. +func Panic(actual any, expected ...any) (err error) { + err = NOT.Panic(actual, expected...) + if errors.Is(err, ErrAssertionFailure) { + return nil + } + + if err != nil { + return err + } + + return failure("provided func did not panic as expected") +} + +// Panic (negated!) expects the func() provided as actual to run without panicking. +func (negated) Panic(actual any, expected ...any) (err error) { + err = validateExpected(0, expected) + if err != nil { + return err + } + + err = validateType(actual, func() {}) + if err != nil { + return err + } + + panicked := true + defer func() { + r := recover() + if panicked { + err = failure(""+ + "provided func should not have"+ + "panicked but it did with: %s", r, + ) + } + }() + + actual.(func())() + panicked = false + return nil +} diff --git a/v2/should/panic_test.go b/v2/should/panic_test.go new file mode 100644 index 0000000..a32eae6 --- /dev/null +++ b/v2/should/panic_test.go @@ -0,0 +1,28 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldPanic(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.Panic, "EXPECTED", "EXTRA") + assert.TypeMismatch("wrong type", should.Panic) + + assert.Fail(func() {}, should.Panic) + assert.Pass(func() { panic("yay") }, should.Panic) + assert.Pass(func() { panic(nil) }, should.Panic) // tricky! +} + +func TestShouldNotPanic(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.NOT.Panic, "EXPECTED", "EXTRA") + assert.TypeMismatch("wrong type", should.NOT.Panic) + + assert.Fail(func() { panic("boo") }, should.NOT.Panic) + assert.Pass(func() {}, should.NOT.Panic) +} diff --git a/v2/should/spec.go b/v2/should/spec.go new file mode 100644 index 0000000..10878b1 --- /dev/null +++ b/v2/should/spec.go @@ -0,0 +1,6 @@ +package should + +type specification interface { + assertable(a, b any) bool + passes(a, b any) bool +} diff --git a/v2/should/start_with.go b/v2/should/start_with.go new file mode 100644 index 0000000..eaf3ad0 --- /dev/null +++ b/v2/should/start_with.go @@ -0,0 +1,57 @@ +package should + +import ( + "reflect" + "strings" +) + +// StartWith verified that actual starts with expected[0]. +// The actual value may be an array, slice, or string. +func StartWith(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + err = validateKind(actual, orderedContainerKinds...) + if err != nil { + return err + } + + actualValue := reflect.ValueOf(actual) + EXPECTED := expected[0] + + switch reflect.TypeOf(actual).Kind() { + case reflect.Array, reflect.Slice: + if actualValue.Len() == 0 { + break + } + first := actualValue.Index(0).Interface() + if Equal(EXPECTED, first) == nil { + return nil + } + case reflect.String: + err = validateKind(EXPECTED, reflect.String, reflectRune) + if err != nil { + return err + } + + expectedRune, ok := EXPECTED.(rune) + if ok { + EXPECTED = string(expectedRune) + } + + full := actual.(string) + prefix := EXPECTED.(string) + if strings.HasPrefix(full, prefix) { + return nil + } + } + + return failure("\n"+ + " proposed prefix: %#v\n"+ + " not a prefix of: %#v", + EXPECTED, + actual, + ) +} diff --git a/v2/should/start_with_test.go b/v2/should/start_with_test.go new file mode 100644 index 0000000..8fc8dd8 --- /dev/null +++ b/v2/should/start_with_test.go @@ -0,0 +1,34 @@ +package should_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldStartWith(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.StartWith) + assert.ExpectedCountInvalid("actual", should.StartWith, "EXPECTED", "EXTRA") + + assert.KindMismatch("string", should.StartWith, false) + assert.KindMismatch(1, should.StartWith, "hi") + + // strings: + assert.Fail("", should.StartWith, "no") + assert.Pass("abc", should.StartWith, 'a') + assert.Pass("integrate", should.StartWith, "in") + + // slices: + assert.Fail([]byte{}, should.StartWith, 'b') + assert.Fail([]byte(nil), should.StartWith, 'b') + assert.Fail([]byte("abc"), should.StartWith, 'b') + assert.Pass([]byte("abc"), should.StartWith, 'a') + assert.Pass([]byte("abc"), should.StartWith, 97) + + // arrays: + assert.Fail([3]byte{'a', 'b', 'c'}, should.StartWith, 'b') + assert.Pass([3]byte{'a', 'b', 'c'}, should.StartWith, 'a') + assert.Pass([3]byte{'a', 'b', 'c'}, should.StartWith, 97) +} diff --git a/v2/should/wrap_error.go b/v2/should/wrap_error.go new file mode 100644 index 0000000..d9a077c --- /dev/null +++ b/v2/should/wrap_error.go @@ -0,0 +1,46 @@ +package should + +import ( + "errors" + "fmt" + "reflect" +) + +// WrapError uses errors.Is to verify that actual is an error value +// that wraps expected[0] (also an error value). +func WrapError(actual any, expected ...any) error { + err := validateExpected(1, expected) + if err != nil { + return err + } + + inner, ok := expected[0].(error) + if !ok { + return errTypeMismatch(expected[0]) + } + + outer, ok := actual.(error) + if !ok { + return errTypeMismatch(actual) + } + + if errors.Is(outer, inner) { + return nil + } + + return fmt.Errorf("%w:\n"+ + "\t outer err: (%s)\n"+ + "\tshould wrap inner err: (%s)", + ErrAssertionFailure, + outer, + inner, + ) +} + +func errTypeMismatch(v any) error { + return fmt.Errorf( + "%w: got %s, want error", + ErrTypeMismatch, + reflect.TypeOf(v), + ) +} diff --git a/v2/should/wrap_error_test.go b/v2/should/wrap_error_test.go new file mode 100644 index 0000000..cdce75b --- /dev/null +++ b/v2/should/wrap_error_test.go @@ -0,0 +1,27 @@ +package should_test + +import ( + "errors" + "fmt" + "testing" + + "github.com/smarty/gunit/v2/should" +) + +func TestShouldWrapError(t *testing.T) { + assert := NewAssertion(t) + + assert.ExpectedCountInvalid("actual", should.WrapError) + assert.ExpectedCountInvalid("actual", should.WrapError, "EXPECTED", "EXTRA") + + assert.TypeMismatch(inner, should.WrapError, 42) + assert.TypeMismatch(42, should.WrapError, inner) + + assert.Pass(outer, should.WrapError, inner) + assert.Fail(inner, should.WrapError, outer) +} + +var ( + inner = errors.New("inner") + outer = fmt.Errorf("outer(%w)", inner) +) diff --git a/v2/so.go b/v2/so.go new file mode 100644 index 0000000..19fe6cd --- /dev/null +++ b/v2/so.go @@ -0,0 +1,25 @@ +package gunit + +import ( + "errors" + + "github.com/smarty/gunit/v2/should" +) + +func So(t testingT, actual any, assertion Assertion, expected ...any) { + t.Helper() + err := assertion(actual, expected...) + if errors.Is(err, should.ErrFatalAssertionFailure) { + t.Fatal(err) + } + if err != nil { + t.Error(err) + } +} + +type testingT interface { + Helper() + Error(...any) + Fatal(...any) +} +type Assertion func(actual any, expected ...any) error diff --git a/v2/so_test.go b/v2/so_test.go new file mode 100644 index 0000000..6811e07 --- /dev/null +++ b/v2/so_test.go @@ -0,0 +1,75 @@ +package gunit_test + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/smarty/gunit/v2" + "github.com/smarty/gunit/v2/better" + "github.com/smarty/gunit/v2/should" +) + +func TestSoSuccess(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + gunit.So(fakeT, 1, should.Equal, 1) + if fakeT.buffer.String() != "" { + t.Errorf("\n"+ + "expected: \n"+ + "actual: %s", fakeT.buffer.String()) + } +} +func TestSoFailure(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + gunit.So(fakeT, 1, should.Equal, 2) + actual := strings.Join(strings.Fields(fakeT.buffer.String()), " ") + expected := `assertion failure: Expected: (int) 2 Actual: (int) 1 ^ Stack: (filtered)` + if !strings.HasPrefix(actual, expected) { + t.Errorf("\n"+ + "expected: %s\n"+ + "actual: %s", expected, actual) + } + if fakeT.failCount != 1 { + t.Error("Expected 1 fatal failure, got:", fakeT.failCount) + } +} +func TestSoFatalSuccess(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + gunit.So(fakeT, 1, better.Equal, 1) + if fakeT.buffer.String() != "" { + t.Errorf("\n"+ + "expected: \n"+ + "actual: %s", fakeT.buffer.String()) + } +} +func TestSoFatalFailure(t *testing.T) { + fakeT := &FakeT{buffer: &bytes.Buffer{}} + gunit.So(fakeT, 1, better.Equal, 2) + actual := strings.Join(strings.Fields(fakeT.buffer.String()), " ") + expected := "fatal assertion failure: Expected: (int) 2 Actual: (int) 1 ^ Stack: (filtered)" + if !strings.HasPrefix(actual, expected) { + t.Errorf("\n"+ + "expected: %s\n"+ + "actual: %s", expected, actual) + } + if fakeT.fatalCount != 1 { + t.Error("Expected 1 fatal failure, got:", fakeT.fatalCount) + } +} + +type FakeT struct { + buffer *bytes.Buffer + failCount int + fatalCount int +} + +func (this *FakeT) Helper() {} +func (this *FakeT) Error(a ...any) { + this.failCount++ + _, _ = fmt.Fprint(this.buffer, a...) +} +func (this *FakeT) Fatal(a ...any) { + this.fatalCount++ + _, _ = fmt.Fprint(this.buffer, a...) +} From 9b178c61319bdf50811e646e5d99746372960a79 Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 13:21:04 -0700 Subject: [PATCH 2/6] Nest assertions. --- v2/Makefile | 2 +- v2/{ => assert}/better/better.go | 30 +++++++++---------- v2/assert/better/better_test.go | 28 +++++++++++++++++ v2/{ => assert}/should/assert_test.go | 16 +++++----- v2/{ => assert}/should/be_chronological.go | 0 .../should/be_chronological_test.go | 2 +- v2/{ => assert}/should/be_empty.go | 0 v2/{ => assert}/should/be_empty_test.go | 2 +- v2/{ => assert}/should/be_false.go | 0 v2/{ => assert}/should/be_false_test.go | 2 +- v2/{ => assert}/should/be_greater_than.go | 0 .../should/be_greater_than_or_equal_to.go | 0 .../be_greater_than_or_equal_to_test.go | 2 +- .../should/be_greater_than_test.go | 2 +- v2/{ => assert}/should/be_in.go | 0 v2/{ => assert}/should/be_in_test.go | 2 +- v2/{ => assert}/should/be_less_than.go | 0 .../should/be_less_than_or_equal_to.go | 0 .../should/be_less_than_or_equal_to_test.go | 2 +- v2/{ => assert}/should/be_less_than_test.go | 2 +- v2/{ => assert}/should/be_nil.go | 0 v2/{ => assert}/should/be_nil_test.go | 2 +- v2/{ => assert}/should/be_true.go | 0 v2/{ => assert}/should/be_true_test.go | 2 +- v2/{ => assert}/should/contain.go | 0 v2/{ => assert}/should/contain_test.go | 2 +- v2/{ => assert}/should/end_with.go | 0 v2/{ => assert}/should/end_with_test.go | 2 +- v2/{ => assert}/should/equal.go | 16 +++++----- v2/{ => assert}/should/equal_test.go | 2 +- v2/{ => assert}/should/errors.go | 0 v2/{ => assert}/should/errors_test.go | 0 v2/{ => assert}/should/expected.go | 0 v2/{ => assert}/should/happen_after.go | 0 v2/{ => assert}/should/happen_after_test.go | 2 +- v2/{ => assert}/should/happen_before.go | 0 v2/{ => assert}/should/happen_before_test.go | 2 +- v2/{ => assert}/should/happen_on.go | 0 v2/{ => assert}/should/happen_on_test.go | 2 +- v2/{ => assert}/should/happen_within.go | 0 v2/{ => assert}/should/happen_within_test.go | 2 +- v2/{ => assert}/should/have_length.go | 0 v2/{ => assert}/should/have_length_test.go | 2 +- .../should/internal/go-diff/.gitignore | 0 .../should/internal/go-diff/.travis.yml | 0 .../internal/go-diff/APACHE-LICENSE-2.0 | 0 .../should/internal/go-diff/AUTHORS | 0 .../should/internal/go-diff/CONTRIBUTORS | 0 .../should/internal/go-diff/LICENSE | 0 .../should/internal/go-diff/Makefile | 0 .../should/internal/go-diff/README.md | 0 .../internal/go-diff/diffmatchpatch/diff.go | 0 .../go-diff/diffmatchpatch/diffmatchpatch.go | 0 .../internal/go-diff/diffmatchpatch/match.go | 0 .../diffmatchpatch/operation_string.go | 0 .../internal/go-diff/diffmatchpatch/patch.go | 0 .../go-diff/diffmatchpatch/stringutil.go | 0 .../should/internal/go-diff/scripts/lint.sh | 0 .../internal/go-diff/testdata/speedtest1.txt | 0 .../internal/go-diff/testdata/speedtest2.txt | 0 .../should/internal/go-render/.travis.yml | 0 .../should/internal/go-render/LICENSE | 0 .../should/internal/go-render/PRESUBMIT.py | 0 .../should/internal/go-render/README.md | 0 .../should/internal/go-render/WATCHLISTS | 0 .../internal/go-render/pre-commit-go.yml | 0 .../internal/go-render/render/render.go | 0 .../internal/go-render/render/render_test.go | 0 .../internal/go-render/render/render_time.go | 0 v2/{ => assert}/should/kinds.go | 0 v2/{ => assert}/should/not.go | 0 v2/{ => assert}/should/panic.go | 0 v2/{ => assert}/should/panic_test.go | 2 +- v2/{ => assert}/should/spec.go | 0 v2/{ => assert}/should/start_with.go | 0 v2/{ => assert}/should/start_with_test.go | 2 +- v2/{ => assert}/should/wrap_error.go | 0 v2/{ => assert}/should/wrap_error_test.go | 2 +- v2/{ => assert}/so.go | 4 +-- v2/{ => assert}/so_test.go | 16 +++++----- v2/better/better_test.go | 28 ----------------- v2/examples/bowling_game_test.go | 2 +- v2/fixture.go | 6 ++-- v2/fixture_test.go | 2 +- v2/gunit_test.go | 2 +- 85 files changed, 98 insertions(+), 96 deletions(-) rename v2/{ => assert}/better/better.go (79%) create mode 100644 v2/assert/better/better_test.go rename v2/{ => assert}/should/assert_test.go (65%) rename v2/{ => assert}/should/be_chronological.go (100%) rename v2/{ => assert}/should/be_chronological_test.go (96%) rename v2/{ => assert}/should/be_empty.go (100%) rename v2/{ => assert}/should/be_empty_test.go (98%) rename v2/{ => assert}/should/be_false.go (100%) rename v2/{ => assert}/should/be_false_test.go (86%) rename v2/{ => assert}/should/be_greater_than.go (100%) rename v2/{ => assert}/should/be_greater_than_or_equal_to.go (100%) rename v2/{ => assert}/should/be_greater_than_or_equal_to_test.go (99%) rename v2/{ => assert}/should/be_greater_than_test.go (98%) rename v2/{ => assert}/should/be_in.go (100%) rename v2/{ => assert}/should/be_in_test.go (97%) rename v2/{ => assert}/should/be_less_than.go (100%) rename v2/{ => assert}/should/be_less_than_or_equal_to.go (100%) rename v2/{ => assert}/should/be_less_than_or_equal_to_test.go (99%) rename v2/{ => assert}/should/be_less_than_test.go (98%) rename v2/{ => assert}/should/be_nil.go (100%) rename v2/{ => assert}/should/be_nil_test.go (93%) rename v2/{ => assert}/should/be_true.go (100%) rename v2/{ => assert}/should/be_true_test.go (86%) rename v2/{ => assert}/should/contain.go (100%) rename v2/{ => assert}/should/contain_test.go (97%) rename v2/{ => assert}/should/end_with.go (100%) rename v2/{ => assert}/should/end_with_test.go (95%) rename v2/{ => assert}/should/equal.go (91%) rename v2/{ => assert}/should/equal_test.go (96%) rename v2/{ => assert}/should/errors.go (100%) rename v2/{ => assert}/should/errors_test.go (100%) rename v2/{ => assert}/should/expected.go (100%) rename v2/{ => assert}/should/happen_after.go (100%) rename v2/{ => assert}/should/happen_after_test.go (92%) rename v2/{ => assert}/should/happen_before.go (100%) rename v2/{ => assert}/should/happen_before_test.go (92%) rename v2/{ => assert}/should/happen_on.go (100%) rename v2/{ => assert}/should/happen_on_test.go (95%) rename v2/{ => assert}/should/happen_within.go (100%) rename v2/{ => assert}/should/happen_within_test.go (93%) rename v2/{ => assert}/should/have_length.go (100%) rename v2/{ => assert}/should/have_length_test.go (95%) rename v2/{ => assert}/should/internal/go-diff/.gitignore (100%) rename v2/{ => assert}/should/internal/go-diff/.travis.yml (100%) rename v2/{ => assert}/should/internal/go-diff/APACHE-LICENSE-2.0 (100%) rename v2/{ => assert}/should/internal/go-diff/AUTHORS (100%) rename v2/{ => assert}/should/internal/go-diff/CONTRIBUTORS (100%) rename v2/{ => assert}/should/internal/go-diff/LICENSE (100%) rename v2/{ => assert}/should/internal/go-diff/Makefile (100%) rename v2/{ => assert}/should/internal/go-diff/README.md (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/diff.go (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/match.go (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/operation_string.go (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/patch.go (100%) rename v2/{ => assert}/should/internal/go-diff/diffmatchpatch/stringutil.go (100%) rename v2/{ => assert}/should/internal/go-diff/scripts/lint.sh (100%) rename v2/{ => assert}/should/internal/go-diff/testdata/speedtest1.txt (100%) rename v2/{ => assert}/should/internal/go-diff/testdata/speedtest2.txt (100%) rename v2/{ => assert}/should/internal/go-render/.travis.yml (100%) rename v2/{ => assert}/should/internal/go-render/LICENSE (100%) rename v2/{ => assert}/should/internal/go-render/PRESUBMIT.py (100%) rename v2/{ => assert}/should/internal/go-render/README.md (100%) rename v2/{ => assert}/should/internal/go-render/WATCHLISTS (100%) rename v2/{ => assert}/should/internal/go-render/pre-commit-go.yml (100%) rename v2/{ => assert}/should/internal/go-render/render/render.go (100%) rename v2/{ => assert}/should/internal/go-render/render/render_test.go (100%) rename v2/{ => assert}/should/internal/go-render/render/render_time.go (100%) rename v2/{ => assert}/should/kinds.go (100%) rename v2/{ => assert}/should/not.go (100%) rename v2/{ => assert}/should/panic.go (100%) rename v2/{ => assert}/should/panic_test.go (93%) rename v2/{ => assert}/should/spec.go (100%) rename v2/{ => assert}/should/start_with.go (100%) rename v2/{ => assert}/should/start_with_test.go (95%) rename v2/{ => assert}/should/wrap_error.go (100%) rename v2/{ => assert}/should/wrap_error_test.go (92%) rename v2/{ => assert}/so.go (86%) rename v2/{ => assert}/so_test.go (84%) delete mode 100644 v2/better/better_test.go diff --git a/v2/Makefile b/v2/Makefile index 9cdd664..e9264cf 100755 --- a/v2/Makefile +++ b/v2/Makefile @@ -1,7 +1,7 @@ #!/usr/bin/make -f test: fmt - GORACE="atexit_sleep_ms=50" go test -timeout=1s -race -count=1 -covermode=atomic ./... + go test -timeout=1s -race -covermode=atomic ./... fmt: go mod tidy && go fmt ./... diff --git a/v2/better/better.go b/v2/assert/better/better.go similarity index 79% rename from v2/better/better.go rename to v2/assert/better/better.go index 88e7f9f..ef55d91 100644 --- a/v2/better/better.go +++ b/v2/assert/better/better.go @@ -6,8 +6,8 @@ package better import ( "fmt" - "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert" + "github.com/smarty/gunit/v2/assert/should" ) var ( @@ -36,18 +36,18 @@ var ( // NOT constrains all negated assertions to their own 'namespace'. var NOT = struct { - BeChronological gunit.Assertion - BeEmpty gunit.Assertion - BeGreaterThan gunit.Assertion - BeGreaterThanOrEqualTo gunit.Assertion - BeIn gunit.Assertion - BeLessThan gunit.Assertion - BeLessThanOrEqualTo gunit.Assertion - BeNil gunit.Assertion - Contain gunit.Assertion - Equal gunit.Assertion - HappenOn gunit.Assertion - Panic gunit.Assertion + BeChronological assert.Assertion + BeEmpty assert.Assertion + BeGreaterThan assert.Assertion + BeGreaterThanOrEqualTo assert.Assertion + BeIn assert.Assertion + BeLessThan assert.Assertion + BeLessThanOrEqualTo assert.Assertion + BeNil assert.Assertion + Contain assert.Assertion + Equal assert.Assertion + HappenOn assert.Assertion + Panic assert.Assertion }{ BeChronological: wrapFatal(should.NOT.BeChronological), BeEmpty: wrapFatal(should.NOT.BeEmpty), @@ -63,7 +63,7 @@ var NOT = struct { Panic: wrapFatal(should.NOT.Panic), } -func wrapFatal(original gunit.Assertion) gunit.Assertion { +func wrapFatal(original assert.Assertion) assert.Assertion { return func(actual any, expected ...any) error { err := original(actual, expected...) if err != nil { diff --git a/v2/assert/better/better_test.go b/v2/assert/better/better_test.go new file mode 100644 index 0000000..27f1d80 --- /dev/null +++ b/v2/assert/better/better_test.go @@ -0,0 +1,28 @@ +package better_test + +import ( + "testing" + + "github.com/smarty/gunit/v2/assert" + "github.com/smarty/gunit/v2/assert/better" + "github.com/smarty/gunit/v2/assert/should" +) + +func TestWrapFatalSuccess(t *testing.T) { + err := better.Equal(1, 1) + assert.So(t, err, should.BeNil) +} +func TestWrapFatalFailure(t *testing.T) { + err := better.Equal(1, 2) + assert.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) + assert.So(t, err, should.WrapError, should.ErrAssertionFailure) +} +func TestWrapFatalSuccess_NOT(t *testing.T) { + err := better.NOT.Equal(1, 2) + assert.So(t, err, should.BeNil) +} +func TestWrapFatalFailure_NOT(t *testing.T) { + err := better.NOT.Equal(1, 1) + assert.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) + assert.So(t, err, should.WrapError, should.ErrAssertionFailure) +} diff --git a/v2/should/assert_test.go b/v2/assert/should/assert_test.go similarity index 65% rename from v2/should/assert_test.go rename to v2/assert/should/assert_test.go index 56ada4a..be042b5 100644 --- a/v2/should/assert_test.go +++ b/v2/assert/should/assert_test.go @@ -7,8 +7,8 @@ import ( "runtime" "testing" - "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert" + "github.com/smarty/gunit/v2/assert/should" ) type Assertion struct{ *testing.T } @@ -16,27 +16,27 @@ type Assertion struct{ *testing.T } func NewAssertion(t *testing.T) *Assertion { return &Assertion{T: t} } -func (this *Assertion) ExpectedCountInvalid(actual any, assertion gunit.Assertion, expected ...any) { +func (this *Assertion) ExpectedCountInvalid(actual any, assertion assert.Assertion, expected ...any) { this.Helper() this.err(actual, assertion, expected, should.ErrExpectedCountInvalid) } -func (this *Assertion) TypeMismatch(actual any, assertion gunit.Assertion, expected ...any) { +func (this *Assertion) TypeMismatch(actual any, assertion assert.Assertion, expected ...any) { this.Helper() this.err(actual, assertion, expected, should.ErrTypeMismatch) } -func (this *Assertion) KindMismatch(actual any, assertion gunit.Assertion, expected ...any) { +func (this *Assertion) KindMismatch(actual any, assertion assert.Assertion, expected ...any) { this.Helper() this.err(actual, assertion, expected, should.ErrKindMismatch) } -func (this *Assertion) Fail(actual any, assertion gunit.Assertion, expected ...any) { +func (this *Assertion) Fail(actual any, assertion assert.Assertion, expected ...any) { this.Helper() this.err(actual, assertion, expected, should.ErrAssertionFailure) } -func (this *Assertion) Pass(actual any, assertion gunit.Assertion, expected ...any) { +func (this *Assertion) Pass(actual any, assertion assert.Assertion, expected ...any) { this.Helper() this.err(actual, assertion, expected, nil) } -func (this *Assertion) err(actual any, assertion gunit.Assertion, expected []any, expectedErr error) { +func (this *Assertion) err(actual any, assertion assert.Assertion, expected []any, expectedErr error) { this.Helper() _, file, line, _ := runtime.Caller(2) subTest := fmt.Sprintf("%s:%d", filepath.Base(file), line) diff --git a/v2/should/be_chronological.go b/v2/assert/should/be_chronological.go similarity index 100% rename from v2/should/be_chronological.go rename to v2/assert/should/be_chronological.go diff --git a/v2/should/be_chronological_test.go b/v2/assert/should/be_chronological_test.go similarity index 96% rename from v2/should/be_chronological_test.go rename to v2/assert/should/be_chronological_test.go index bd9ddde..99890b0 100644 --- a/v2/should/be_chronological_test.go +++ b/v2/assert/should/be_chronological_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeChronological(t *testing.T) { diff --git a/v2/should/be_empty.go b/v2/assert/should/be_empty.go similarity index 100% rename from v2/should/be_empty.go rename to v2/assert/should/be_empty.go diff --git a/v2/should/be_empty_test.go b/v2/assert/should/be_empty_test.go similarity index 98% rename from v2/should/be_empty_test.go rename to v2/assert/should/be_empty_test.go index c8a1df3..0a57834 100644 --- a/v2/should/be_empty_test.go +++ b/v2/assert/should/be_empty_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeEmpty(t *testing.T) { diff --git a/v2/should/be_false.go b/v2/assert/should/be_false.go similarity index 100% rename from v2/should/be_false.go rename to v2/assert/should/be_false.go diff --git a/v2/should/be_false_test.go b/v2/assert/should/be_false_test.go similarity index 86% rename from v2/should/be_false_test.go rename to v2/assert/should/be_false_test.go index 0815244..77716bf 100644 --- a/v2/should/be_false_test.go +++ b/v2/assert/should/be_false_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeFalse(t *testing.T) { diff --git a/v2/should/be_greater_than.go b/v2/assert/should/be_greater_than.go similarity index 100% rename from v2/should/be_greater_than.go rename to v2/assert/should/be_greater_than.go diff --git a/v2/should/be_greater_than_or_equal_to.go b/v2/assert/should/be_greater_than_or_equal_to.go similarity index 100% rename from v2/should/be_greater_than_or_equal_to.go rename to v2/assert/should/be_greater_than_or_equal_to.go diff --git a/v2/should/be_greater_than_or_equal_to_test.go b/v2/assert/should/be_greater_than_or_equal_to_test.go similarity index 99% rename from v2/should/be_greater_than_or_equal_to_test.go rename to v2/assert/should/be_greater_than_or_equal_to_test.go index 9693599..158dca9 100644 --- a/v2/should/be_greater_than_or_equal_to_test.go +++ b/v2/assert/should/be_greater_than_or_equal_to_test.go @@ -4,7 +4,7 @@ import ( "math" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeGreaterThanOrEqualTo(t *testing.T) { diff --git a/v2/should/be_greater_than_test.go b/v2/assert/should/be_greater_than_test.go similarity index 98% rename from v2/should/be_greater_than_test.go rename to v2/assert/should/be_greater_than_test.go index 19434f2..4604897 100644 --- a/v2/should/be_greater_than_test.go +++ b/v2/assert/should/be_greater_than_test.go @@ -4,7 +4,7 @@ import ( "math" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeGreaterThan(t *testing.T) { diff --git a/v2/should/be_in.go b/v2/assert/should/be_in.go similarity index 100% rename from v2/should/be_in.go rename to v2/assert/should/be_in.go diff --git a/v2/should/be_in_test.go b/v2/assert/should/be_in_test.go similarity index 97% rename from v2/should/be_in_test.go rename to v2/assert/should/be_in_test.go index 1b5a2d1..a6efa6a 100644 --- a/v2/should/be_in_test.go +++ b/v2/assert/should/be_in_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeIn(t *testing.T) { diff --git a/v2/should/be_less_than.go b/v2/assert/should/be_less_than.go similarity index 100% rename from v2/should/be_less_than.go rename to v2/assert/should/be_less_than.go diff --git a/v2/should/be_less_than_or_equal_to.go b/v2/assert/should/be_less_than_or_equal_to.go similarity index 100% rename from v2/should/be_less_than_or_equal_to.go rename to v2/assert/should/be_less_than_or_equal_to.go diff --git a/v2/should/be_less_than_or_equal_to_test.go b/v2/assert/should/be_less_than_or_equal_to_test.go similarity index 99% rename from v2/should/be_less_than_or_equal_to_test.go rename to v2/assert/should/be_less_than_or_equal_to_test.go index 082b20e..79c072a 100644 --- a/v2/should/be_less_than_or_equal_to_test.go +++ b/v2/assert/should/be_less_than_or_equal_to_test.go @@ -4,7 +4,7 @@ import ( "math" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeLessThanOrEqualTo(t *testing.T) { diff --git a/v2/should/be_less_than_test.go b/v2/assert/should/be_less_than_test.go similarity index 98% rename from v2/should/be_less_than_test.go rename to v2/assert/should/be_less_than_test.go index 0e537b7..c75b11e 100644 --- a/v2/should/be_less_than_test.go +++ b/v2/assert/should/be_less_than_test.go @@ -4,7 +4,7 @@ import ( "math" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeLessThan(t *testing.T) { diff --git a/v2/should/be_nil.go b/v2/assert/should/be_nil.go similarity index 100% rename from v2/should/be_nil.go rename to v2/assert/should/be_nil.go diff --git a/v2/should/be_nil_test.go b/v2/assert/should/be_nil_test.go similarity index 93% rename from v2/should/be_nil_test.go rename to v2/assert/should/be_nil_test.go index 3937eca..f44dfd0 100644 --- a/v2/should/be_nil_test.go +++ b/v2/assert/should/be_nil_test.go @@ -4,7 +4,7 @@ import ( "errors" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeNil(t *testing.T) { diff --git a/v2/should/be_true.go b/v2/assert/should/be_true.go similarity index 100% rename from v2/should/be_true.go rename to v2/assert/should/be_true.go diff --git a/v2/should/be_true_test.go b/v2/assert/should/be_true_test.go similarity index 86% rename from v2/should/be_true_test.go rename to v2/assert/should/be_true_test.go index 49b6b03..b3cbf40 100644 --- a/v2/should/be_true_test.go +++ b/v2/assert/should/be_true_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldBeTrue(t *testing.T) { diff --git a/v2/should/contain.go b/v2/assert/should/contain.go similarity index 100% rename from v2/should/contain.go rename to v2/assert/should/contain.go diff --git a/v2/should/contain_test.go b/v2/assert/should/contain_test.go similarity index 97% rename from v2/should/contain_test.go rename to v2/assert/should/contain_test.go index 3037dee..d3e81e2 100644 --- a/v2/should/contain_test.go +++ b/v2/assert/should/contain_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldContain(t *testing.T) { diff --git a/v2/should/end_with.go b/v2/assert/should/end_with.go similarity index 100% rename from v2/should/end_with.go rename to v2/assert/should/end_with.go diff --git a/v2/should/end_with_test.go b/v2/assert/should/end_with_test.go similarity index 95% rename from v2/should/end_with_test.go rename to v2/assert/should/end_with_test.go index 7b9502d..e333df5 100644 --- a/v2/should/end_with_test.go +++ b/v2/assert/should/end_with_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldEndWith(t *testing.T) { diff --git a/v2/should/equal.go b/v2/assert/should/equal.go similarity index 91% rename from v2/should/equal.go rename to v2/assert/should/equal.go index e2a2371..6fe4750 100644 --- a/v2/should/equal.go +++ b/v2/assert/should/equal.go @@ -8,8 +8,8 @@ import ( "strings" "time" - "github.com/smarty/gunit/v2/should/internal/go-diff/diffmatchpatch" - "github.com/smarty/gunit/v2/should/internal/go-render/render" + diffmatchpatch2 "github.com/smarty/gunit/v2/assert/should/internal/go-diff/diffmatchpatch" + "github.com/smarty/gunit/v2/assert/should/internal/go-render/render" ) // Equal verifies that the actual value is equal to the expected value. @@ -99,7 +99,7 @@ func simpleDiff(a, b any) string { } func prettyDiff(actual, expected any) string { - diff := diffmatchpatch.New() + diff := diffmatchpatch2.New() diffs := diff.DiffMain(render.Render(expected), render.Render(actual), false) if prettyDiffIsLikelyToBeHelpful(diffs) { return fmt.Sprintf("\nDiff: '%s'", diff.DiffPrettyText(diffs)) @@ -109,19 +109,19 @@ func prettyDiff(actual, expected any) string { // prettyDiffIsLikelyToBeHelpful returns true if the diff listing contains // more 'equal' segments than 'deleted'/'inserted' segments. -func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch.Diff) bool { +func prettyDiffIsLikelyToBeHelpful(diffs []diffmatchpatch2.Diff) bool { equal, deleted, inserted := measureDiffTypeLengths(diffs) return equal > deleted && equal > inserted } -func measureDiffTypeLengths(diffs []diffmatchpatch.Diff) (equal, deleted, inserted int) { +func measureDiffTypeLengths(diffs []diffmatchpatch2.Diff) (equal, deleted, inserted int) { for _, segment := range diffs { switch segment.Type { - case diffmatchpatch.DiffEqual: + case diffmatchpatch2.DiffEqual: equal += len(segment.Text) - case diffmatchpatch.DiffDelete: + case diffmatchpatch2.DiffDelete: deleted += len(segment.Text) - case diffmatchpatch.DiffInsert: + case diffmatchpatch2.DiffInsert: inserted += len(segment.Text) } } diff --git a/v2/should/equal_test.go b/v2/assert/should/equal_test.go similarity index 96% rename from v2/should/equal_test.go rename to v2/assert/should/equal_test.go index 4b441af..bacb7f0 100644 --- a/v2/should/equal_test.go +++ b/v2/assert/should/equal_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldEqual(t *testing.T) { diff --git a/v2/should/errors.go b/v2/assert/should/errors.go similarity index 100% rename from v2/should/errors.go rename to v2/assert/should/errors.go diff --git a/v2/should/errors_test.go b/v2/assert/should/errors_test.go similarity index 100% rename from v2/should/errors_test.go rename to v2/assert/should/errors_test.go diff --git a/v2/should/expected.go b/v2/assert/should/expected.go similarity index 100% rename from v2/should/expected.go rename to v2/assert/should/expected.go diff --git a/v2/should/happen_after.go b/v2/assert/should/happen_after.go similarity index 100% rename from v2/should/happen_after.go rename to v2/assert/should/happen_after.go diff --git a/v2/should/happen_after_test.go b/v2/assert/should/happen_after_test.go similarity index 92% rename from v2/should/happen_after_test.go rename to v2/assert/should/happen_after_test.go index a5550e1..815f8b5 100644 --- a/v2/should/happen_after_test.go +++ b/v2/assert/should/happen_after_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldHappenAfter(t *testing.T) { diff --git a/v2/should/happen_before.go b/v2/assert/should/happen_before.go similarity index 100% rename from v2/should/happen_before.go rename to v2/assert/should/happen_before.go diff --git a/v2/should/happen_before_test.go b/v2/assert/should/happen_before_test.go similarity index 92% rename from v2/should/happen_before_test.go rename to v2/assert/should/happen_before_test.go index b3e5d23..1147126 100644 --- a/v2/should/happen_before_test.go +++ b/v2/assert/should/happen_before_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldHappenBefore(t *testing.T) { diff --git a/v2/should/happen_on.go b/v2/assert/should/happen_on.go similarity index 100% rename from v2/should/happen_on.go rename to v2/assert/should/happen_on.go diff --git a/v2/should/happen_on_test.go b/v2/assert/should/happen_on_test.go similarity index 95% rename from v2/should/happen_on_test.go rename to v2/assert/should/happen_on_test.go index a6de443..0300783 100644 --- a/v2/should/happen_on_test.go +++ b/v2/assert/should/happen_on_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldHappenOn(t *testing.T) { diff --git a/v2/should/happen_within.go b/v2/assert/should/happen_within.go similarity index 100% rename from v2/should/happen_within.go rename to v2/assert/should/happen_within.go diff --git a/v2/should/happen_within_test.go b/v2/assert/should/happen_within_test.go similarity index 93% rename from v2/should/happen_within_test.go rename to v2/assert/should/happen_within_test.go index e5abd15..4efb923 100644 --- a/v2/should/happen_within_test.go +++ b/v2/assert/should/happen_within_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldHappenWithin(t *testing.T) { diff --git a/v2/should/have_length.go b/v2/assert/should/have_length.go similarity index 100% rename from v2/should/have_length.go rename to v2/assert/should/have_length.go diff --git a/v2/should/have_length_test.go b/v2/assert/should/have_length_test.go similarity index 95% rename from v2/should/have_length_test.go rename to v2/assert/should/have_length_test.go index f6ab390..43e19d1 100644 --- a/v2/should/have_length_test.go +++ b/v2/assert/should/have_length_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldHaveLength(t *testing.T) { diff --git a/v2/should/internal/go-diff/.gitignore b/v2/assert/should/internal/go-diff/.gitignore similarity index 100% rename from v2/should/internal/go-diff/.gitignore rename to v2/assert/should/internal/go-diff/.gitignore diff --git a/v2/should/internal/go-diff/.travis.yml b/v2/assert/should/internal/go-diff/.travis.yml similarity index 100% rename from v2/should/internal/go-diff/.travis.yml rename to v2/assert/should/internal/go-diff/.travis.yml diff --git a/v2/should/internal/go-diff/APACHE-LICENSE-2.0 b/v2/assert/should/internal/go-diff/APACHE-LICENSE-2.0 similarity index 100% rename from v2/should/internal/go-diff/APACHE-LICENSE-2.0 rename to v2/assert/should/internal/go-diff/APACHE-LICENSE-2.0 diff --git a/v2/should/internal/go-diff/AUTHORS b/v2/assert/should/internal/go-diff/AUTHORS similarity index 100% rename from v2/should/internal/go-diff/AUTHORS rename to v2/assert/should/internal/go-diff/AUTHORS diff --git a/v2/should/internal/go-diff/CONTRIBUTORS b/v2/assert/should/internal/go-diff/CONTRIBUTORS similarity index 100% rename from v2/should/internal/go-diff/CONTRIBUTORS rename to v2/assert/should/internal/go-diff/CONTRIBUTORS diff --git a/v2/should/internal/go-diff/LICENSE b/v2/assert/should/internal/go-diff/LICENSE similarity index 100% rename from v2/should/internal/go-diff/LICENSE rename to v2/assert/should/internal/go-diff/LICENSE diff --git a/v2/should/internal/go-diff/Makefile b/v2/assert/should/internal/go-diff/Makefile similarity index 100% rename from v2/should/internal/go-diff/Makefile rename to v2/assert/should/internal/go-diff/Makefile diff --git a/v2/should/internal/go-diff/README.md b/v2/assert/should/internal/go-diff/README.md similarity index 100% rename from v2/should/internal/go-diff/README.md rename to v2/assert/should/internal/go-diff/README.md diff --git a/v2/should/internal/go-diff/diffmatchpatch/diff.go b/v2/assert/should/internal/go-diff/diffmatchpatch/diff.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/diff.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/diff.go diff --git a/v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go b/v2/assert/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/diffmatchpatch.go diff --git a/v2/should/internal/go-diff/diffmatchpatch/match.go b/v2/assert/should/internal/go-diff/diffmatchpatch/match.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/match.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/match.go diff --git a/v2/should/internal/go-diff/diffmatchpatch/operation_string.go b/v2/assert/should/internal/go-diff/diffmatchpatch/operation_string.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/operation_string.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/operation_string.go diff --git a/v2/should/internal/go-diff/diffmatchpatch/patch.go b/v2/assert/should/internal/go-diff/diffmatchpatch/patch.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/patch.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/patch.go diff --git a/v2/should/internal/go-diff/diffmatchpatch/stringutil.go b/v2/assert/should/internal/go-diff/diffmatchpatch/stringutil.go similarity index 100% rename from v2/should/internal/go-diff/diffmatchpatch/stringutil.go rename to v2/assert/should/internal/go-diff/diffmatchpatch/stringutil.go diff --git a/v2/should/internal/go-diff/scripts/lint.sh b/v2/assert/should/internal/go-diff/scripts/lint.sh similarity index 100% rename from v2/should/internal/go-diff/scripts/lint.sh rename to v2/assert/should/internal/go-diff/scripts/lint.sh diff --git a/v2/should/internal/go-diff/testdata/speedtest1.txt b/v2/assert/should/internal/go-diff/testdata/speedtest1.txt similarity index 100% rename from v2/should/internal/go-diff/testdata/speedtest1.txt rename to v2/assert/should/internal/go-diff/testdata/speedtest1.txt diff --git a/v2/should/internal/go-diff/testdata/speedtest2.txt b/v2/assert/should/internal/go-diff/testdata/speedtest2.txt similarity index 100% rename from v2/should/internal/go-diff/testdata/speedtest2.txt rename to v2/assert/should/internal/go-diff/testdata/speedtest2.txt diff --git a/v2/should/internal/go-render/.travis.yml b/v2/assert/should/internal/go-render/.travis.yml similarity index 100% rename from v2/should/internal/go-render/.travis.yml rename to v2/assert/should/internal/go-render/.travis.yml diff --git a/v2/should/internal/go-render/LICENSE b/v2/assert/should/internal/go-render/LICENSE similarity index 100% rename from v2/should/internal/go-render/LICENSE rename to v2/assert/should/internal/go-render/LICENSE diff --git a/v2/should/internal/go-render/PRESUBMIT.py b/v2/assert/should/internal/go-render/PRESUBMIT.py similarity index 100% rename from v2/should/internal/go-render/PRESUBMIT.py rename to v2/assert/should/internal/go-render/PRESUBMIT.py diff --git a/v2/should/internal/go-render/README.md b/v2/assert/should/internal/go-render/README.md similarity index 100% rename from v2/should/internal/go-render/README.md rename to v2/assert/should/internal/go-render/README.md diff --git a/v2/should/internal/go-render/WATCHLISTS b/v2/assert/should/internal/go-render/WATCHLISTS similarity index 100% rename from v2/should/internal/go-render/WATCHLISTS rename to v2/assert/should/internal/go-render/WATCHLISTS diff --git a/v2/should/internal/go-render/pre-commit-go.yml b/v2/assert/should/internal/go-render/pre-commit-go.yml similarity index 100% rename from v2/should/internal/go-render/pre-commit-go.yml rename to v2/assert/should/internal/go-render/pre-commit-go.yml diff --git a/v2/should/internal/go-render/render/render.go b/v2/assert/should/internal/go-render/render/render.go similarity index 100% rename from v2/should/internal/go-render/render/render.go rename to v2/assert/should/internal/go-render/render/render.go diff --git a/v2/should/internal/go-render/render/render_test.go b/v2/assert/should/internal/go-render/render/render_test.go similarity index 100% rename from v2/should/internal/go-render/render/render_test.go rename to v2/assert/should/internal/go-render/render/render_test.go diff --git a/v2/should/internal/go-render/render/render_time.go b/v2/assert/should/internal/go-render/render/render_time.go similarity index 100% rename from v2/should/internal/go-render/render/render_time.go rename to v2/assert/should/internal/go-render/render/render_time.go diff --git a/v2/should/kinds.go b/v2/assert/should/kinds.go similarity index 100% rename from v2/should/kinds.go rename to v2/assert/should/kinds.go diff --git a/v2/should/not.go b/v2/assert/should/not.go similarity index 100% rename from v2/should/not.go rename to v2/assert/should/not.go diff --git a/v2/should/panic.go b/v2/assert/should/panic.go similarity index 100% rename from v2/should/panic.go rename to v2/assert/should/panic.go diff --git a/v2/should/panic_test.go b/v2/assert/should/panic_test.go similarity index 93% rename from v2/should/panic_test.go rename to v2/assert/should/panic_test.go index a32eae6..eaa73cf 100644 --- a/v2/should/panic_test.go +++ b/v2/assert/should/panic_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldPanic(t *testing.T) { diff --git a/v2/should/spec.go b/v2/assert/should/spec.go similarity index 100% rename from v2/should/spec.go rename to v2/assert/should/spec.go diff --git a/v2/should/start_with.go b/v2/assert/should/start_with.go similarity index 100% rename from v2/should/start_with.go rename to v2/assert/should/start_with.go diff --git a/v2/should/start_with_test.go b/v2/assert/should/start_with_test.go similarity index 95% rename from v2/should/start_with_test.go rename to v2/assert/should/start_with_test.go index 8fc8dd8..59e9271 100644 --- a/v2/should/start_with_test.go +++ b/v2/assert/should/start_with_test.go @@ -3,7 +3,7 @@ package should_test import ( "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldStartWith(t *testing.T) { diff --git a/v2/should/wrap_error.go b/v2/assert/should/wrap_error.go similarity index 100% rename from v2/should/wrap_error.go rename to v2/assert/should/wrap_error.go diff --git a/v2/should/wrap_error_test.go b/v2/assert/should/wrap_error_test.go similarity index 92% rename from v2/should/wrap_error_test.go rename to v2/assert/should/wrap_error_test.go index cdce75b..37c28cb 100644 --- a/v2/should/wrap_error_test.go +++ b/v2/assert/should/wrap_error_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldWrapError(t *testing.T) { diff --git a/v2/so.go b/v2/assert/so.go similarity index 86% rename from v2/so.go rename to v2/assert/so.go index 19fe6cd..673d080 100644 --- a/v2/so.go +++ b/v2/assert/so.go @@ -1,9 +1,9 @@ -package gunit +package assert import ( "errors" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func So(t testingT, actual any, assertion Assertion, expected ...any) { diff --git a/v2/so_test.go b/v2/assert/so_test.go similarity index 84% rename from v2/so_test.go rename to v2/assert/so_test.go index 6811e07..b20440b 100644 --- a/v2/so_test.go +++ b/v2/assert/so_test.go @@ -1,4 +1,4 @@ -package gunit_test +package assert_test import ( "bytes" @@ -6,14 +6,14 @@ import ( "strings" "testing" - "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/better" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert" + "github.com/smarty/gunit/v2/assert/better" + "github.com/smarty/gunit/v2/assert/should" ) func TestSoSuccess(t *testing.T) { fakeT := &FakeT{buffer: &bytes.Buffer{}} - gunit.So(fakeT, 1, should.Equal, 1) + assert.So(fakeT, 1, should.Equal, 1) if fakeT.buffer.String() != "" { t.Errorf("\n"+ "expected: \n"+ @@ -22,7 +22,7 @@ func TestSoSuccess(t *testing.T) { } func TestSoFailure(t *testing.T) { fakeT := &FakeT{buffer: &bytes.Buffer{}} - gunit.So(fakeT, 1, should.Equal, 2) + assert.So(fakeT, 1, should.Equal, 2) actual := strings.Join(strings.Fields(fakeT.buffer.String()), " ") expected := `assertion failure: Expected: (int) 2 Actual: (int) 1 ^ Stack: (filtered)` if !strings.HasPrefix(actual, expected) { @@ -36,7 +36,7 @@ func TestSoFailure(t *testing.T) { } func TestSoFatalSuccess(t *testing.T) { fakeT := &FakeT{buffer: &bytes.Buffer{}} - gunit.So(fakeT, 1, better.Equal, 1) + assert.So(fakeT, 1, better.Equal, 1) if fakeT.buffer.String() != "" { t.Errorf("\n"+ "expected: \n"+ @@ -45,7 +45,7 @@ func TestSoFatalSuccess(t *testing.T) { } func TestSoFatalFailure(t *testing.T) { fakeT := &FakeT{buffer: &bytes.Buffer{}} - gunit.So(fakeT, 1, better.Equal, 2) + assert.So(fakeT, 1, better.Equal, 2) actual := strings.Join(strings.Fields(fakeT.buffer.String()), " ") expected := "fatal assertion failure: Expected: (int) 2 Actual: (int) 1 ^ Stack: (filtered)" if !strings.HasPrefix(actual, expected) { diff --git a/v2/better/better_test.go b/v2/better/better_test.go deleted file mode 100644 index efb1c1a..0000000 --- a/v2/better/better_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package better_test - -import ( - "testing" - - "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/better" - "github.com/smarty/gunit/v2/should" -) - -func TestWrapFatalSuccess(t *testing.T) { - err := better.Equal(1, 1) - gunit.So(t, err, should.BeNil) -} -func TestWrapFatalFailure(t *testing.T) { - err := better.Equal(1, 2) - gunit.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) - gunit.So(t, err, should.WrapError, should.ErrAssertionFailure) -} -func TestWrapFatalSuccess_NOT(t *testing.T) { - err := better.NOT.Equal(1, 2) - gunit.So(t, err, should.BeNil) -} -func TestWrapFatalFailure_NOT(t *testing.T) { - err := better.NOT.Equal(1, 1) - gunit.So(t, err, should.WrapError, should.ErrFatalAssertionFailure) - gunit.So(t, err, should.WrapError, should.ErrAssertionFailure) -} diff --git a/v2/examples/bowling_game_test.go b/v2/examples/bowling_game_test.go index d668150..b6fe3f9 100644 --- a/v2/examples/bowling_game_test.go +++ b/v2/examples/bowling_game_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestBowlingGameScoringFixture(t *testing.T) { diff --git a/v2/fixture.go b/v2/fixture.go index 57ad211..e6f6764 100644 --- a/v2/fixture.go +++ b/v2/fixture.go @@ -6,6 +6,8 @@ import ( "io" "runtime/debug" "testing" + + "github.com/smarty/gunit/v2/assert" ) type Fixture struct{ TestingT } @@ -17,9 +19,9 @@ func (this *Fixture) Println(a ...any) { _, _ = fmt.Fprintln(this.Outpu // So is a convenience method for reporting assertion failure messages // with the many assertion functions found in github.com/smarty/gunit/v2/should. // Example: this.So(actual, should.Equal, expected) -func (this *Fixture) So(actual any, assert Assertion, expected ...any) { +func (this *Fixture) So(actual any, assertion assert.Assertion, expected ...any) { this.Helper() - So(this, actual, assert, expected...) + assert.So(this, actual, assertion, expected...) } // Run is analogous to *testing.T.Run and allows for running subtests from diff --git a/v2/fixture_test.go b/v2/fixture_test.go index 243874e..4608ad3 100644 --- a/v2/fixture_test.go +++ b/v2/fixture_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestShouldFailure(t *testing.T) { diff --git a/v2/gunit_test.go b/v2/gunit_test.go index e68b76c..6123cf8 100644 --- a/v2/gunit_test.go +++ b/v2/gunit_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/smarty/gunit/v2" - "github.com/smarty/gunit/v2/should" + "github.com/smarty/gunit/v2/assert/should" ) func TestSuiteWithoutEmbeddedFixture(t *testing.T) { From e7dacde53b18775653064b7a4e22cc2079986a62 Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 13:27:15 -0700 Subject: [PATCH 3/6] A few meta files. --- v2/CONTRIBUTING.md | 12 ++++++++++++ v2/LICENSE.md | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 v2/CONTRIBUTING.md create mode 100644 v2/LICENSE.md diff --git a/v2/CONTRIBUTING.md b/v2/CONTRIBUTING.md new file mode 100644 index 0000000..a8c4823 --- /dev/null +++ b/v2/CONTRIBUTING.md @@ -0,0 +1,12 @@ +# Contributing + +In general, the code posted to the [Smarty github organization](https://github.com/smarty) is created to solve specific problems at Smarty that are ancillary to our core products in the address verification industry and may or may not be useful to other organizations or developers. Our reason for posting said code isn't necessarily to solicit feedback or contributions from the community but more as a showcase of some of the approaches to solving problems we have adopted. + +Having stated that, we do consider issues raised by other githubbers as well as contributions submitted via pull requests. When submitting such a pull request, please follow these guidelines: + +- _Look before you leap:_ If the changes you plan to make are significant, it's in everyone's best interest for you to discuss them with a Smarty team member prior to opening a pull request. +- _License and ownership:_ If modifying the `LICENSE.md` file, limit your changes to fixing typographical mistakes. Do NOT modify the actual terms in the license or the copyright by **Smarty, LLC**. Code submitted to Smarty projects becomes property of Smarty and must be compatible with the associated license. +- _Testing:_ If the code you are submitting resides in packages/modules covered by automated tests, be sure to add passing tests that cover your changes and assert expected behavior and state. Submit the additional test cases as part of your change set. +- _Style:_ Match your approach to **naming** and **formatting** with the surrounding code. Basically, the code you submit shouldn't stand out. + - "Naming" refers to such constructs as variables, methods, functions, classes, structs, interfaces, packages, modules, directories, files, etc... + - "Formatting" refers to such constructs as whitespace, horizontal line length, vertical function length, vertical file length, indentation, curly braces, etc... diff --git a/v2/LICENSE.md b/v2/LICENSE.md new file mode 100644 index 0000000..ac27340 --- /dev/null +++ b/v2/LICENSE.md @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) 2026 Smarty + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +NOTE: Various optional and subordinate components carry their own licensing +requirements and restrictions. Use of those components is subject to the terms +and conditions outlined the respective license of each component. From 98d407c1d0cf4b81d76f972a93ed7de4e612ab6a Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 13:56:05 -0700 Subject: [PATCH 4/6] Department of redundancy department. --- v2/options.go | 1 - 1 file changed, 1 deletion(-) diff --git a/v2/options.go b/v2/options.go index 808e730..0c65f95 100644 --- a/v2/options.go +++ b/v2/options.go @@ -78,7 +78,6 @@ func (singleton) ParallelTests() Option { return func(c *config) { c.parallelTests = true c.freshFixture = true - Options.FreshFixture()(c) } } From 3bfee8ab666619c0fa378e38ad60250ece2f637c Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 13:59:03 -0700 Subject: [PATCH 5/6] Ensure proper spacingbetween words. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See what I did there? ⬆️ --- v2/assert/should/panic.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/v2/assert/should/panic.go b/v2/assert/should/panic.go index b658353..1c8b8d9 100644 --- a/v2/assert/should/panic.go +++ b/v2/assert/should/panic.go @@ -33,10 +33,7 @@ func (negated) Panic(actual any, expected ...any) (err error) { defer func() { r := recover() if panicked { - err = failure(""+ - "provided func should not have"+ - "panicked but it did with: %s", r, - ) + err = failure("provided func should not have panicked but it did with: %s", r) } }() From 61710f72ddd635fb8ee010f15cc4c3ea81e35169 Mon Sep 17 00:00:00 2001 From: Michael Whatcott Date: Wed, 31 Dec 2025 14:01:10 -0700 Subject: [PATCH 6/6] should.EndWith deals with a suffix, not a prefix. --- v2/assert/should/end_with.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/v2/assert/should/end_with.go b/v2/assert/should/end_with.go index 5fb703b..2889260 100644 --- a/v2/assert/should/end_with.go +++ b/v2/assert/should/end_with.go @@ -42,15 +42,15 @@ func EndWith(actual any, expected ...any) error { } full := actual.(string) - prefix := EXPECTED.(string) - if strings.HasSuffix(full, prefix) { + suffix := EXPECTED.(string) + if strings.HasSuffix(full, suffix) { return nil } } return failure("\n"+ - " proposed prefix: %#v\n"+ - " not a prefix of: %#v", + " proposed suffix: %#v\n"+ + " not a suffix of: %#v", EXPECTED, actual, )