TestMethod.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. -- @class - TestMethod
  2. -- @desc - used to run a specific method from a module's /test/ suite
  3. -- each assertion is tracked and then printed to output
  4. TestMethod = {
  5. -- @method - TestMethod:new()
  6. -- @desc - create a new TestMethod object
  7. -- @param {string} method - string of method name to run
  8. -- @param {TestMethod} testmethod - parent testmethod this test belongs to
  9. -- @return {table} - returns the new Test object
  10. new = function(self, method, testmodule)
  11. local test = {
  12. testmodule = testmodule,
  13. method = method,
  14. asserts = {},
  15. start = love.timer.getTime(),
  16. finish = 0,
  17. count = 0,
  18. passed = false,
  19. skipped = false,
  20. skipreason = '',
  21. fatal = '',
  22. message = nil,
  23. result = {},
  24. colors = {
  25. red = {1, 0, 0, 1},
  26. redpale = {1, 0.5, 0.5, 1},
  27. red07 = {0.7, 0, 0, 1},
  28. green = {0, 1, 0, 1},
  29. greenhalf = {0, 0.5, 0, 1},
  30. greenfade = {0, 1, 0, 0.5},
  31. blue = {0, 0, 1, 1},
  32. bluefade = {0, 0, 1, 0.5},
  33. yellow = {1, 1, 0, 1},
  34. pink = {1, 0, 1, 1},
  35. black = {0, 0, 0, 1},
  36. white = {1, 1, 1, 1},
  37. lovepink = {214/255, 86/255, 151/255, 1},
  38. loveblue = {83/255, 168/255, 220/255, 1}
  39. },
  40. imgs = 1,
  41. delay = 0,
  42. delayed = false,
  43. store = {},
  44. co = nil
  45. }
  46. setmetatable(test, self)
  47. self.__index = self
  48. return test
  49. end,
  50. -- @method - TestMethod:assertEquals()
  51. -- @desc - used to assert two values are equals
  52. -- @param {any} expected - expected value of the test
  53. -- @param {any} actual - actual value of the test
  54. -- @param {string} label - label for this test to use in exports
  55. -- @return {nil}
  56. assertEquals = function(self, expected, actual, label)
  57. self.count = self.count + 1
  58. table.insert(self.asserts, {
  59. key = 'assert ' .. tostring(self.count),
  60. passed = expected == actual,
  61. message = 'expected \'' .. tostring(expected) .. '\' got \'' ..
  62. tostring(actual) .. '\'',
  63. test = label or 'no label given'
  64. })
  65. end,
  66. -- @method - TestMethod:assertPixels()
  67. -- @desc - checks a list of coloured pixels agaisnt given imgdata
  68. -- @param {ImageData} imgdata - image data to check
  69. -- @param {table} pixels - map of colors to list of pixel coords, i.e.
  70. -- { blue = { {1, 1}, {2, 2}, {3, 4} } }
  71. -- @return {nil}
  72. assertPixels = function(self, imgdata, pixels, label)
  73. for i, v in pairs(pixels) do
  74. local col = self.colors[i]
  75. local pixels = v
  76. for p=1,#pixels do
  77. local coord = pixels[p]
  78. local tr, tg, tb, ta = imgdata:getPixel(coord[1], coord[2])
  79. local compare_id = tostring(coord[1]) .. ',' .. tostring(coord[2])
  80. -- prevent us getting stuff like 0.501960785 for 0.5 red
  81. tr = math.floor((tr*10)+0.5)/10
  82. tg = math.floor((tg*10)+0.5)/10
  83. tb = math.floor((tb*10)+0.5)/10
  84. ta = math.floor((ta*10)+0.5)/10
  85. col[1] = math.floor((col[1]*10)+0.5)/10
  86. col[2] = math.floor((col[2]*10)+0.5)/10
  87. col[3] = math.floor((col[3]*10)+0.5)/10
  88. col[4] = math.floor((col[4]*10)+0.5)/10
  89. -- @TODO add some sort pixel tolerance to the coords
  90. self:assertEquals(col[1], tr, 'check pixel r for ' .. i .. ' at ' .. compare_id .. '(' .. label .. ')')
  91. self:assertEquals(col[2], tg, 'check pixel g for ' .. i .. ' at ' .. compare_id .. '(' .. label .. ')')
  92. self:assertEquals(col[3], tb, 'check pixel b for ' .. i .. ' at ' .. compare_id .. '(' .. label .. ')')
  93. self:assertEquals(col[4], ta, 'check pixel a for ' .. i .. ' at ' .. compare_id .. '(' .. label .. ')')
  94. end
  95. end
  96. end,
  97. -- @method - TestMethod:assertNotEquals()
  98. -- @desc - used to assert two values are not equal
  99. -- @param {any} expected - expected value of the test
  100. -- @param {any} actual - actual value of the test
  101. -- @param {string} label - label for this test to use in exports
  102. -- @return {nil}
  103. assertNotEquals = function(self, expected, actual, label)
  104. self.count = self.count + 1
  105. table.insert(self.asserts, {
  106. key = 'assert ' .. tostring(self.count),
  107. passed = expected ~= actual,
  108. message = 'avoiding \'' .. tostring(expected) .. '\' got \'' ..
  109. tostring(actual) .. '\'',
  110. test = label or 'no label given'
  111. })
  112. end,
  113. -- @method - TestMethod:assertRange()
  114. -- @desc - used to check a value is within an expected range
  115. -- @param {number} actual - actual value of the test
  116. -- @param {number} min - minimum value the actual should be >= to
  117. -- @param {number} max - maximum value the actual should be <= to
  118. -- @param {string} label - label for this test to use in exports
  119. -- @return {nil}
  120. assertRange = function(self, actual, min, max, label)
  121. self.count = self.count + 1
  122. table.insert(self.asserts, {
  123. key = 'assert ' .. tostring(self.count),
  124. passed = actual >= min and actual <= max,
  125. message = 'value \'' .. tostring(actual) .. '\' out of range \'' ..
  126. tostring(min) .. '-' .. tostring(max) .. '\'',
  127. test = label or 'no label given'
  128. })
  129. end,
  130. -- @method - TestMethod:assertMatch()
  131. -- @desc - used to check a value is within a list of values
  132. -- @param {number} list - list of valid values for the test
  133. -- @param {number} actual - actual value of the test to check is in the list
  134. -- @param {string} label - label for this test to use in exports
  135. -- @return {nil}
  136. assertMatch = function(self, list, actual, label)
  137. self.count = self.count + 1
  138. local found = false
  139. for l=1,#list do
  140. if list[l] == actual then found = true end;
  141. end
  142. table.insert(self.asserts, {
  143. key = 'assert ' .. tostring(self.count),
  144. passed = found == true,
  145. message = 'value \'' .. tostring(actual) .. '\' not found in \'' ..
  146. table.concat(list, ',') .. '\'',
  147. test = label or 'no label given'
  148. })
  149. end,
  150. -- @method - TestMethod:assertGreaterEqual()
  151. -- @desc - used to check a value is >= than a certain target value
  152. -- @param {any} target - value to check the test agaisnt
  153. -- @param {any} actual - actual value of the test
  154. -- @param {string} label - label for this test to use in exports
  155. -- @return {nil}
  156. assertGreaterEqual = function(self, target, actual, label)
  157. self.count = self.count + 1
  158. local passing = false
  159. if target ~= nil and actual ~= nil then
  160. passing = actual >= target
  161. end
  162. table.insert(self.asserts, {
  163. key = 'assert ' .. tostring(self.count),
  164. passed = passing,
  165. message = 'value \'' .. tostring(actual) .. '\' not >= \'' ..
  166. tostring(target) .. '\'',
  167. test = label or 'no label given'
  168. })
  169. end,
  170. -- @method - TestMethod:assertLessEqual()
  171. -- @desc - used to check a value is <= than a certain target value
  172. -- @param {any} target - value to check the test agaisnt
  173. -- @param {any} actual - actual value of the test
  174. -- @param {string} label - label for this test to use in exports
  175. -- @return {nil}
  176. assertLessEqual = function(self, target, actual, label)
  177. self.count = self.count + 1
  178. local passing = false
  179. if target ~= nil and actual ~= nil then
  180. passing = actual <= target
  181. end
  182. table.insert(self.asserts, {
  183. key = 'assert ' .. tostring(self.count),
  184. passed = passing,
  185. message = 'value \'' .. tostring(actual) .. '\' not <= \'' ..
  186. tostring(target) .. '\'',
  187. test = label or 'no label given'
  188. })
  189. end,
  190. -- @method - TestMethod:assertObject()
  191. -- @desc - used to check a table is a love object, this runs 3 seperate
  192. -- tests to check table has the basic properties of an object
  193. -- @note - actual object functionality tests have their own methods
  194. -- @param {table} obj - table to check is a valid love object
  195. -- @return {nil}
  196. assertObject = function(self, obj)
  197. self:assertNotNil(obj)
  198. self:assertEquals('userdata', type(obj), 'check is userdata')
  199. if obj ~= nil then
  200. self:assertNotEquals(nil, obj:type(), 'check has :type()')
  201. end
  202. end,
  203. -- @method - TestMethod:assertCoords()
  204. -- @desc - used to check a pair of values (usually coordinates)
  205. -- @param {table} obj - table to check is a valid love object
  206. -- @return {nil}
  207. assertCoords = function(self, expected, actual, label)
  208. self.count = self.count + 1
  209. local passing = false
  210. if expected ~= nil and actual ~= nil then
  211. if expected[1] == actual[1] and expected[2] == actual[2] then
  212. passing = true
  213. end
  214. end
  215. table.insert(self.asserts, {
  216. key = 'assert ' .. tostring(self.count),
  217. passed = passing,
  218. message = 'expected \'' .. tostring(expected[1]) .. 'x,' ..
  219. tostring(expected[2]) .. 'y\' got \'' ..
  220. tostring(actual[1]) .. 'x,' .. tostring(actual[2]) .. 'y\'',
  221. test = label or 'no label given'
  222. })
  223. end,
  224. -- @method - TestMethod:assertNotNil()
  225. -- @desc - quick assert for value not nil
  226. -- @param {any} value - value to check not nil
  227. -- @return {nil}
  228. assertNotNil = function (self, value, err)
  229. self:assertNotEquals(nil, value, 'check not nil')
  230. if err ~= nil then
  231. table.insert(self.asserts, {
  232. key = 'assert ' .. tostring(self.count),
  233. passed = false,
  234. message = err,
  235. test = 'assert not nil catch'
  236. })
  237. end
  238. end,
  239. -- @method - TestMethod:compareImg()
  240. -- @desc - compares a given image to the 'expected' version, with a tolerance of
  241. -- 1px in any direction, and then saves it as the 'actual' version for
  242. -- report viewing
  243. -- @param {table} imgdata - imgdata to save as a png
  244. -- @return {nil}
  245. compareImg = function(self, imgdata)
  246. local expected = love.image.newImageData(
  247. 'tempoutput/expected/love.test.graphics.' .. self.method .. '-' ..
  248. tostring(self.imgs) .. '.png'
  249. )
  250. local iw = imgdata:getWidth()-2
  251. local ih = imgdata:getHeight()-2
  252. local tolerance = 0 -- @NOTE could pass in optional tolerance i.e. 1/255
  253. for ix=2,iw do
  254. for iy=2,ih do
  255. local ir, ig, ib, ia = imgdata:getPixel(ix, iy)
  256. local er, eg, eb, ea = expected:getPixel(ix, iy)
  257. local has_match_r = false
  258. local has_match_g = false
  259. local has_match_b = false
  260. local has_match_a = false
  261. for t=1,9 do
  262. if ir >= er - tolerance and ir <= er + tolerance then has_match_r = true; end
  263. if ig >= eg - tolerance and ig <= eg + tolerance then has_match_g = true; end
  264. if ib >= eb - tolerance and ib <= eb + tolerance then has_match_b = true; end
  265. if ia >= ea - tolerance and ia <= ea + tolerance then has_match_a = true; end
  266. end
  267. local matching = has_match_r and has_match_g and has_match_b and has_match_a
  268. local ymatch = ''
  269. local nmatch = ''
  270. if has_match_r then ymatch = ymatch .. 'r' else nmatch = nmatch .. 'r' end
  271. if has_match_g then ymatch = ymatch .. 'g' else nmatch = nmatch .. 'g' end
  272. if has_match_b then ymatch = ymatch .. 'b' else nmatch = nmatch .. 'b' end
  273. if has_match_a then ymatch = ymatch .. 'a' else nmatch = nmatch .. 'a' end
  274. local pixel = tostring(ir)..','..tostring(ig)..','..tostring(ib)..','..tostring(ia)
  275. self:assertEquals(true, matching, 'compare image pixel (' .. pixel .. ') at ' ..
  276. tostring(ix) .. ',' .. tostring(iy) .. ', matching = ' .. ymatch ..
  277. ', not matching = ' .. nmatch .. ' (' .. self.method .. ')'
  278. )
  279. end
  280. end
  281. local path = 'tempoutput/actual/love.test.graphics.' ..
  282. self.method .. '-' .. tostring(self.imgs) .. '.png'
  283. imgdata:encode('png', path)
  284. self.imgs = self.imgs + 1
  285. end,
  286. -- @method - TestMethod:skipTest()
  287. -- @desc - used to mark this test as skipped for a specific reason
  288. -- @param {string} reason - reason why method is being skipped
  289. -- @return {nil}
  290. skipTest = function(self, reason)
  291. self.skipped = true
  292. self.skipreason = reason
  293. end,
  294. waitFrames = function(self, frames)
  295. for i=1,frames do coroutine.yield() end
  296. end,
  297. -- @method - TestMethod:evaluateTest()
  298. -- @desc - evaluates the results of all assertions for a final restult
  299. -- @return {nil}
  300. evaluateTest = function(self)
  301. local failure = ''
  302. local failures = 0
  303. for a=1,#self.asserts do
  304. -- @TODO just return first failed assertion msg? or all?
  305. -- currently just shows the first assert that failed
  306. if self.asserts[a].passed == false and self.skipped == false then
  307. if failure == '' then failure = self.asserts[a] end
  308. failures = failures + 1
  309. end
  310. end
  311. if self.fatal ~= '' then failure = self.fatal end
  312. local passed = tostring(#self.asserts - failures)
  313. local total = '(' .. passed .. '/' .. tostring(#self.asserts) .. ')'
  314. if self.skipped == true then
  315. self.testmodule.skipped = self.testmodule.skipped + 1
  316. love.test.totals[3] = love.test.totals[3] + 1
  317. self.result = {
  318. total = '',
  319. result = "SKIP",
  320. passed = false,
  321. message = '(0/0) - method skipped [' .. self.skipreason .. ']'
  322. }
  323. else
  324. if failure == '' and #self.asserts > 0 then
  325. self.passed = true
  326. self.testmodule.passed = self.testmodule.passed + 1
  327. love.test.totals[1] = love.test.totals[1] + 1
  328. self.result = {
  329. total = total,
  330. result = 'PASS',
  331. passed = true,
  332. message = nil
  333. }
  334. else
  335. self.passed = false
  336. self.testmodule.failed = self.testmodule.failed + 1
  337. love.test.totals[2] = love.test.totals[2] + 1
  338. if #self.asserts == 0 then
  339. local msg = 'no asserts defined'
  340. if self.fatal ~= '' then msg = self.fatal end
  341. self.result = {
  342. total = total,
  343. result = 'FAIL',
  344. passed = false,
  345. key = 'test',
  346. message = msg
  347. }
  348. else
  349. local key = failure['key']
  350. if failure['test'] ~= nil then
  351. key = key .. ' [' .. failure['test'] .. ']'
  352. end
  353. local msg = failure['message']
  354. if self.fatal ~= '' then
  355. key = 'code'
  356. msg = self.fatal
  357. end
  358. self.result = {
  359. total = total,
  360. result = 'FAIL',
  361. passed = false,
  362. key = key,
  363. message = msg
  364. }
  365. end
  366. end
  367. end
  368. self:printResult()
  369. end,
  370. -- @method - TestMethod:printResult()
  371. -- @desc - prints the result of the test to the console as well as appends
  372. -- the XML + HTML for the test to the testsuite output
  373. -- @return {nil}
  374. printResult = function(self)
  375. -- get total timestamp
  376. -- @TODO make nicer, just need a 3DP ms value
  377. self.finish = love.timer.getTime() - self.start
  378. love.test.time = love.test.time + self.finish
  379. self.testmodule.time = self.testmodule.time + self.finish
  380. local endtime = UtilTimeFormat(love.timer.getTime() - self.start)
  381. -- get failure/skip message for output (if any)
  382. local failure = ''
  383. local output = ''
  384. if self.passed == false and self.skipped == false then
  385. failure = '\t\t\t<failure message="' .. self.result.key .. ' ' ..
  386. self.result.message .. '">' .. self.result.key .. ' ' .. self.result.message .. '</failure>\n'
  387. output = self.result.key .. ' ' .. self.result.message
  388. -- append failures if any to report md
  389. love.test.mdfailures = love.test.mdfailures .. '> 🔴 ' .. self.method .. ' \n' ..
  390. '> ' .. output .. ' \n\n'
  391. end
  392. if output == '' and self.skipped == true then
  393. failure = '\t\t\t<skipped message="' .. self.skipreason .. '" />\n'
  394. output = self.skipreason
  395. end
  396. -- append XML for the test class result
  397. self.testmodule.xml = self.testmodule.xml .. '\t\t<testcase classname="' ..
  398. self.method .. '" name="' .. self.method .. '" assertions="' .. tostring(#self.asserts) ..
  399. '" time="' .. endtime .. '">\n' ..
  400. failure .. '\t\t</testcase>\n'
  401. -- unused currently, adds a preview image for certain graphics methods to the output
  402. local preview = ''
  403. if self.testmodule.module == 'graphics' then
  404. local filename = 'love.test.graphics.' .. self.method
  405. if love.filesystem.openFile('tempoutput/actual/' .. filename .. '-1.png', 'r') then
  406. preview = '<div class="preview">' .. '<img src="expected/' .. filename .. '-1.png"/><p>Expected</p></div>' ..
  407. '<div class="preview">' .. '<img src="actual/' .. filename .. '-1.png"/><p>Actual</p></div>'
  408. end
  409. if love.filesystem.openFile('tempoutput/actual/' .. filename .. '-2.png', 'r') then
  410. preview = preview .. '<div class="preview">' .. '<img src="expected/' .. filename .. '-2.png"/><p>Expected</p></div>' ..
  411. '<div class="preview">' .. '<img src="actual/' .. filename .. '-2.png"/><p>Actual</p></div>'
  412. end
  413. if love.filesystem.openFile('tempoutput/actual/' .. filename .. '-3.png', 'r') then
  414. preview = preview .. '<div class="preview">' .. '<img src="expected/' .. filename .. '-3.png"/><p>Expected</p></div>' ..
  415. '<div class="preview">' .. '<img src="actual/' .. filename .. '-3.png"/><p>Actual</p></div>'
  416. end
  417. end
  418. -- append HTML for the test class result
  419. local status = '🔴'
  420. local cls = 'red'
  421. if self.passed == true then status = '🟢'; cls = '' end
  422. if self.skipped == true then status = '🟡'; cls = '' end
  423. self.testmodule.html = self.testmodule.html ..
  424. '<tr class=" ' .. cls .. '">' ..
  425. '<td>' .. status .. '</td>' ..
  426. '<td>' .. self.method .. '</td>' ..
  427. '<td>' .. endtime .. 's</td>' ..
  428. '<td>' .. output .. preview .. '</td>' ..
  429. '</tr>'
  430. -- add message if assert failed
  431. local msg = ''
  432. if self.result.message ~= nil and self.skipped == false then
  433. msg = ' - ' .. self.result.key ..
  434. ' failed - (' .. self.result.message .. ')'
  435. end
  436. if self.skipped == true then
  437. msg = self.result.message
  438. end
  439. -- log final test result to console
  440. -- i know its hacky but its neat soz
  441. local tested = 'love.' .. self.testmodule.module .. '.' .. self.method .. '()'
  442. local matching = string.sub(self.testmodule.spacer, string.len(tested), 40)
  443. self.testmodule:log(
  444. self.testmodule.colors[self.result.result],
  445. ' ' .. tested .. matching,
  446. ' ==> ' .. self.result.result .. ' - ' .. endtime .. 's ' ..
  447. self.result.total .. msg
  448. )
  449. end
  450. }