Skip to content

Commit

Permalink
Merge pull request #45 from JosiahWitt/ensure-new
Browse files Browse the repository at this point in the history
Allow creating new instances of ensure when package is shadowed
  • Loading branch information
JosiahWitt authored Jun 18, 2021
2 parents f4e3079 + 437b660 commit fd3a99f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions ensurepkg/ensurepkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ func InternalCreateDoNotCallDirectly(t T) Ensure {
return wrap(t)
}

// New creates an instance of ensure with the provided testing context.
//
// This allows the `ensure` package to be shadowed by the `ensure` variable,
// while still allowing new instances of ensure to be created.
func (e Ensure) New(t T) Ensure {
return wrap(t)
}

// Failf fails the test immediately with a formatted message.
// The formatted message follows the same format as the fmt package.
func (e Ensure) Failf(format string, args ...interface{}) {
Expand Down
26 changes: 26 additions & 0 deletions ensurepkg/ensurepkg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,32 @@ func TestNew(t *testing.T) {
})
}

func TestNestedNew(t *testing.T) {
checkTestingContext := func(ensure ensurepkg.Ensure, mockT *mock_ensurepkg.MockT) {
mockT.EXPECT().Helper().AnyTimes()
mockT.EXPECT().Cleanup(gomock.Any()).AnyTimes()

if ensure.T() != mockT {
t.Errorf("The testing context should be the one provided")
}

mockT.EXPECT().Fatalf(gomock.Any(), gomock.Any())
ensure.Failf("") // Should trigger the provided mock context
}

outerMockT := setupMockT(t)
outerEnsure := ensure.New(outerMockT)

innerMockT := setupMockT(t)
innerEnsure := outerEnsure.New(innerMockT) // Uses the nested New method

// Make sure the inner testing context is correct
checkTestingContext(innerEnsure, innerMockT)

// Make sure the original testing context was not changed
checkTestingContext(outerEnsure, outerMockT)
}

func TestEnsureFailf(t *testing.T) {
mockT := setupMockTWithCleanupCheck(t)

Expand Down

0 comments on commit fd3a99f

Please sign in to comment.