robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
f907614088
master
1--- @class test.assert 2local M ={} 3 4local FORMAT_DEPTH =100 5 6--- @param value any 7--- @return string 8local function fmt ( value ) 9if type ( value ) == 'string' then 10return string . format ( '%q' , value ) 11end 12 13local ok , inspected =pcall ( vim . inspect , value , { depth =FORMAT_DEPTH } ) 14if ok then 15return inspected 16end 17 18return tostring ( value ) 19end 20 21--- @param condition boolean 22--- @param value any 23--- @param context any 24--- @param message string 25local function assert_value ( condition , value , context , message ) 26if not condition then 27error (( context ~= nil and tostring ( context ) .. ': ' or '' ) .. message , 0 ) 28end 29return value 30end 31 32--- @param expected any 33--- @param actual any 34--- @param comparator string 35--- @return string 36local function comparison_message ( expected , actual , comparator ) 37return ( 'Expected values to be %s.\nExpected:\n%s\nActual:\n%s' ): format ( 38comparator , 39fmt ( expected ), 40fmt ( actual ) 41) 42end 43 44--- @param expected any 45--- @param actual any 46--- @param context? any 47--- @return any 48function M . eq ( expected , actual , context ) 49return assert_value ( 50vim . deep_equal ( expected , actual ), 51actual , 52context , 53comparison_message ( expected , actual , 'equal' ) 54) 55end 56 57--- @param expected any 58--- @param actual any 59--- @param context? any 60--- @return any 61function M . neq ( expected , actual , context ) 62return assert_value ( 63not vim . deep_equal ( expected , actual ), 64actual , 65context , 66( 'Expected values to differ.\nValue:\n%s' ): format ( fmt ( actual )) 67) 68end 69 70return setmetatable ( M , { 71--- @param condition any 72--- @param message? string 73--- @param level? integer 74__call =function ( _ , condition , message , level , ... ) 75if condition then 76return condition , message , level , ... 77end 78 79error ( message or 'assertion failed!' , ( type ( level ) == 'number' and level or 1 ) + 1 ) 80end , 81} )