Added HasLen checker.
diff --git a/checkers.go b/checkers.go
index 8232384..e6e72c4 100644
--- a/checkers.go
+++ b/checkers.go
@@ -23,7 +23,8 @@
// c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i))
//
// Note that if the comment is constant, a better option is to
-// simply use a normal comment next to the line:
+// simply use a normal comment right above or next to the line, as
+// it will also get printed with any errors:
//
// c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123)
//
@@ -203,6 +204,42 @@
}
// -----------------------------------------------------------------------
+// HasLen checker.
+
+type hasLenChecker struct {
+ *CheckerInfo
+}
+
+// The HasLen checker verifies that the obtained value has the
+// provided length. In many cases this is superior to using Equals
+// in conjuction with the len function because in case the check
+// fails the value itself will be printed, instead of its length,
+// providing more details for figuring the problem.
+//
+// For example:
+//
+// c.Assert(list, HasLen, 5)
+//
+var HasLen Checker = &hasLenChecker{
+ &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}},
+}
+
+func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) {
+ n, ok := params[1].(int)
+ if !ok {
+ return false, "n must be an int"
+ }
+ value := reflect.ValueOf(params[0])
+ switch value.Kind() {
+ case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String:
+ default:
+ return false, "obtained value type has no length"
+ }
+ return value.Len() == n, ""
+}
+
+
+// -----------------------------------------------------------------------
// ErrorMatches checker.
type errorMatchesChecker struct {
diff --git a/checkers_test.go b/checkers_test.go
index d87ace4..0945491 100644
--- a/checkers_test.go
+++ b/checkers_test.go
@@ -134,6 +134,17 @@
testCheck(c, gocheck.DeepEquals, false, "", &simpleStruct{1}, &simpleStruct{2})
}
+func (s *CheckersS) TestHasLen(c *gocheck.C) {
+ testInfo(c, gocheck.HasLen, "HasLen", []string{"obtained", "n"})
+
+ testCheck(c, gocheck.HasLen, true, "", "abcd", 4)
+ testCheck(c, gocheck.HasLen, true, "", []int{1, 2}, 2)
+ testCheck(c, gocheck.HasLen, false, "", []int{1, 2}, 3)
+
+ testCheck(c, gocheck.HasLen, false, "n must be an int", []int{1, 2}, "2")
+ testCheck(c, gocheck.HasLen, false, "obtained value type has no length", nil, 2)
+}
+
func (s *CheckersS) TestErrorMatches(c *gocheck.C) {
testInfo(c, gocheck.ErrorMatches, "ErrorMatches", []string{"value", "regex"})