How to write broken unit tests for functions returning ok, err?

I have a Lua function that returns falsewith an error message and wants to test its behavior using busted ., Now I am doing it something like this:

function safe_divide(a, b)
    if b > 0 then -- buggy! should be b ~= 0 
        return a / b
    else
        return false, "division by zero"
    end
end

describe("safe_divide", function()
    it("can divide by positive numbers", function()
        local ok, err = safe_divide(10.0, 5.0)
        assert.truthy(ok)
        assert.are.same(2.0, ok)
    end)

    it("errors when dividing by zero", function()
        local ok, err = safe_divide(10.0, 0.0)
        assert.not_truthy(ok)
        assert.are.same("division by zero", err)
    end)

    it("can divide by negative numbers", function()
        local ok, err = safe_divide(-10.0, -5.0)
        assert.truthy(ok)
        assert.are.same(2.0, ok)
    end)
end)

There are two things that I don't like about my current approach:

  • Each test is 3 lines instead of one blank line.
  • When the third test fails, busted simply says that falseit is not a true value as expected, and never mentions a divide by zero error message.

Is there a way to improve my test file to avoid these problems?

, , , has_error busted, , , , , false, .

+4
1

Busted luassert, .

, answers, , - .

local assert = require "luassert"

local function safe_divide(a, b)
    if b > 0 then -- buggy! should be b ~= 0
        return a / b
    else
        return false, "division by zero"
    end
end

local function answers(state, arguments)
  local expected = arguments[1]
  assert(type(expected) == "table")
  for i = 2, #arguments do
      if arguments[i] ~= expected[i-1] then
          state.failure_message = "unexpected result " .. tostring (i-1) .. ": " .. tostring (arguments [i])
          return false
      end
  end
  return true
end
assert:register("assertion", "answers", answers)

describe("safe_divide", function()
    it("can divide by positive numbers", function()
        assert.answers({ 2.0 }, safe_divide(10.0, 5.0))
    end)

    it("errors when dividing by zero", function()
        assert.answers({ false, "division by zero" }, safe_divide(10.0, 0.0))
    end)

    it("can divide by negative numbers", function()
        assert.answers({ 2.0 }, safe_divide(-10.0, -5.0))
    end)
end)

. luaassert . say .

+2

Source: https://habr.com/ru/post/1686154/


All Articles