From b281819cbaa915eab848021b72a96bc2041b640d Mon Sep 17 00:00:00 2001 From: Lorenzo Bolla Date: Thu, 16 Dec 2021 14:09:46 +0100 Subject: [PATCH] Make truthy function less surprising --- api/api.go | 11 ++++++++--- api/api_test.go | 18 ++++++++++++------ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/api/api.go b/api/api.go index dc3f2463..b8656178 100644 --- a/api/api.go +++ b/api/api.go @@ -114,18 +114,23 @@ func runTaskInBackground(name string, resources []string, proc task.Process) (ta } func truthy(value interface{}) bool { + if value == nil { + return false + } switch value.(type) { case string: switch strings.ToLower(value.(string)) { - case "y", "yes", "t", "true", "1": + case "n", "no", "f", "false", "0", "off": + return false + default: return true } case int: - return value.(int) == 1 + return !(value.(int) == 0) case bool: return value.(bool) } - return false + return true } func maybeRunTaskInBackground(c *gin.Context, name string, resources []string, proc task.Process) { diff --git a/api/api_test.go b/api/api_test.go index 38529bef..2e55638e 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -93,6 +93,14 @@ func (s *ApiSuite) TestGetVersion(c *C) { } func (s *ApiSuite) TestTruthy(c *C) { + c.Check(truthy("no"), Equals, false) + c.Check(truthy("n"), Equals, false) + c.Check(truthy("off"), Equals, false) + c.Check(truthy("false"), Equals, false) + c.Check(truthy("0"), Equals, false) + c.Check(truthy(false), Equals, false) + c.Check(truthy(0), Equals, false) + c.Check(truthy("y"), Equals, true) c.Check(truthy("yes"), Equals, true) c.Check(truthy("t"), Equals, true) @@ -101,11 +109,9 @@ func (s *ApiSuite) TestTruthy(c *C) { c.Check(truthy(true), Equals, true) c.Check(truthy(1), Equals, true) - c.Check(truthy("no"), Equals, false) - c.Check(truthy("foobar"), Equals, false) - c.Check(truthy(0), Equals, false) - c.Check(truthy(-1), Equals, false) - c.Check(truthy(false), Equals, false) c.Check(truthy(nil), Equals, false) - c.Check(truthy(gin.H{}), Equals, false) + + c.Check(truthy("foobar"), Equals, true) + c.Check(truthy(-1), Equals, true) + c.Check(truthy(gin.H{}), Equals, true) }