diff --git a/CHANGELOG.md b/CHANGELOG.md index be1fc074..73f8014a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,7 @@ - Group working directories of servers inside a replica set into one directory. - Fix collecting coverage if tarantool binary has a suffix. - Add `--no-clean` option to disable deletion of the var directory. +- Add new assert function `assert_one_of`. ## 0.5.7 diff --git a/README.rst b/README.rst index 91f1499f..c849a0ee 100644 --- a/README.rst +++ b/README.rst @@ -170,6 +170,8 @@ List of luatest functions +--------------------------------------------------------------------+-----------------------------------------------+ | ``assert_covers (actual, expected[, message])`` | Checks that actual map includes expected one. | +--------------------------------------------------------------------+-----------------------------------------------+ +| ``assert_one_of (actual, expected[, message])`` | Checks that value is one of alternatives. | ++--------------------------------------------------------------------+-----------------------------------------------+ | ``assert_lt (left, right[, message])`` | Compare numbers. | +--------------------------------------------------------------------+-----------------------------------------------+ | ``assert_le (left, right[, message])`` | | diff --git a/luatest/assertions.lua b/luatest/assertions.lua index 6902133e..9b1f5b54 100644 --- a/luatest/assertions.lua +++ b/luatest/assertions.lua @@ -276,6 +276,25 @@ function M.assert_ge(left, right, message) end end +--- Check that value is one of alternatives. +-- +-- @param actual +-- @param expected +-- @string[opt] message +function M.assert_one_of(actual, expected, message) + local res = false + for _, v in ipairs(expected) do + if comparator.equals(actual, v) then + res = true + break + end + end + if not res then + local str_actual, str_expected = prettystr_pairs(actual, expected) + fail_fmt(2, message, 'Assertion failed: %s must be one of %s', str_actual, str_expected) + end +end + --- Check that two values are not equal. -- Tables are compared by value. -- diff --git a/test/luaunit/assertions_test.lua b/test/luaunit/assertions_test.lua index bdc17055..07e216f6 100644 --- a/test/luaunit/assertions_test.lua +++ b/test/luaunit/assertions_test.lua @@ -969,6 +969,16 @@ function g.test_assertTableAdditions() t.assert_not_equals({1,x=2,3,y=4}, {1,x=2,3}) end +function g.test_assert_one_of() + t.assert_one_of(1, {1,2,3}) + t.assert_one_of({1}, {{1},{2},{3}}) + t.assert_one_of("two", {"one", "two"}) + + assert_failure_contains("oh no", t.assert_one_of, 1, {2,3}, "oh no") + assert_failure_contains("Assertion failed: 1 must be one of {2, 3}", t.assert_one_of, 1, {2,3}) + assert_failure_contains("Assertion failed: {1} must be one of {{2}, {3}}", t.assert_one_of, {1}, {{2},{3}}) +end + g.test_assert_comparisons = function() -- assert_lt t.assert_lt(1.9, 2)