From 9e1bda590fbb412257c476e87fed7f6d903b8acf Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Wed, 8 Mar 2023 13:07:55 +0300 Subject: [PATCH] Add NotPanics checker --- README.md | 5 +++++ checkers.go | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d3dfec9..44a9371 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,11 @@ c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`) c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}). ``` +**`NotPanics`** — Checker verifies that calling the provided zero-argument function will not cause any panic. +```golang +c.Assert(func() { f(1, 2) }, NotPanics). +``` + ### Selecting which tests to run `gocheck` can filter tests out based on the test name, the suite name, or both. To run tests selectively, provide the command line option `-check.f` when running go test. Note that this option is specific to gocheck, and won't affect `go test` itself. diff --git a/checkers.go b/checkers.go index 03f076c..a0c5168 100644 --- a/checkers.go +++ b/checkers.go @@ -424,7 +424,41 @@ func matches(value, regex interface{}) (result bool, error string) { } // ----------------------------------------------------------------------- -// Panics checker. +// NotPanics checker. + +type notPanicsChecker struct { + *CheckerInfo +} + +// The NotPanics checker verifies that calling the provided zero-argument +// function will not cause any panic. +// +// For example: +// +// c.Assert(func() { f(1, 2) }, NotPanics). +// +// +var NotPanics Checker = ¬PanicsChecker{ + &CheckerInfo{Name: "NotPanics", Params: []string{"function"}}, +} + +func (checker *notPanicsChecker) Check(params []interface{}, names []string) (result bool, error string) { + f := reflect.ValueOf(params[0]) + if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { + return false, "Function must take zero arguments" + } + defer func() { + // If the function has not panicked, then don't do the check. + if error != "" { + return + } + params[0] = recover() + names[0] = "panic" + result = params[0] == nil + }() + f.Call(nil) + return true, "" +} type panicsChecker struct { *CheckerInfo