ert.el 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548
  1. ;;; ert.el --- Emacs Lisp Regression Testing
  2. ;; Copyright (C) 2007-2008, 2010-2012 Free Software Foundation, Inc.
  3. ;; Author: Christian Ohler <ohler@gnu.org>
  4. ;; Keywords: lisp, tools
  5. ;; This file is part of GNU Emacs.
  6. ;; This program is free software: you can redistribute it and/or
  7. ;; modify it under the terms of the GNU General Public License as
  8. ;; published by the Free Software Foundation, either version 3 of the
  9. ;; License, or (at your option) any later version.
  10. ;;
  11. ;; This program is distributed in the hope that it will be useful, but
  12. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. ;; General Public License for more details.
  15. ;;
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with this program. If not, see `http://www.gnu.org/licenses/'.
  18. ;;; Commentary:
  19. ;; ERT is a tool for automated testing in Emacs Lisp. Its main
  20. ;; features are facilities for defining and running test cases and
  21. ;; reporting the results as well as for debugging test failures
  22. ;; interactively.
  23. ;;
  24. ;; The main entry points are `ert-deftest', which is similar to
  25. ;; `defun' but defines a test, and `ert-run-tests-interactively',
  26. ;; which runs tests and offers an interactive interface for inspecting
  27. ;; results and debugging. There is also
  28. ;; `ert-run-tests-batch-and-exit' for non-interactive use.
  29. ;;
  30. ;; The body of `ert-deftest' forms resembles a function body, but the
  31. ;; additional operators `should', `should-not' and `should-error' are
  32. ;; available. `should' is similar to cl's `assert', but signals a
  33. ;; different error when its condition is violated that is caught and
  34. ;; processed by ERT. In addition, it analyzes its argument form and
  35. ;; records information that helps debugging (`assert' tries to do
  36. ;; something similar when its second argument SHOW-ARGS is true, but
  37. ;; `should' is more sophisticated). For information on `should-not'
  38. ;; and `should-error', see their docstrings.
  39. ;;
  40. ;; See ERT's info manual as well as the docstrings for more details.
  41. ;; To compile the manual, run `makeinfo ert.texinfo' in the ERT
  42. ;; directory, then C-u M-x info ert.info in Emacs to view it.
  43. ;;
  44. ;; To see some examples of tests written in ERT, see its self-tests in
  45. ;; ert-tests.el. Some of these are tricky due to the bootstrapping
  46. ;; problem of writing tests for a testing tool, others test simple
  47. ;; functions and are straightforward.
  48. ;;; Code:
  49. (eval-when-compile
  50. (require 'cl))
  51. (require 'button)
  52. (require 'debug)
  53. (require 'easymenu)
  54. (require 'ewoc)
  55. (require 'find-func)
  56. (require 'help)
  57. ;;; UI customization options.
  58. (defgroup ert ()
  59. "ERT, the Emacs Lisp regression testing tool."
  60. :prefix "ert-"
  61. :group 'lisp)
  62. (defface ert-test-result-expected '((((class color) (background light))
  63. :background "green1")
  64. (((class color) (background dark))
  65. :background "green3"))
  66. "Face used for expected results in the ERT results buffer."
  67. :group 'ert)
  68. (defface ert-test-result-unexpected '((((class color) (background light))
  69. :background "red1")
  70. (((class color) (background dark))
  71. :background "red3"))
  72. "Face used for unexpected results in the ERT results buffer."
  73. :group 'ert)
  74. ;;; Copies/reimplementations of cl functions.
  75. (defun ert--cl-do-remf (plist tag)
  76. "Copy of `cl-do-remf'. Modify PLIST by removing TAG."
  77. (let ((p (cdr plist)))
  78. (while (and (cdr p) (not (eq (car (cdr p)) tag))) (setq p (cdr (cdr p))))
  79. (and (cdr p) (progn (setcdr p (cdr (cdr (cdr p)))) t))))
  80. (defun ert--remprop (sym tag)
  81. "Copy of `cl-remprop'. Modify SYM's plist by removing TAG."
  82. (let ((plist (symbol-plist sym)))
  83. (if (and plist (eq tag (car plist)))
  84. (progn (setplist sym (cdr (cdr plist))) t)
  85. (ert--cl-do-remf plist tag))))
  86. (defun ert--remove-if-not (ert-pred ert-list)
  87. "A reimplementation of `remove-if-not'.
  88. ERT-PRED is a predicate, ERT-LIST is the input list."
  89. (loop for ert-x in ert-list
  90. if (funcall ert-pred ert-x)
  91. collect ert-x))
  92. (defun ert--intersection (a b)
  93. "A reimplementation of `intersection'. Intersect the sets A and B.
  94. Elements are compared using `eql'."
  95. (loop for x in a
  96. if (memql x b)
  97. collect x))
  98. (defun ert--set-difference (a b)
  99. "A reimplementation of `set-difference'. Subtract the set B from the set A.
  100. Elements are compared using `eql'."
  101. (loop for x in a
  102. unless (memql x b)
  103. collect x))
  104. (defun ert--set-difference-eq (a b)
  105. "A reimplementation of `set-difference'. Subtract the set B from the set A.
  106. Elements are compared using `eq'."
  107. (loop for x in a
  108. unless (memq x b)
  109. collect x))
  110. (defun ert--union (a b)
  111. "A reimplementation of `union'. Compute the union of the sets A and B.
  112. Elements are compared using `eql'."
  113. (append a (ert--set-difference b a)))
  114. (eval-and-compile
  115. (defvar ert--gensym-counter 0))
  116. (eval-and-compile
  117. (defun ert--gensym (&optional prefix)
  118. "Only allows string PREFIX, not compatible with CL."
  119. (unless prefix (setq prefix "G"))
  120. (make-symbol (format "%s%s"
  121. prefix
  122. (prog1 ert--gensym-counter
  123. (incf ert--gensym-counter))))))
  124. (defun ert--coerce-to-vector (x)
  125. "Coerce X to a vector."
  126. (when (char-table-p x) (error "Not supported"))
  127. (if (vectorp x)
  128. x
  129. (vconcat x)))
  130. (defun* ert--remove* (x list &key key test)
  131. "Does not support all the keywords of remove*."
  132. (unless key (setq key #'identity))
  133. (unless test (setq test #'eql))
  134. (loop for y in list
  135. unless (funcall test x (funcall key y))
  136. collect y))
  137. (defun ert--string-position (c s)
  138. "Return the position of the first occurrence of C in S, or nil if none."
  139. (loop for i from 0
  140. for x across s
  141. when (eql x c) return i))
  142. (defun ert--mismatch (a b)
  143. "Return index of first element that differs between A and B.
  144. Like `mismatch'. Uses `equal' for comparison."
  145. (cond ((or (listp a) (listp b))
  146. (ert--mismatch (ert--coerce-to-vector a)
  147. (ert--coerce-to-vector b)))
  148. ((> (length a) (length b))
  149. (ert--mismatch b a))
  150. (t
  151. (let ((la (length a))
  152. (lb (length b)))
  153. (assert (arrayp a) t)
  154. (assert (arrayp b) t)
  155. (assert (<= la lb) t)
  156. (loop for i below la
  157. when (not (equal (aref a i) (aref b i))) return i
  158. finally (return (if (/= la lb)
  159. la
  160. (assert (equal a b) t)
  161. nil)))))))
  162. (defun ert--subseq (seq start &optional end)
  163. "Return a subsequence of SEQ from START to END."
  164. (when (char-table-p seq) (error "Not supported"))
  165. (let ((vector (substring (ert--coerce-to-vector seq) start end)))
  166. (etypecase seq
  167. (vector vector)
  168. (string (concat vector))
  169. (list (append vector nil))
  170. (bool-vector (loop with result = (make-bool-vector (length vector) nil)
  171. for i below (length vector) do
  172. (setf (aref result i) (aref vector i))
  173. finally (return result)))
  174. (char-table (assert nil)))))
  175. (defun ert-equal-including-properties (a b)
  176. "Return t if A and B have similar structure and contents.
  177. This is like `equal-including-properties' except that it compares
  178. the property values of text properties structurally (by
  179. recursing) rather than with `eq'. Perhaps this is what
  180. `equal-including-properties' should do in the first place; see
  181. Emacs bug 6581 at URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=6581'."
  182. ;; This implementation is inefficient. Rather than making it
  183. ;; efficient, let's hope bug 6581 gets fixed so that we can delete
  184. ;; it altogether.
  185. (not (ert--explain-equal-including-properties a b)))
  186. ;;; Defining and locating tests.
  187. ;; The data structure that represents a test case.
  188. (defstruct ert-test
  189. (name nil)
  190. (documentation nil)
  191. (body (assert nil))
  192. (most-recent-result nil)
  193. (expected-result-type ':passed)
  194. (tags '()))
  195. (defun ert-test-boundp (symbol)
  196. "Return non-nil if SYMBOL names a test."
  197. (and (get symbol 'ert--test) t))
  198. (defun ert-get-test (symbol)
  199. "If SYMBOL names a test, return that. Signal an error otherwise."
  200. (unless (ert-test-boundp symbol) (error "No test named `%S'" symbol))
  201. (get symbol 'ert--test))
  202. (defun ert-set-test (symbol definition)
  203. "Make SYMBOL name the test DEFINITION, and return DEFINITION."
  204. (when (eq symbol 'nil)
  205. ;; We disallow nil since `ert-test-at-point' and related functions
  206. ;; want to return a test name, but also need an out-of-band value
  207. ;; on failure. Nil is the most natural out-of-band value; using 0
  208. ;; or "" or signaling an error would be too awkward.
  209. ;;
  210. ;; Note that nil is still a valid value for the `name' slot in
  211. ;; ert-test objects. It designates an anonymous test.
  212. (error "Attempt to define a test named nil"))
  213. (put symbol 'ert--test definition)
  214. definition)
  215. (defun ert-make-test-unbound (symbol)
  216. "Make SYMBOL name no test. Return SYMBOL."
  217. (ert--remprop symbol 'ert--test)
  218. symbol)
  219. (defun ert--parse-keys-and-body (keys-and-body)
  220. "Split KEYS-AND-BODY into keyword-and-value pairs and the remaining body.
  221. KEYS-AND-BODY should have the form of a property list, with the
  222. exception that only keywords are permitted as keys and that the
  223. tail -- the body -- is a list of forms that does not start with a
  224. keyword.
  225. Returns a two-element list containing the keys-and-values plist
  226. and the body."
  227. (let ((extracted-key-accu '())
  228. (remaining keys-and-body))
  229. (while (and (consp remaining) (keywordp (first remaining)))
  230. (let ((keyword (pop remaining)))
  231. (unless (consp remaining)
  232. (error "Value expected after keyword %S in %S"
  233. keyword keys-and-body))
  234. (when (assoc keyword extracted-key-accu)
  235. (warn "Keyword %S appears more than once in %S" keyword
  236. keys-and-body))
  237. (push (cons keyword (pop remaining)) extracted-key-accu)))
  238. (setq extracted-key-accu (nreverse extracted-key-accu))
  239. (list (loop for (key . value) in extracted-key-accu
  240. collect key
  241. collect value)
  242. remaining)))
  243. ;;;###autoload
  244. (defmacro* ert-deftest (name () &body docstring-keys-and-body)
  245. "Define NAME (a symbol) as a test.
  246. BODY is evaluated as a `progn' when the test is run. It should
  247. signal a condition on failure or just return if the test passes.
  248. `should', `should-not' and `should-error' are useful for
  249. assertions in BODY.
  250. Use `ert' to run tests interactively.
  251. Tests that are expected to fail can be marked as such
  252. using :expected-result. See `ert-test-result-type-p' for a
  253. description of valid values for RESULT-TYPE.
  254. \(fn NAME () [DOCSTRING] [:expected-result RESULT-TYPE] \
  255. \[:tags '(TAG...)] BODY...)"
  256. (declare (debug (&define :name test
  257. name sexp [&optional stringp]
  258. [&rest keywordp sexp] def-body))
  259. (doc-string 3)
  260. (indent 2))
  261. (let ((documentation nil)
  262. (documentation-supplied-p nil))
  263. (when (stringp (first docstring-keys-and-body))
  264. (setq documentation (pop docstring-keys-and-body)
  265. documentation-supplied-p t))
  266. (destructuring-bind ((&key (expected-result nil expected-result-supplied-p)
  267. (tags nil tags-supplied-p))
  268. body)
  269. (ert--parse-keys-and-body docstring-keys-and-body)
  270. `(progn
  271. (ert-set-test ',name
  272. (make-ert-test
  273. :name ',name
  274. ,@(when documentation-supplied-p
  275. `(:documentation ,documentation))
  276. ,@(when expected-result-supplied-p
  277. `(:expected-result-type ,expected-result))
  278. ,@(when tags-supplied-p
  279. `(:tags ,tags))
  280. :body (lambda () ,@body)))
  281. ;; This hack allows `symbol-file' to associate `ert-deftest'
  282. ;; forms with files, and therefore enables `find-function' to
  283. ;; work with tests. However, it leads to warnings in
  284. ;; `unload-feature', which doesn't know how to undefine tests
  285. ;; and has no mechanism for extension.
  286. (push '(ert-deftest . ,name) current-load-list)
  287. ',name))))
  288. ;; We use these `put' forms in addition to the (declare (indent)) in
  289. ;; the defmacro form since the `declare' alone does not lead to
  290. ;; correct indentation before the .el/.elc file is loaded.
  291. ;; Autoloading these `put' forms solves this.
  292. ;;;###autoload
  293. (progn
  294. ;; TODO(ohler): Figure out what these mean and make sure they are correct.
  295. (put 'ert-deftest 'lisp-indent-function 2)
  296. (put 'ert-info 'lisp-indent-function 1))
  297. (defvar ert--find-test-regexp
  298. (concat "^\\s-*(ert-deftest"
  299. find-function-space-re
  300. "%s\\(\\s-\\|$\\)")
  301. "The regexp the `find-function' mechanisms use for finding test definitions.")
  302. (put 'ert-test-failed 'error-conditions '(error ert-test-failed))
  303. (put 'ert-test-failed 'error-message "Test failed")
  304. (defun ert-pass ()
  305. "Terminate the current test and mark it passed. Does not return."
  306. (throw 'ert--pass nil))
  307. (defun ert-fail (data)
  308. "Terminate the current test and mark it failed. Does not return.
  309. DATA is displayed to the user and should state the reason of the failure."
  310. (signal 'ert-test-failed (list data)))
  311. ;;; The `should' macros.
  312. (defvar ert--should-execution-observer nil)
  313. (defun ert--signal-should-execution (form-description)
  314. "Tell the current `should' form observer (if any) about FORM-DESCRIPTION."
  315. (when ert--should-execution-observer
  316. (funcall ert--should-execution-observer form-description)))
  317. (defun ert--special-operator-p (thing)
  318. "Return non-nil if THING is a symbol naming a special operator."
  319. (and (symbolp thing)
  320. (let ((definition (indirect-function thing t)))
  321. (and (subrp definition)
  322. (eql (cdr (subr-arity definition)) 'unevalled)))))
  323. (defun ert--expand-should-1 (whole form inner-expander)
  324. "Helper function for the `should' macro and its variants."
  325. (let ((form
  326. ;; If `cl-macroexpand' isn't bound, the code that we're
  327. ;; compiling doesn't depend on cl and thus doesn't need an
  328. ;; environment arg for `macroexpand'.
  329. (if (fboundp 'cl-macroexpand)
  330. ;; Suppress warning about run-time call to cl function: we
  331. ;; only call it if it's fboundp.
  332. (with-no-warnings
  333. (cl-macroexpand form (and (boundp 'cl-macro-environment)
  334. cl-macro-environment)))
  335. (macroexpand form))))
  336. (cond
  337. ((or (atom form) (ert--special-operator-p (car form)))
  338. (let ((value (ert--gensym "value-")))
  339. `(let ((,value (ert--gensym "ert-form-evaluation-aborted-")))
  340. ,(funcall inner-expander
  341. `(setq ,value ,form)
  342. `(list ',whole :form ',form :value ,value)
  343. value)
  344. ,value)))
  345. (t
  346. (let ((fn-name (car form))
  347. (arg-forms (cdr form)))
  348. (assert (or (symbolp fn-name)
  349. (and (consp fn-name)
  350. (eql (car fn-name) 'lambda)
  351. (listp (cdr fn-name)))))
  352. (let ((fn (ert--gensym "fn-"))
  353. (args (ert--gensym "args-"))
  354. (value (ert--gensym "value-"))
  355. (default-value (ert--gensym "ert-form-evaluation-aborted-")))
  356. `(let ((,fn (function ,fn-name))
  357. (,args (list ,@arg-forms)))
  358. (let ((,value ',default-value))
  359. ,(funcall inner-expander
  360. `(setq ,value (apply ,fn ,args))
  361. `(nconc (list ',whole)
  362. (list :form `(,,fn ,@,args))
  363. (unless (eql ,value ',default-value)
  364. (list :value ,value))
  365. (let ((-explainer-
  366. (and (symbolp ',fn-name)
  367. (get ',fn-name 'ert-explainer))))
  368. (when -explainer-
  369. (list :explanation
  370. (apply -explainer- ,args)))))
  371. value)
  372. ,value))))))))
  373. (defun ert--expand-should (whole form inner-expander)
  374. "Helper function for the `should' macro and its variants.
  375. Analyzes FORM and returns an expression that has the same
  376. semantics under evaluation but records additional debugging
  377. information.
  378. INNER-EXPANDER should be a function and is called with two
  379. arguments: INNER-FORM and FORM-DESCRIPTION-FORM, where INNER-FORM
  380. is an expression equivalent to FORM, and FORM-DESCRIPTION-FORM is
  381. an expression that returns a description of FORM. INNER-EXPANDER
  382. should return code that calls INNER-FORM and performs the checks
  383. and error signaling specific to the particular variant of
  384. `should'. The code that INNER-EXPANDER returns must not call
  385. FORM-DESCRIPTION-FORM before it has called INNER-FORM."
  386. (lexical-let ((inner-expander inner-expander))
  387. (ert--expand-should-1
  388. whole form
  389. (lambda (inner-form form-description-form value-var)
  390. (let ((form-description (ert--gensym "form-description-")))
  391. `(let (,form-description)
  392. ,(funcall inner-expander
  393. `(unwind-protect
  394. ,inner-form
  395. (setq ,form-description ,form-description-form)
  396. (ert--signal-should-execution ,form-description))
  397. `,form-description
  398. value-var)))))))
  399. (defmacro* should (form)
  400. "Evaluate FORM. If it returns nil, abort the current test as failed.
  401. Returns the value of FORM."
  402. (ert--expand-should `(should ,form) form
  403. (lambda (inner-form form-description-form value-var)
  404. `(unless ,inner-form
  405. (ert-fail ,form-description-form)))))
  406. (defmacro* should-not (form)
  407. "Evaluate FORM. If it returns non-nil, abort the current test as failed.
  408. Returns nil."
  409. (ert--expand-should `(should-not ,form) form
  410. (lambda (inner-form form-description-form value-var)
  411. `(unless (not ,inner-form)
  412. (ert-fail ,form-description-form)))))
  413. (defun ert--should-error-handle-error (form-description-fn
  414. condition type exclude-subtypes)
  415. "Helper function for `should-error'.
  416. Determines whether CONDITION matches TYPE and EXCLUDE-SUBTYPES,
  417. and aborts the current test as failed if it doesn't."
  418. (let ((signaled-conditions (get (car condition) 'error-conditions))
  419. (handled-conditions (etypecase type
  420. (list type)
  421. (symbol (list type)))))
  422. (assert signaled-conditions)
  423. (unless (ert--intersection signaled-conditions handled-conditions)
  424. (ert-fail (append
  425. (funcall form-description-fn)
  426. (list
  427. :condition condition
  428. :fail-reason (concat "the error signaled did not"
  429. " have the expected type")))))
  430. (when exclude-subtypes
  431. (unless (member (car condition) handled-conditions)
  432. (ert-fail (append
  433. (funcall form-description-fn)
  434. (list
  435. :condition condition
  436. :fail-reason (concat "the error signaled was a subtype"
  437. " of the expected type"))))))))
  438. ;; FIXME: The expansion will evaluate the keyword args (if any) in
  439. ;; nonstandard order.
  440. (defmacro* should-error (form &rest keys &key type exclude-subtypes)
  441. "Evaluate FORM and check that it signals an error.
  442. The error signaled needs to match TYPE. TYPE should be a list
  443. of condition names. (It can also be a non-nil symbol, which is
  444. equivalent to a singleton list containing that symbol.) If
  445. EXCLUDE-SUBTYPES is nil, the error matches TYPE if one of its
  446. condition names is an element of TYPE. If EXCLUDE-SUBTYPES is
  447. non-nil, the error matches TYPE if it is an element of TYPE.
  448. If the error matches, returns (ERROR-SYMBOL . DATA) from the
  449. error. If not, or if no error was signaled, abort the test as
  450. failed."
  451. (unless type (setq type ''error))
  452. (ert--expand-should
  453. `(should-error ,form ,@keys)
  454. form
  455. (lambda (inner-form form-description-form value-var)
  456. (let ((errorp (ert--gensym "errorp"))
  457. (form-description-fn (ert--gensym "form-description-fn-")))
  458. `(let ((,errorp nil)
  459. (,form-description-fn (lambda () ,form-description-form)))
  460. (condition-case -condition-
  461. ,inner-form
  462. ;; We can't use ,type here because we want to evaluate it.
  463. (error
  464. (setq ,errorp t)
  465. (ert--should-error-handle-error ,form-description-fn
  466. -condition-
  467. ,type ,exclude-subtypes)
  468. (setq ,value-var -condition-)))
  469. (unless ,errorp
  470. (ert-fail (append
  471. (funcall ,form-description-fn)
  472. (list
  473. :fail-reason "did not signal an error")))))))))
  474. ;;; Explanation of `should' failures.
  475. ;; TODO(ohler): Rework explanations so that they are displayed in a
  476. ;; similar way to `ert-info' messages; in particular, allow text
  477. ;; buttons in explanations that give more detail or open an ediff
  478. ;; buffer. Perhaps explanations should be reported through `ert-info'
  479. ;; rather than as part of the condition.
  480. (defun ert--proper-list-p (x)
  481. "Return non-nil if X is a proper list, nil otherwise."
  482. (loop
  483. for firstp = t then nil
  484. for fast = x then (cddr fast)
  485. for slow = x then (cdr slow) do
  486. (when (null fast) (return t))
  487. (when (not (consp fast)) (return nil))
  488. (when (null (cdr fast)) (return t))
  489. (when (not (consp (cdr fast))) (return nil))
  490. (when (and (not firstp) (eq fast slow)) (return nil))))
  491. (defun ert--explain-format-atom (x)
  492. "Format the atom X for `ert--explain-equal'."
  493. (typecase x
  494. (fixnum (list x (format "#x%x" x) (format "?%c" x)))
  495. (t x)))
  496. (defun ert--explain-equal-rec (a b)
  497. "Return a programmer-readable explanation of why A and B are not `equal'.
  498. Returns nil if they are."
  499. (if (not (equal (type-of a) (type-of b)))
  500. `(different-types ,a ,b)
  501. (etypecase a
  502. (cons
  503. (let ((a-proper-p (ert--proper-list-p a))
  504. (b-proper-p (ert--proper-list-p b)))
  505. (if (not (eql (not a-proper-p) (not b-proper-p)))
  506. `(one-list-proper-one-improper ,a ,b)
  507. (if a-proper-p
  508. (if (not (equal (length a) (length b)))
  509. `(proper-lists-of-different-length ,(length a) ,(length b)
  510. ,a ,b
  511. first-mismatch-at
  512. ,(ert--mismatch a b))
  513. (loop for i from 0
  514. for ai in a
  515. for bi in b
  516. for xi = (ert--explain-equal-rec ai bi)
  517. do (when xi (return `(list-elt ,i ,xi)))
  518. finally (assert (equal a b) t)))
  519. (let ((car-x (ert--explain-equal-rec (car a) (car b))))
  520. (if car-x
  521. `(car ,car-x)
  522. (let ((cdr-x (ert--explain-equal-rec (cdr a) (cdr b))))
  523. (if cdr-x
  524. `(cdr ,cdr-x)
  525. (assert (equal a b) t)
  526. nil))))))))
  527. (array (if (not (equal (length a) (length b)))
  528. `(arrays-of-different-length ,(length a) ,(length b)
  529. ,a ,b
  530. ,@(unless (char-table-p a)
  531. `(first-mismatch-at
  532. ,(ert--mismatch a b))))
  533. (loop for i from 0
  534. for ai across a
  535. for bi across b
  536. for xi = (ert--explain-equal-rec ai bi)
  537. do (when xi (return `(array-elt ,i ,xi)))
  538. finally (assert (equal a b) t))))
  539. (atom (if (not (equal a b))
  540. (if (and (symbolp a) (symbolp b) (string= a b))
  541. `(different-symbols-with-the-same-name ,a ,b)
  542. `(different-atoms ,(ert--explain-format-atom a)
  543. ,(ert--explain-format-atom b)))
  544. nil)))))
  545. (defun ert--explain-equal (a b)
  546. "Explainer function for `equal'."
  547. ;; Do a quick comparison in C to avoid running our expensive
  548. ;; comparison when possible.
  549. (if (equal a b)
  550. nil
  551. (ert--explain-equal-rec a b)))
  552. (put 'equal 'ert-explainer 'ert--explain-equal)
  553. (defun ert--significant-plist-keys (plist)
  554. "Return the keys of PLIST that have non-null values, in order."
  555. (assert (zerop (mod (length plist) 2)) t)
  556. (loop for (key value . rest) on plist by #'cddr
  557. unless (or (null value) (memq key accu)) collect key into accu
  558. finally (return accu)))
  559. (defun ert--plist-difference-explanation (a b)
  560. "Return a programmer-readable explanation of why A and B are different plists.
  561. Returns nil if they are equivalent, i.e., have the same value for
  562. each key, where absent values are treated as nil. The order of
  563. key/value pairs in each list does not matter."
  564. (assert (zerop (mod (length a) 2)) t)
  565. (assert (zerop (mod (length b) 2)) t)
  566. ;; Normalizing the plists would be another way to do this but it
  567. ;; requires a total ordering on all lisp objects (since any object
  568. ;; is valid as a text property key). Perhaps defining such an
  569. ;; ordering is useful in other contexts, too, but it's a lot of
  570. ;; work, so let's punt on it for now.
  571. (let* ((keys-a (ert--significant-plist-keys a))
  572. (keys-b (ert--significant-plist-keys b))
  573. (keys-in-a-not-in-b (ert--set-difference-eq keys-a keys-b))
  574. (keys-in-b-not-in-a (ert--set-difference-eq keys-b keys-a)))
  575. (flet ((explain-with-key (key)
  576. (let ((value-a (plist-get a key))
  577. (value-b (plist-get b key)))
  578. (assert (not (equal value-a value-b)) t)
  579. `(different-properties-for-key
  580. ,key ,(ert--explain-equal-including-properties value-a
  581. value-b)))))
  582. (cond (keys-in-a-not-in-b
  583. (explain-with-key (first keys-in-a-not-in-b)))
  584. (keys-in-b-not-in-a
  585. (explain-with-key (first keys-in-b-not-in-a)))
  586. (t
  587. (loop for key in keys-a
  588. when (not (equal (plist-get a key) (plist-get b key)))
  589. return (explain-with-key key)))))))
  590. (defun ert--abbreviate-string (s len suffixp)
  591. "Shorten string S to at most LEN chars.
  592. If SUFFIXP is non-nil, returns a suffix of S, otherwise a prefix."
  593. (let ((n (length s)))
  594. (cond ((< n len)
  595. s)
  596. (suffixp
  597. (substring s (- n len)))
  598. (t
  599. (substring s 0 len)))))
  600. ;; TODO(ohler): Once bug 6581 is fixed, rename this to
  601. ;; `ert--explain-equal-including-properties-rec' and add a fast-path
  602. ;; wrapper like `ert--explain-equal'.
  603. (defun ert--explain-equal-including-properties (a b)
  604. "Explainer function for `ert-equal-including-properties'.
  605. Returns a programmer-readable explanation of why A and B are not
  606. `ert-equal-including-properties', or nil if they are."
  607. (if (not (equal a b))
  608. (ert--explain-equal a b)
  609. (assert (stringp a) t)
  610. (assert (stringp b) t)
  611. (assert (eql (length a) (length b)) t)
  612. (loop for i from 0 to (length a)
  613. for props-a = (text-properties-at i a)
  614. for props-b = (text-properties-at i b)
  615. for difference = (ert--plist-difference-explanation props-a props-b)
  616. do (when difference
  617. (return `(char ,i ,(substring-no-properties a i (1+ i))
  618. ,difference
  619. context-before
  620. ,(ert--abbreviate-string
  621. (substring-no-properties a 0 i)
  622. 10 t)
  623. context-after
  624. ,(ert--abbreviate-string
  625. (substring-no-properties a (1+ i))
  626. 10 nil))))
  627. ;; TODO(ohler): Get `equal-including-properties' fixed in
  628. ;; Emacs, delete `ert-equal-including-properties', and
  629. ;; re-enable this assertion.
  630. ;;finally (assert (equal-including-properties a b) t)
  631. )))
  632. (put 'ert-equal-including-properties
  633. 'ert-explainer
  634. 'ert--explain-equal-including-properties)
  635. ;;; Implementation of `ert-info'.
  636. ;; TODO(ohler): The name `info' clashes with
  637. ;; `ert--test-execution-info'. One or both should be renamed.
  638. (defvar ert--infos '()
  639. "The stack of `ert-info' infos that currently apply.
  640. Bound dynamically. This is a list of (PREFIX . MESSAGE) pairs.")
  641. (defmacro* ert-info ((message-form &key ((:prefix prefix-form) "Info: "))
  642. &body body)
  643. "Evaluate MESSAGE-FORM and BODY, and report the message if BODY fails.
  644. To be used within ERT tests. MESSAGE-FORM should evaluate to a
  645. string that will be displayed together with the test result if
  646. the test fails. PREFIX-FORM should evaluate to a string as well
  647. and is displayed in front of the value of MESSAGE-FORM."
  648. (declare (debug ((form &rest [sexp form]) body))
  649. (indent 1))
  650. `(let ((ert--infos (cons (cons ,prefix-form ,message-form) ert--infos)))
  651. ,@body))
  652. ;;; Facilities for running a single test.
  653. (defvar ert-debug-on-error nil
  654. "Non-nil means enter debugger when a test fails or terminates with an error.")
  655. ;; The data structures that represent the result of running a test.
  656. (defstruct ert-test-result
  657. (messages nil)
  658. (should-forms nil)
  659. )
  660. (defstruct (ert-test-passed (:include ert-test-result)))
  661. (defstruct (ert-test-result-with-condition (:include ert-test-result))
  662. (condition (assert nil))
  663. (backtrace (assert nil))
  664. (infos (assert nil)))
  665. (defstruct (ert-test-quit (:include ert-test-result-with-condition)))
  666. (defstruct (ert-test-failed (:include ert-test-result-with-condition)))
  667. (defstruct (ert-test-aborted-with-non-local-exit (:include ert-test-result)))
  668. (defun ert--record-backtrace ()
  669. "Record the current backtrace (as a list) and return it."
  670. ;; Since the backtrace is stored in the result object, result
  671. ;; objects must only be printed with appropriate limits
  672. ;; (`print-level' and `print-length') in place. For interactive
  673. ;; use, the cost of ensuring this possibly outweighs the advantage
  674. ;; of storing the backtrace for
  675. ;; `ert-results-pop-to-backtrace-for-test-at-point' given that we
  676. ;; already have `ert-results-rerun-test-debugging-errors-at-point'.
  677. ;; For batch use, however, printing the backtrace may be useful.
  678. (loop
  679. ;; 6 is the number of frames our own debugger adds (when
  680. ;; compiled; more when interpreted). FIXME: Need to describe a
  681. ;; procedure for determining this constant.
  682. for i from 6
  683. for frame = (backtrace-frame i)
  684. while frame
  685. collect frame))
  686. (defun ert--print-backtrace (backtrace)
  687. "Format the backtrace BACKTRACE to the current buffer."
  688. ;; This is essentially a reimplementation of Fbacktrace
  689. ;; (src/eval.c), but for a saved backtrace, not the current one.
  690. (let ((print-escape-newlines t)
  691. (print-level 8)
  692. (print-length 50))
  693. (dolist (frame backtrace)
  694. (ecase (first frame)
  695. ((nil)
  696. ;; Special operator.
  697. (destructuring-bind (special-operator &rest arg-forms)
  698. (cdr frame)
  699. (insert
  700. (format " %S\n" (list* special-operator arg-forms)))))
  701. ((t)
  702. ;; Function call.
  703. (destructuring-bind (fn &rest args) (cdr frame)
  704. (insert (format " %S(" fn))
  705. (loop for firstp = t then nil
  706. for arg in args do
  707. (unless firstp
  708. (insert " "))
  709. (insert (format "%S" arg)))
  710. (insert ")\n")))))))
  711. ;; A container for the state of the execution of a single test and
  712. ;; environment data needed during its execution.
  713. (defstruct ert--test-execution-info
  714. (test (assert nil))
  715. (result (assert nil))
  716. ;; A thunk that may be called when RESULT has been set to its final
  717. ;; value and test execution should be terminated. Should not
  718. ;; return.
  719. (exit-continuation (assert nil))
  720. ;; The binding of `debugger' outside of the execution of the test.
  721. next-debugger
  722. ;; The binding of `ert-debug-on-error' that is in effect for the
  723. ;; execution of the current test. We store it to avoid being
  724. ;; affected by any new bindings the test itself may establish. (I
  725. ;; don't remember whether this feature is important.)
  726. ert-debug-on-error)
  727. (defun ert--run-test-debugger (info debugger-args)
  728. "During a test run, `debugger' is bound to a closure that calls this function.
  729. This function records failures and errors and either terminates
  730. the test silently or calls the interactive debugger, as
  731. appropriate.
  732. INFO is the ert--test-execution-info corresponding to this test
  733. run. DEBUGGER-ARGS are the arguments to `debugger'."
  734. (destructuring-bind (first-debugger-arg &rest more-debugger-args)
  735. debugger-args
  736. (ecase first-debugger-arg
  737. ((lambda debug t exit nil)
  738. (apply (ert--test-execution-info-next-debugger info) debugger-args))
  739. (error
  740. (let* ((condition (first more-debugger-args))
  741. (type (case (car condition)
  742. ((quit) 'quit)
  743. (otherwise 'failed)))
  744. (backtrace (ert--record-backtrace))
  745. (infos (reverse ert--infos)))
  746. (setf (ert--test-execution-info-result info)
  747. (ecase type
  748. (quit
  749. (make-ert-test-quit :condition condition
  750. :backtrace backtrace
  751. :infos infos))
  752. (failed
  753. (make-ert-test-failed :condition condition
  754. :backtrace backtrace
  755. :infos infos))))
  756. ;; Work around Emacs's heuristic (in eval.c) for detecting
  757. ;; errors in the debugger.
  758. (incf num-nonmacro-input-events)
  759. ;; FIXME: We should probably implement more fine-grained
  760. ;; control a la non-t `debug-on-error' here.
  761. (cond
  762. ((ert--test-execution-info-ert-debug-on-error info)
  763. (apply (ert--test-execution-info-next-debugger info) debugger-args))
  764. (t))
  765. (funcall (ert--test-execution-info-exit-continuation info)))))))
  766. (defun ert--run-test-internal (ert-test-execution-info)
  767. "Low-level function to run a test according to ERT-TEST-EXECUTION-INFO.
  768. This mainly sets up debugger-related bindings."
  769. (lexical-let ((info ert-test-execution-info))
  770. (setf (ert--test-execution-info-next-debugger info) debugger
  771. (ert--test-execution-info-ert-debug-on-error info) ert-debug-on-error)
  772. (catch 'ert--pass
  773. ;; For now, each test gets its own temp buffer and its own
  774. ;; window excursion, just to be safe. If this turns out to be
  775. ;; too expensive, we can remove it.
  776. (with-temp-buffer
  777. (save-window-excursion
  778. (let ((debugger (lambda (&rest debugger-args)
  779. (ert--run-test-debugger info debugger-args)))
  780. (debug-on-error t)
  781. (debug-on-quit t)
  782. ;; FIXME: Do we need to store the old binding of this
  783. ;; and consider it in `ert--run-test-debugger'?
  784. (debug-ignored-errors nil)
  785. (ert--infos '()))
  786. (funcall (ert-test-body (ert--test-execution-info-test info))))))
  787. (ert-pass))
  788. (setf (ert--test-execution-info-result info) (make-ert-test-passed)))
  789. nil)
  790. (defun ert--force-message-log-buffer-truncation ()
  791. "Immediately truncate *Messages* buffer according to `message-log-max'.
  792. This can be useful after reducing the value of `message-log-max'."
  793. (with-current-buffer (get-buffer-create "*Messages*")
  794. ;; This is a reimplementation of this part of message_dolog() in xdisp.c:
  795. ;; if (NATNUMP (Vmessage_log_max))
  796. ;; {
  797. ;; scan_newline (Z, Z_BYTE, BEG, BEG_BYTE,
  798. ;; -XFASTINT (Vmessage_log_max) - 1, 0);
  799. ;; del_range_both (BEG, BEG_BYTE, PT, PT_BYTE, 0);
  800. ;; }
  801. (when (and (integerp message-log-max) (>= message-log-max 0))
  802. (let ((begin (point-min))
  803. (end (save-excursion
  804. (goto-char (point-max))
  805. (forward-line (- message-log-max))
  806. (point))))
  807. (delete-region begin end)))))
  808. (defvar ert--running-tests nil
  809. "List of tests that are currently in execution.
  810. This list is empty while no test is running, has one element
  811. while a test is running, two elements while a test run from
  812. inside a test is running, etc. The list is in order of nesting,
  813. innermost test first.
  814. The elements are of type `ert-test'.")
  815. (defun ert-run-test (ert-test)
  816. "Run ERT-TEST.
  817. Returns the result and stores it in ERT-TEST's `most-recent-result' slot."
  818. (setf (ert-test-most-recent-result ert-test) nil)
  819. (block error
  820. (lexical-let ((begin-marker
  821. (with-current-buffer (get-buffer-create "*Messages*")
  822. (set-marker (make-marker) (point-max)))))
  823. (unwind-protect
  824. (lexical-let ((info (make-ert--test-execution-info
  825. :test ert-test
  826. :result
  827. (make-ert-test-aborted-with-non-local-exit)
  828. :exit-continuation (lambda ()
  829. (return-from error nil))))
  830. (should-form-accu (list)))
  831. (unwind-protect
  832. (let ((ert--should-execution-observer
  833. (lambda (form-description)
  834. (push form-description should-form-accu)))
  835. (message-log-max t)
  836. (ert--running-tests (cons ert-test ert--running-tests)))
  837. (ert--run-test-internal info))
  838. (let ((result (ert--test-execution-info-result info)))
  839. (setf (ert-test-result-messages result)
  840. (with-current-buffer (get-buffer-create "*Messages*")
  841. (buffer-substring begin-marker (point-max))))
  842. (ert--force-message-log-buffer-truncation)
  843. (setq should-form-accu (nreverse should-form-accu))
  844. (setf (ert-test-result-should-forms result)
  845. should-form-accu)
  846. (setf (ert-test-most-recent-result ert-test) result))))
  847. (set-marker begin-marker nil))))
  848. (ert-test-most-recent-result ert-test))
  849. (defun ert-running-test ()
  850. "Return the top-level test currently executing."
  851. (car (last ert--running-tests)))
  852. ;;; Test selectors.
  853. (defun ert-test-result-type-p (result result-type)
  854. "Return non-nil if RESULT matches type RESULT-TYPE.
  855. Valid result types:
  856. nil -- Never matches.
  857. t -- Always matches.
  858. :failed, :passed -- Matches corresponding results.
  859. \(and TYPES...\) -- Matches if all TYPES match.
  860. \(or TYPES...\) -- Matches if some TYPES match.
  861. \(not TYPE\) -- Matches if TYPE does not match.
  862. \(satisfies PREDICATE\) -- Matches if PREDICATE returns true when called with
  863. RESULT."
  864. ;; It would be easy to add `member' and `eql' types etc., but I
  865. ;; haven't bothered yet.
  866. (etypecase result-type
  867. ((member nil) nil)
  868. ((member t) t)
  869. ((member :failed) (ert-test-failed-p result))
  870. ((member :passed) (ert-test-passed-p result))
  871. (cons
  872. (destructuring-bind (operator &rest operands) result-type
  873. (ecase operator
  874. (and
  875. (case (length operands)
  876. (0 t)
  877. (t
  878. (and (ert-test-result-type-p result (first operands))
  879. (ert-test-result-type-p result `(and ,@(rest operands)))))))
  880. (or
  881. (case (length operands)
  882. (0 nil)
  883. (t
  884. (or (ert-test-result-type-p result (first operands))
  885. (ert-test-result-type-p result `(or ,@(rest operands)))))))
  886. (not
  887. (assert (eql (length operands) 1))
  888. (not (ert-test-result-type-p result (first operands))))
  889. (satisfies
  890. (assert (eql (length operands) 1))
  891. (funcall (first operands) result)))))))
  892. (defun ert-test-result-expected-p (test result)
  893. "Return non-nil if TEST's expected result type matches RESULT."
  894. (ert-test-result-type-p result (ert-test-expected-result-type test)))
  895. (defun ert-select-tests (selector universe)
  896. "Return a list of tests that match SELECTOR.
  897. UNIVERSE specifies the set of tests to select from; it should be a list
  898. of tests, or t, which refers to all tests named by symbols in `obarray'.
  899. Valid SELECTORs:
  900. nil -- Selects the empty set.
  901. t -- Selects UNIVERSE.
  902. :new -- Selects all tests that have not been run yet.
  903. :failed, :passed -- Select tests according to their most recent result.
  904. :expected, :unexpected -- Select tests according to their most recent result.
  905. a string -- A regular expression selecting all tests with matching names.
  906. a test -- (i.e., an object of the ert-test data-type) Selects that test.
  907. a symbol -- Selects the test that the symbol names, errors if none.
  908. \(member TESTS...) -- Selects the elements of TESTS, a list of tests
  909. or symbols naming tests.
  910. \(eql TEST\) -- Selects TEST, a test or a symbol naming a test.
  911. \(and SELECTORS...) -- Selects the tests that match all SELECTORS.
  912. \(or SELECTORS...) -- Selects the tests that match any of the SELECTORS.
  913. \(not SELECTOR) -- Selects all tests that do not match SELECTOR.
  914. \(tag TAG) -- Selects all tests that have TAG on their tags list.
  915. A tag is an arbitrary label you can apply when you define a test.
  916. \(satisfies PREDICATE) -- Selects all tests that satisfy PREDICATE.
  917. PREDICATE is a function that takes an ert-test object as argument,
  918. and returns non-nil if it is selected.
  919. Only selectors that require a superset of tests, such
  920. as (satisfies ...), strings, :new, etc. make use of UNIVERSE.
  921. Selectors that do not, such as (member ...), just return the
  922. set implied by them without checking whether it is really
  923. contained in UNIVERSE."
  924. ;; This code needs to match the etypecase in
  925. ;; `ert-insert-human-readable-selector'.
  926. (etypecase selector
  927. ((member nil) nil)
  928. ((member t) (etypecase universe
  929. (list universe)
  930. ((member t) (ert-select-tests "" universe))))
  931. ((member :new) (ert-select-tests
  932. `(satisfies ,(lambda (test)
  933. (null (ert-test-most-recent-result test))))
  934. universe))
  935. ((member :failed) (ert-select-tests
  936. `(satisfies ,(lambda (test)
  937. (ert-test-result-type-p
  938. (ert-test-most-recent-result test)
  939. ':failed)))
  940. universe))
  941. ((member :passed) (ert-select-tests
  942. `(satisfies ,(lambda (test)
  943. (ert-test-result-type-p
  944. (ert-test-most-recent-result test)
  945. ':passed)))
  946. universe))
  947. ((member :expected) (ert-select-tests
  948. `(satisfies
  949. ,(lambda (test)
  950. (ert-test-result-expected-p
  951. test
  952. (ert-test-most-recent-result test))))
  953. universe))
  954. ((member :unexpected) (ert-select-tests `(not :expected) universe))
  955. (string
  956. (etypecase universe
  957. ((member t) (mapcar #'ert-get-test
  958. (apropos-internal selector #'ert-test-boundp)))
  959. (list (ert--remove-if-not (lambda (test)
  960. (and (ert-test-name test)
  961. (string-match selector
  962. (ert-test-name test))))
  963. universe))))
  964. (ert-test (list selector))
  965. (symbol
  966. (assert (ert-test-boundp selector))
  967. (list (ert-get-test selector)))
  968. (cons
  969. (destructuring-bind (operator &rest operands) selector
  970. (ecase operator
  971. (member
  972. (mapcar (lambda (purported-test)
  973. (etypecase purported-test
  974. (symbol (assert (ert-test-boundp purported-test))
  975. (ert-get-test purported-test))
  976. (ert-test purported-test)))
  977. operands))
  978. (eql
  979. (assert (eql (length operands) 1))
  980. (ert-select-tests `(member ,@operands) universe))
  981. (and
  982. ;; Do these definitions of AND, NOT and OR satisfy de
  983. ;; Morgan's laws? Should they?
  984. (case (length operands)
  985. (0 (ert-select-tests 't universe))
  986. (t (ert-select-tests `(and ,@(rest operands))
  987. (ert-select-tests (first operands)
  988. universe)))))
  989. (not
  990. (assert (eql (length operands) 1))
  991. (let ((all-tests (ert-select-tests 't universe)))
  992. (ert--set-difference all-tests
  993. (ert-select-tests (first operands)
  994. all-tests))))
  995. (or
  996. (case (length operands)
  997. (0 (ert-select-tests 'nil universe))
  998. (t (ert--union (ert-select-tests (first operands) universe)
  999. (ert-select-tests `(or ,@(rest operands))
  1000. universe)))))
  1001. (tag
  1002. (assert (eql (length operands) 1))
  1003. (let ((tag (first operands)))
  1004. (ert-select-tests `(satisfies
  1005. ,(lambda (test)
  1006. (member tag (ert-test-tags test))))
  1007. universe)))
  1008. (satisfies
  1009. (assert (eql (length operands) 1))
  1010. (ert--remove-if-not (first operands)
  1011. (ert-select-tests 't universe))))))))
  1012. (defun ert--insert-human-readable-selector (selector)
  1013. "Insert a human-readable presentation of SELECTOR into the current buffer."
  1014. ;; This is needed to avoid printing the (huge) contents of the
  1015. ;; `backtrace' slot of the result objects in the
  1016. ;; `most-recent-result' slots of test case objects in (eql ...) or
  1017. ;; (member ...) selectors.
  1018. (labels ((rec (selector)
  1019. ;; This code needs to match the etypecase in `ert-select-tests'.
  1020. (etypecase selector
  1021. ((or (member nil t
  1022. :new :failed :passed
  1023. :expected :unexpected)
  1024. string
  1025. symbol)
  1026. selector)
  1027. (ert-test
  1028. (if (ert-test-name selector)
  1029. (make-symbol (format "<%S>" (ert-test-name selector)))
  1030. (make-symbol "<unnamed test>")))
  1031. (cons
  1032. (destructuring-bind (operator &rest operands) selector
  1033. (ecase operator
  1034. ((member eql and not or)
  1035. `(,operator ,@(mapcar #'rec operands)))
  1036. ((member tag satisfies)
  1037. selector)))))))
  1038. (insert (format "%S" (rec selector)))))
  1039. ;;; Facilities for running a whole set of tests.
  1040. ;; The data structure that contains the set of tests being executed
  1041. ;; during one particular test run, their results, the state of the
  1042. ;; execution, and some statistics.
  1043. ;;
  1044. ;; The data about results and expected results of tests may seem
  1045. ;; redundant here, since the test objects also carry such information.
  1046. ;; However, the information in the test objects may be more recent, it
  1047. ;; may correspond to a different test run. We need the information
  1048. ;; that corresponds to this run in order to be able to update the
  1049. ;; statistics correctly when a test is re-run interactively and has a
  1050. ;; different result than before.
  1051. (defstruct ert--stats
  1052. (selector (assert nil))
  1053. ;; The tests, in order.
  1054. (tests (assert nil) :type vector)
  1055. ;; A map of test names (or the test objects themselves for unnamed
  1056. ;; tests) to indices into the `tests' vector.
  1057. (test-map (assert nil) :type hash-table)
  1058. ;; The results of the tests during this run, in order.
  1059. (test-results (assert nil) :type vector)
  1060. ;; The start times of the tests, in order, as reported by
  1061. ;; `current-time'.
  1062. (test-start-times (assert nil) :type vector)
  1063. ;; The end times of the tests, in order, as reported by
  1064. ;; `current-time'.
  1065. (test-end-times (assert nil) :type vector)
  1066. (passed-expected 0)
  1067. (passed-unexpected 0)
  1068. (failed-expected 0)
  1069. (failed-unexpected 0)
  1070. (start-time nil)
  1071. (end-time nil)
  1072. (aborted-p nil)
  1073. (current-test nil)
  1074. ;; The time at or after which the next redisplay should occur, as a
  1075. ;; float.
  1076. (next-redisplay 0.0))
  1077. (defun ert-stats-completed-expected (stats)
  1078. "Return the number of tests in STATS that had expected results."
  1079. (+ (ert--stats-passed-expected stats)
  1080. (ert--stats-failed-expected stats)))
  1081. (defun ert-stats-completed-unexpected (stats)
  1082. "Return the number of tests in STATS that had unexpected results."
  1083. (+ (ert--stats-passed-unexpected stats)
  1084. (ert--stats-failed-unexpected stats)))
  1085. (defun ert-stats-completed (stats)
  1086. "Number of tests in STATS that have run so far."
  1087. (+ (ert-stats-completed-expected stats)
  1088. (ert-stats-completed-unexpected stats)))
  1089. (defun ert-stats-total (stats)
  1090. "Number of tests in STATS, regardless of whether they have run yet."
  1091. (length (ert--stats-tests stats)))
  1092. ;; The stats object of the current run, dynamically bound. This is
  1093. ;; used for the mode line progress indicator.
  1094. (defvar ert--current-run-stats nil)
  1095. (defun ert--stats-test-key (test)
  1096. "Return the key used for TEST in the test map of ert--stats objects.
  1097. Returns the name of TEST if it has one, or TEST itself otherwise."
  1098. (or (ert-test-name test) test))
  1099. (defun ert--stats-set-test-and-result (stats pos test result)
  1100. "Change STATS by replacing the test at position POS with TEST and RESULT.
  1101. Also changes the counters in STATS to match."
  1102. (let* ((tests (ert--stats-tests stats))
  1103. (results (ert--stats-test-results stats))
  1104. (old-test (aref tests pos))
  1105. (map (ert--stats-test-map stats)))
  1106. (flet ((update (d)
  1107. (if (ert-test-result-expected-p (aref tests pos)
  1108. (aref results pos))
  1109. (etypecase (aref results pos)
  1110. (ert-test-passed (incf (ert--stats-passed-expected stats) d))
  1111. (ert-test-failed (incf (ert--stats-failed-expected stats) d))
  1112. (null)
  1113. (ert-test-aborted-with-non-local-exit)
  1114. (ert-test-quit))
  1115. (etypecase (aref results pos)
  1116. (ert-test-passed (incf (ert--stats-passed-unexpected stats) d))
  1117. (ert-test-failed (incf (ert--stats-failed-unexpected stats) d))
  1118. (null)
  1119. (ert-test-aborted-with-non-local-exit)
  1120. (ert-test-quit)))))
  1121. ;; Adjust counters to remove the result that is currently in stats.
  1122. (update -1)
  1123. ;; Put new test and result into stats.
  1124. (setf (aref tests pos) test
  1125. (aref results pos) result)
  1126. (remhash (ert--stats-test-key old-test) map)
  1127. (setf (gethash (ert--stats-test-key test) map) pos)
  1128. ;; Adjust counters to match new result.
  1129. (update +1)
  1130. nil)))
  1131. (defun ert--make-stats (tests selector)
  1132. "Create a new `ert--stats' object for running TESTS.
  1133. SELECTOR is the selector that was used to select TESTS."
  1134. (setq tests (ert--coerce-to-vector tests))
  1135. (let ((map (make-hash-table :size (length tests))))
  1136. (loop for i from 0
  1137. for test across tests
  1138. for key = (ert--stats-test-key test) do
  1139. (assert (not (gethash key map)))
  1140. (setf (gethash key map) i))
  1141. (make-ert--stats :selector selector
  1142. :tests tests
  1143. :test-map map
  1144. :test-results (make-vector (length tests) nil)
  1145. :test-start-times (make-vector (length tests) nil)
  1146. :test-end-times (make-vector (length tests) nil))))
  1147. (defun ert-run-or-rerun-test (stats test listener)
  1148. ;; checkdoc-order: nil
  1149. "Run the single test TEST and record the result using STATS and LISTENER."
  1150. (let ((ert--current-run-stats stats)
  1151. (pos (ert--stats-test-pos stats test)))
  1152. (ert--stats-set-test-and-result stats pos test nil)
  1153. ;; Call listener after setting/before resetting
  1154. ;; (ert--stats-current-test stats); the listener might refresh the
  1155. ;; mode line display, and if the value is not set yet/any more
  1156. ;; during this refresh, the mode line will flicker unnecessarily.
  1157. (setf (ert--stats-current-test stats) test)
  1158. (funcall listener 'test-started stats test)
  1159. (setf (ert-test-most-recent-result test) nil)
  1160. (setf (aref (ert--stats-test-start-times stats) pos) (current-time))
  1161. (unwind-protect
  1162. (ert-run-test test)
  1163. (setf (aref (ert--stats-test-end-times stats) pos) (current-time))
  1164. (let ((result (ert-test-most-recent-result test)))
  1165. (ert--stats-set-test-and-result stats pos test result)
  1166. (funcall listener 'test-ended stats test result))
  1167. (setf (ert--stats-current-test stats) nil))))
  1168. (defun ert-run-tests (selector listener)
  1169. "Run the tests specified by SELECTOR, sending progress updates to LISTENER."
  1170. (let* ((tests (ert-select-tests selector t))
  1171. (stats (ert--make-stats tests selector)))
  1172. (setf (ert--stats-start-time stats) (current-time))
  1173. (funcall listener 'run-started stats)
  1174. (let ((abortedp t))
  1175. (unwind-protect
  1176. (let ((ert--current-run-stats stats))
  1177. (force-mode-line-update)
  1178. (unwind-protect
  1179. (progn
  1180. (loop for test in tests do
  1181. (ert-run-or-rerun-test stats test listener))
  1182. (setq abortedp nil))
  1183. (setf (ert--stats-aborted-p stats) abortedp)
  1184. (setf (ert--stats-end-time stats) (current-time))
  1185. (funcall listener 'run-ended stats abortedp)))
  1186. (force-mode-line-update))
  1187. stats)))
  1188. (defun ert--stats-test-pos (stats test)
  1189. ;; checkdoc-order: nil
  1190. "Return the position (index) of TEST in the run represented by STATS."
  1191. (gethash (ert--stats-test-key test) (ert--stats-test-map stats)))
  1192. ;;; Formatting functions shared across UIs.
  1193. (defun ert--format-time-iso8601 (time)
  1194. "Format TIME in the variant of ISO 8601 used for timestamps in ERT."
  1195. (format-time-string "%Y-%m-%d %T%z" time))
  1196. (defun ert-char-for-test-result (result expectedp)
  1197. "Return a character that represents the test result RESULT.
  1198. EXPECTEDP specifies whether the result was expected."
  1199. (let ((s (etypecase result
  1200. (ert-test-passed ".P")
  1201. (ert-test-failed "fF")
  1202. (null "--")
  1203. (ert-test-aborted-with-non-local-exit "aA")
  1204. (ert-test-quit "qQ"))))
  1205. (elt s (if expectedp 0 1))))
  1206. (defun ert-string-for-test-result (result expectedp)
  1207. "Return a string that represents the test result RESULT.
  1208. EXPECTEDP specifies whether the result was expected."
  1209. (let ((s (etypecase result
  1210. (ert-test-passed '("passed" "PASSED"))
  1211. (ert-test-failed '("failed" "FAILED"))
  1212. (null '("unknown" "UNKNOWN"))
  1213. (ert-test-aborted-with-non-local-exit '("aborted" "ABORTED"))
  1214. (ert-test-quit '("quit" "QUIT")))))
  1215. (elt s (if expectedp 0 1))))
  1216. (defun ert--pp-with-indentation-and-newline (object)
  1217. "Pretty-print OBJECT, indenting it to the current column of point.
  1218. Ensures a final newline is inserted."
  1219. (let ((begin (point)))
  1220. (pp object (current-buffer))
  1221. (unless (bolp) (insert "\n"))
  1222. (save-excursion
  1223. (goto-char begin)
  1224. (indent-sexp))))
  1225. (defun ert--insert-infos (result)
  1226. "Insert `ert-info' infos from RESULT into current buffer.
  1227. RESULT must be an `ert-test-result-with-condition'."
  1228. (check-type result ert-test-result-with-condition)
  1229. (dolist (info (ert-test-result-with-condition-infos result))
  1230. (destructuring-bind (prefix . message) info
  1231. (let ((begin (point))
  1232. (indentation (make-string (+ (length prefix) 4) ?\s))
  1233. (end nil))
  1234. (unwind-protect
  1235. (progn
  1236. (insert message "\n")
  1237. (setq end (copy-marker (point)))
  1238. (goto-char begin)
  1239. (insert " " prefix)
  1240. (forward-line 1)
  1241. (while (< (point) end)
  1242. (insert indentation)
  1243. (forward-line 1)))
  1244. (when end (set-marker end nil)))))))
  1245. ;;; Running tests in batch mode.
  1246. (defvar ert-batch-backtrace-right-margin 70
  1247. "*The maximum line length for printing backtraces in `ert-run-tests-batch'.")
  1248. ;;;###autoload
  1249. (defun ert-run-tests-batch (&optional selector)
  1250. "Run the tests specified by SELECTOR, printing results to the terminal.
  1251. SELECTOR works as described in `ert-select-tests', except if
  1252. SELECTOR is nil, in which case all tests rather than none will be
  1253. run; this makes the command line \"emacs -batch -l my-tests.el -f
  1254. ert-run-tests-batch-and-exit\" useful.
  1255. Returns the stats object."
  1256. (unless selector (setq selector 't))
  1257. (ert-run-tests
  1258. selector
  1259. (lambda (event-type &rest event-args)
  1260. (ecase event-type
  1261. (run-started
  1262. (destructuring-bind (stats) event-args
  1263. (message "Running %s tests (%s)"
  1264. (length (ert--stats-tests stats))
  1265. (ert--format-time-iso8601 (ert--stats-start-time stats)))))
  1266. (run-ended
  1267. (destructuring-bind (stats abortedp) event-args
  1268. (let ((unexpected (ert-stats-completed-unexpected stats))
  1269. (expected-failures (ert--stats-failed-expected stats)))
  1270. (message "\n%sRan %s tests, %s results as expected%s (%s)%s\n"
  1271. (if (not abortedp)
  1272. ""
  1273. "Aborted: ")
  1274. (ert-stats-total stats)
  1275. (ert-stats-completed-expected stats)
  1276. (if (zerop unexpected)
  1277. ""
  1278. (format ", %s unexpected" unexpected))
  1279. (ert--format-time-iso8601 (ert--stats-end-time stats))
  1280. (if (zerop expected-failures)
  1281. ""
  1282. (format "\n%s expected failures" expected-failures)))
  1283. (unless (zerop unexpected)
  1284. (message "%s unexpected results:" unexpected)
  1285. (loop for test across (ert--stats-tests stats)
  1286. for result = (ert-test-most-recent-result test) do
  1287. (when (not (ert-test-result-expected-p test result))
  1288. (message "%9s %S"
  1289. (ert-string-for-test-result result nil)
  1290. (ert-test-name test))))
  1291. (message "%s" "")))))
  1292. (test-started
  1293. )
  1294. (test-ended
  1295. (destructuring-bind (stats test result) event-args
  1296. (unless (ert-test-result-expected-p test result)
  1297. (etypecase result
  1298. (ert-test-passed
  1299. (message "Test %S passed unexpectedly" (ert-test-name test)))
  1300. (ert-test-result-with-condition
  1301. (message "Test %S backtrace:" (ert-test-name test))
  1302. (with-temp-buffer
  1303. (ert--print-backtrace (ert-test-result-with-condition-backtrace
  1304. result))
  1305. (goto-char (point-min))
  1306. (while (not (eobp))
  1307. (let ((start (point))
  1308. (end (progn (end-of-line) (point))))
  1309. (setq end (min end
  1310. (+ start ert-batch-backtrace-right-margin)))
  1311. (message "%s" (buffer-substring-no-properties
  1312. start end)))
  1313. (forward-line 1)))
  1314. (with-temp-buffer
  1315. (ert--insert-infos result)
  1316. (insert " ")
  1317. (let ((print-escape-newlines t)
  1318. (print-level 5)
  1319. (print-length 10))
  1320. (ert--pp-with-indentation-and-newline
  1321. (ert-test-result-with-condition-condition result)))
  1322. (goto-char (1- (point-max)))
  1323. (assert (looking-at "\n"))
  1324. (delete-char 1)
  1325. (message "Test %S condition:" (ert-test-name test))
  1326. (message "%s" (buffer-string))))
  1327. (ert-test-aborted-with-non-local-exit
  1328. (message "Test %S aborted with non-local exit"
  1329. (ert-test-name test)))
  1330. (ert-test-quit
  1331. (message "Quit during %S" (ert-test-name test)))))
  1332. (let* ((max (prin1-to-string (length (ert--stats-tests stats))))
  1333. (format-string (concat "%9s %"
  1334. (prin1-to-string (length max))
  1335. "s/" max " %S")))
  1336. (message format-string
  1337. (ert-string-for-test-result result
  1338. (ert-test-result-expected-p
  1339. test result))
  1340. (1+ (ert--stats-test-pos stats test))
  1341. (ert-test-name test)))))))))
  1342. ;;;###autoload
  1343. (defun ert-run-tests-batch-and-exit (&optional selector)
  1344. "Like `ert-run-tests-batch', but exits Emacs when done.
  1345. The exit status will be 0 if all test results were as expected, 1
  1346. on unexpected results, or 2 if the tool detected an error outside
  1347. of the tests (e.g. invalid SELECTOR or bug in the code that runs
  1348. the tests)."
  1349. (unwind-protect
  1350. (let ((stats (ert-run-tests-batch selector)))
  1351. (kill-emacs (if (zerop (ert-stats-completed-unexpected stats)) 0 1)))
  1352. (unwind-protect
  1353. (progn
  1354. (message "Error running tests")
  1355. (backtrace))
  1356. (kill-emacs 2))))
  1357. ;;; Utility functions for load/unload actions.
  1358. (defun ert--activate-font-lock-keywords ()
  1359. "Activate font-lock keywords for some of ERT's symbols."
  1360. (font-lock-add-keywords
  1361. nil
  1362. '(("(\\(\\<ert-deftest\\)\\>\\s *\\(\\sw+\\)?"
  1363. (1 font-lock-keyword-face nil t)
  1364. (2 font-lock-function-name-face nil t)))))
  1365. (defun* ert--remove-from-list (list-var element &key key test)
  1366. "Remove ELEMENT from the value of LIST-VAR if present.
  1367. This can be used as an inverse of `add-to-list'."
  1368. (unless key (setq key #'identity))
  1369. (unless test (setq test #'equal))
  1370. (setf (symbol-value list-var)
  1371. (ert--remove* element
  1372. (symbol-value list-var)
  1373. :key key
  1374. :test test)))
  1375. ;;; Some basic interactive functions.
  1376. (defun ert-read-test-name (prompt &optional default history
  1377. add-default-to-prompt)
  1378. "Read the name of a test and return it as a symbol.
  1379. Prompt with PROMPT. If DEFAULT is a valid test name, use it as a
  1380. default. HISTORY is the history to use; see `completing-read'.
  1381. If ADD-DEFAULT-TO-PROMPT is non-nil, PROMPT will be modified to
  1382. include the default, if any.
  1383. Signals an error if no test name was read."
  1384. (etypecase default
  1385. (string (let ((symbol (intern-soft default)))
  1386. (unless (and symbol (ert-test-boundp symbol))
  1387. (setq default nil))))
  1388. (symbol (setq default
  1389. (if (ert-test-boundp default)
  1390. (symbol-name default)
  1391. nil)))
  1392. (ert-test (setq default (ert-test-name default))))
  1393. (when add-default-to-prompt
  1394. (setq prompt (if (null default)
  1395. (format "%s: " prompt)
  1396. (format "%s (default %s): " prompt default))))
  1397. (let ((input (completing-read prompt obarray #'ert-test-boundp
  1398. t nil history default nil)))
  1399. ;; completing-read returns an empty string if default was nil and
  1400. ;; the user just hit enter.
  1401. (let ((sym (intern-soft input)))
  1402. (if (ert-test-boundp sym)
  1403. sym
  1404. (error "Input does not name a test")))))
  1405. (defun ert-read-test-name-at-point (prompt)
  1406. "Read the name of a test and return it as a symbol.
  1407. As a default, use the symbol at point, or the test at point if in
  1408. the ERT results buffer. Prompt with PROMPT, augmented with the
  1409. default (if any)."
  1410. (ert-read-test-name prompt (ert-test-at-point) nil t))
  1411. (defun ert-find-test-other-window (test-name)
  1412. "Find, in another window, the definition of TEST-NAME."
  1413. (interactive (list (ert-read-test-name-at-point "Find test definition: ")))
  1414. (find-function-do-it test-name 'ert-deftest 'switch-to-buffer-other-window))
  1415. (defun ert-delete-test (test-name)
  1416. "Make the test TEST-NAME unbound.
  1417. Nothing more than an interactive interface to `ert-make-test-unbound'."
  1418. (interactive (list (ert-read-test-name-at-point "Delete test")))
  1419. (ert-make-test-unbound test-name))
  1420. (defun ert-delete-all-tests ()
  1421. "Make all symbols in `obarray' name no test."
  1422. (interactive)
  1423. (when (called-interactively-p 'any)
  1424. (unless (y-or-n-p "Delete all tests? ")
  1425. (error "Aborted")))
  1426. ;; We can't use `ert-select-tests' here since that gives us only
  1427. ;; test objects, and going from them back to the test name symbols
  1428. ;; can fail if the `ert-test' defstruct has been redefined.
  1429. (mapc #'ert-make-test-unbound (apropos-internal "" #'ert-test-boundp))
  1430. t)
  1431. ;;; Display of test progress and results.
  1432. ;; An entry in the results buffer ewoc. There is one entry per test.
  1433. (defstruct ert--ewoc-entry
  1434. (test (assert nil))
  1435. ;; If the result of this test was expected, its ewoc entry is hidden
  1436. ;; initially.
  1437. (hidden-p (assert nil))
  1438. ;; An ewoc entry may be collapsed to hide details such as the error
  1439. ;; condition.
  1440. ;;
  1441. ;; I'm not sure the ability to expand and collapse entries is still
  1442. ;; a useful feature.
  1443. (expanded-p t)
  1444. ;; By default, the ewoc entry presents the error condition with
  1445. ;; certain limits on how much to print (`print-level',
  1446. ;; `print-length'). The user can interactively switch to a set of
  1447. ;; higher limits.
  1448. (extended-printer-limits-p nil))
  1449. ;; Variables local to the results buffer.
  1450. ;; The ewoc.
  1451. (defvar ert--results-ewoc)
  1452. ;; The stats object.
  1453. (defvar ert--results-stats)
  1454. ;; A string with one character per test. Each character represents
  1455. ;; the result of the corresponding test. The string is displayed near
  1456. ;; the top of the buffer and serves as a progress bar.
  1457. (defvar ert--results-progress-bar-string)
  1458. ;; The position where the progress bar button begins.
  1459. (defvar ert--results-progress-bar-button-begin)
  1460. ;; The test result listener that updates the buffer when tests are run.
  1461. (defvar ert--results-listener)
  1462. (defun ert-insert-test-name-button (test-name)
  1463. "Insert a button that links to TEST-NAME."
  1464. (insert-text-button (format "%S" test-name)
  1465. :type 'ert--test-name-button
  1466. 'ert-test-name test-name))
  1467. (defun ert--results-format-expected-unexpected (expected unexpected)
  1468. "Return a string indicating EXPECTED expected results, UNEXPECTED unexpected."
  1469. (if (zerop unexpected)
  1470. (format "%s" expected)
  1471. (format "%s (%s unexpected)" (+ expected unexpected) unexpected)))
  1472. (defun ert--results-update-ewoc-hf (ewoc stats)
  1473. "Update the header and footer of EWOC to show certain information from STATS.
  1474. Also sets `ert--results-progress-bar-button-begin'."
  1475. (let ((run-count (ert-stats-completed stats))
  1476. (results-buffer (current-buffer))
  1477. ;; Need to save buffer-local value.
  1478. (font-lock font-lock-mode))
  1479. (ewoc-set-hf
  1480. ewoc
  1481. ;; header
  1482. (with-temp-buffer
  1483. (insert "Selector: ")
  1484. (ert--insert-human-readable-selector (ert--stats-selector stats))
  1485. (insert "\n")
  1486. (insert
  1487. (format (concat "Passed: %s\n"
  1488. "Failed: %s\n"
  1489. "Total: %s/%s\n\n")
  1490. (ert--results-format-expected-unexpected
  1491. (ert--stats-passed-expected stats)
  1492. (ert--stats-passed-unexpected stats))
  1493. (ert--results-format-expected-unexpected
  1494. (ert--stats-failed-expected stats)
  1495. (ert--stats-failed-unexpected stats))
  1496. run-count
  1497. (ert-stats-total stats)))
  1498. (insert
  1499. (format "Started at: %s\n"
  1500. (ert--format-time-iso8601 (ert--stats-start-time stats))))
  1501. ;; FIXME: This is ugly. Need to properly define invariants of
  1502. ;; the `stats' data structure.
  1503. (let ((state (cond ((ert--stats-aborted-p stats) 'aborted)
  1504. ((ert--stats-current-test stats) 'running)
  1505. ((ert--stats-end-time stats) 'finished)
  1506. (t 'preparing))))
  1507. (ecase state
  1508. (preparing
  1509. (insert ""))
  1510. (aborted
  1511. (cond ((ert--stats-current-test stats)
  1512. (insert "Aborted during test: ")
  1513. (ert-insert-test-name-button
  1514. (ert-test-name (ert--stats-current-test stats))))
  1515. (t
  1516. (insert "Aborted."))))
  1517. (running
  1518. (assert (ert--stats-current-test stats))
  1519. (insert "Running test: ")
  1520. (ert-insert-test-name-button (ert-test-name
  1521. (ert--stats-current-test stats))))
  1522. (finished
  1523. (assert (not (ert--stats-current-test stats)))
  1524. (insert "Finished.")))
  1525. (insert "\n")
  1526. (if (ert--stats-end-time stats)
  1527. (insert
  1528. (format "%s%s\n"
  1529. (if (ert--stats-aborted-p stats)
  1530. "Aborted at: "
  1531. "Finished at: ")
  1532. (ert--format-time-iso8601 (ert--stats-end-time stats))))
  1533. (insert "\n"))
  1534. (insert "\n"))
  1535. (let ((progress-bar-string (with-current-buffer results-buffer
  1536. ert--results-progress-bar-string)))
  1537. (let ((progress-bar-button-begin
  1538. (insert-text-button progress-bar-string
  1539. :type 'ert--results-progress-bar-button
  1540. 'face (or (and font-lock
  1541. (ert-face-for-stats stats))
  1542. 'button))))
  1543. ;; The header gets copied verbatim to the results buffer,
  1544. ;; and all positions remain the same, so
  1545. ;; `progress-bar-button-begin' will be the right position
  1546. ;; even in the results buffer.
  1547. (with-current-buffer results-buffer
  1548. (set (make-local-variable 'ert--results-progress-bar-button-begin)
  1549. progress-bar-button-begin))))
  1550. (insert "\n\n")
  1551. (buffer-string))
  1552. ;; footer
  1553. ;;
  1554. ;; We actually want an empty footer, but that would trigger a bug
  1555. ;; in ewoc, sometimes clearing the entire buffer. (It's possible
  1556. ;; that this bug has been fixed since this has been tested; we
  1557. ;; should test it again.)
  1558. "\n")))
  1559. (defvar ert-test-run-redisplay-interval-secs .1
  1560. "How many seconds ERT should wait between redisplays while running tests.
  1561. While running tests, ERT shows the current progress, and this variable
  1562. determines how frequently the progress display is updated.")
  1563. (defun ert--results-update-stats-display (ewoc stats)
  1564. "Update EWOC and the mode line to show data from STATS."
  1565. ;; TODO(ohler): investigate using `make-progress-reporter'.
  1566. (ert--results-update-ewoc-hf ewoc stats)
  1567. (force-mode-line-update)
  1568. (redisplay t)
  1569. (setf (ert--stats-next-redisplay stats)
  1570. (+ (float-time) ert-test-run-redisplay-interval-secs)))
  1571. (defun ert--results-update-stats-display-maybe (ewoc stats)
  1572. "Call `ert--results-update-stats-display' if not called recently.
  1573. EWOC and STATS are arguments for `ert--results-update-stats-display'."
  1574. (when (>= (float-time) (ert--stats-next-redisplay stats))
  1575. (ert--results-update-stats-display ewoc stats)))
  1576. (defun ert--tests-running-mode-line-indicator ()
  1577. "Return a string for the mode line that shows the test run progress."
  1578. (let* ((stats ert--current-run-stats)
  1579. (tests-total (ert-stats-total stats))
  1580. (tests-completed (ert-stats-completed stats)))
  1581. (if (>= tests-completed tests-total)
  1582. (format " ERT(%s/%s,finished)" tests-completed tests-total)
  1583. (format " ERT(%s/%s):%s"
  1584. (1+ tests-completed)
  1585. tests-total
  1586. (if (null (ert--stats-current-test stats))
  1587. "?"
  1588. (format "%S"
  1589. (ert-test-name (ert--stats-current-test stats))))))))
  1590. (defun ert--make-xrefs-region (begin end)
  1591. "Attach cross-references to function names between BEGIN and END.
  1592. BEGIN and END specify a region in the current buffer."
  1593. (save-excursion
  1594. (save-restriction
  1595. (narrow-to-region begin end)
  1596. ;; Inhibit optimization in `debugger-make-xrefs' that would
  1597. ;; sometimes insert unrelated backtrace info into our buffer.
  1598. (let ((debugger-previous-backtrace nil))
  1599. (debugger-make-xrefs)))))
  1600. (defun ert--string-first-line (s)
  1601. "Return the first line of S, or S if it contains no newlines.
  1602. The return value does not include the line terminator."
  1603. (substring s 0 (ert--string-position ?\n s)))
  1604. (defun ert-face-for-test-result (expectedp)
  1605. "Return a face that shows whether a test result was expected or unexpected.
  1606. If EXPECTEDP is nil, returns the face for unexpected results; if
  1607. non-nil, returns the face for expected results.."
  1608. (if expectedp 'ert-test-result-expected 'ert-test-result-unexpected))
  1609. (defun ert-face-for-stats (stats)
  1610. "Return a face that represents STATS."
  1611. (cond ((ert--stats-aborted-p stats) 'nil)
  1612. ((plusp (ert-stats-completed-unexpected stats))
  1613. (ert-face-for-test-result nil))
  1614. ((eql (ert-stats-completed-expected stats) (ert-stats-total stats))
  1615. (ert-face-for-test-result t))
  1616. (t 'nil)))
  1617. (defun ert--print-test-for-ewoc (entry)
  1618. "The ewoc print function for ewoc test entries. ENTRY is the entry to print."
  1619. (let* ((test (ert--ewoc-entry-test entry))
  1620. (stats ert--results-stats)
  1621. (result (let ((pos (ert--stats-test-pos stats test)))
  1622. (assert pos)
  1623. (aref (ert--stats-test-results stats) pos)))
  1624. (hiddenp (ert--ewoc-entry-hidden-p entry))
  1625. (expandedp (ert--ewoc-entry-expanded-p entry))
  1626. (extended-printer-limits-p (ert--ewoc-entry-extended-printer-limits-p
  1627. entry)))
  1628. (cond (hiddenp)
  1629. (t
  1630. (let ((expectedp (ert-test-result-expected-p test result)))
  1631. (insert-text-button (format "%c" (ert-char-for-test-result
  1632. result expectedp))
  1633. :type 'ert--results-expand-collapse-button
  1634. 'face (or (and font-lock-mode
  1635. (ert-face-for-test-result
  1636. expectedp))
  1637. 'button)))
  1638. (insert " ")
  1639. (ert-insert-test-name-button (ert-test-name test))
  1640. (insert "\n")
  1641. (when (and expandedp (not (eql result 'nil)))
  1642. (when (ert-test-documentation test)
  1643. (insert " "
  1644. (propertize
  1645. (ert--string-first-line (ert-test-documentation test))
  1646. 'font-lock-face 'font-lock-doc-face)
  1647. "\n"))
  1648. (etypecase result
  1649. (ert-test-passed
  1650. (if (ert-test-result-expected-p test result)
  1651. (insert " passed\n")
  1652. (insert " passed unexpectedly\n"))
  1653. (insert ""))
  1654. (ert-test-result-with-condition
  1655. (ert--insert-infos result)
  1656. (let ((print-escape-newlines t)
  1657. (print-level (if extended-printer-limits-p 12 6))
  1658. (print-length (if extended-printer-limits-p 100 10)))
  1659. (insert " ")
  1660. (let ((begin (point)))
  1661. (ert--pp-with-indentation-and-newline
  1662. (ert-test-result-with-condition-condition result))
  1663. (ert--make-xrefs-region begin (point)))))
  1664. (ert-test-aborted-with-non-local-exit
  1665. (insert " aborted\n"))
  1666. (ert-test-quit
  1667. (insert " quit\n")))
  1668. (insert "\n")))))
  1669. nil)
  1670. (defun ert--results-font-lock-function (enabledp)
  1671. "Redraw the ERT results buffer after font-lock-mode was switched on or off.
  1672. ENABLEDP is true if font-lock-mode is switched on, false
  1673. otherwise."
  1674. (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
  1675. (ewoc-refresh ert--results-ewoc)
  1676. (font-lock-default-function enabledp))
  1677. (defun ert--setup-results-buffer (stats listener buffer-name)
  1678. "Set up a test results buffer.
  1679. STATS is the stats object; LISTENER is the results listener;
  1680. BUFFER-NAME, if non-nil, is the buffer name to use."
  1681. (unless buffer-name (setq buffer-name "*ert*"))
  1682. (let ((buffer (get-buffer-create buffer-name)))
  1683. (with-current-buffer buffer
  1684. (let ((inhibit-read-only t))
  1685. (buffer-disable-undo)
  1686. (erase-buffer)
  1687. (ert-results-mode)
  1688. ;; Erase buffer again in case switching out of the previous
  1689. ;; mode inserted anything. (This happens e.g. when switching
  1690. ;; from ert-results-mode to ert-results-mode when
  1691. ;; font-lock-mode turns itself off in change-major-mode-hook.)
  1692. (erase-buffer)
  1693. (set (make-local-variable 'font-lock-function)
  1694. 'ert--results-font-lock-function)
  1695. (let ((ewoc (ewoc-create 'ert--print-test-for-ewoc nil nil t)))
  1696. (set (make-local-variable 'ert--results-ewoc) ewoc)
  1697. (set (make-local-variable 'ert--results-stats) stats)
  1698. (set (make-local-variable 'ert--results-progress-bar-string)
  1699. (make-string (ert-stats-total stats)
  1700. (ert-char-for-test-result nil t)))
  1701. (set (make-local-variable 'ert--results-listener) listener)
  1702. (loop for test across (ert--stats-tests stats) do
  1703. (ewoc-enter-last ewoc
  1704. (make-ert--ewoc-entry :test test :hidden-p t)))
  1705. (ert--results-update-ewoc-hf ert--results-ewoc ert--results-stats)
  1706. (goto-char (1- (point-max)))
  1707. buffer)))))
  1708. (defvar ert--selector-history nil
  1709. "List of recent test selectors read from terminal.")
  1710. ;; Should OUTPUT-BUFFER-NAME and MESSAGE-FN really be arguments here?
  1711. ;; They are needed only for our automated self-tests at the moment.
  1712. ;; Or should there be some other mechanism?
  1713. ;;;###autoload
  1714. (defun ert-run-tests-interactively (selector
  1715. &optional output-buffer-name message-fn)
  1716. "Run the tests specified by SELECTOR and display the results in a buffer.
  1717. SELECTOR works as described in `ert-select-tests'.
  1718. OUTPUT-BUFFER-NAME and MESSAGE-FN should normally be nil; they
  1719. are used for automated self-tests and specify which buffer to use
  1720. and how to display message."
  1721. (interactive
  1722. (list (let ((default (if ert--selector-history
  1723. ;; Can't use `first' here as this form is
  1724. ;; not compiled, and `first' is not
  1725. ;; defined without cl.
  1726. (car ert--selector-history)
  1727. "t")))
  1728. (read-from-minibuffer (if (null default)
  1729. "Run tests: "
  1730. (format "Run tests (default %s): " default))
  1731. nil nil t 'ert--selector-history
  1732. default nil))
  1733. nil))
  1734. (unless message-fn (setq message-fn 'message))
  1735. (lexical-let ((output-buffer-name output-buffer-name)
  1736. buffer
  1737. listener
  1738. (message-fn message-fn))
  1739. (setq listener
  1740. (lambda (event-type &rest event-args)
  1741. (ecase event-type
  1742. (run-started
  1743. (destructuring-bind (stats) event-args
  1744. (setq buffer (ert--setup-results-buffer stats
  1745. listener
  1746. output-buffer-name))
  1747. (pop-to-buffer buffer)))
  1748. (run-ended
  1749. (destructuring-bind (stats abortedp) event-args
  1750. (funcall message-fn
  1751. "%sRan %s tests, %s results were as expected%s"
  1752. (if (not abortedp)
  1753. ""
  1754. "Aborted: ")
  1755. (ert-stats-total stats)
  1756. (ert-stats-completed-expected stats)
  1757. (let ((unexpected
  1758. (ert-stats-completed-unexpected stats)))
  1759. (if (zerop unexpected)
  1760. ""
  1761. (format ", %s unexpected" unexpected))))
  1762. (ert--results-update-stats-display (with-current-buffer buffer
  1763. ert--results-ewoc)
  1764. stats)))
  1765. (test-started
  1766. (destructuring-bind (stats test) event-args
  1767. (with-current-buffer buffer
  1768. (let* ((ewoc ert--results-ewoc)
  1769. (pos (ert--stats-test-pos stats test))
  1770. (node (ewoc-nth ewoc pos)))
  1771. (assert node)
  1772. (setf (ert--ewoc-entry-test (ewoc-data node)) test)
  1773. (aset ert--results-progress-bar-string pos
  1774. (ert-char-for-test-result nil t))
  1775. (ert--results-update-stats-display-maybe ewoc stats)
  1776. (ewoc-invalidate ewoc node)))))
  1777. (test-ended
  1778. (destructuring-bind (stats test result) event-args
  1779. (with-current-buffer buffer
  1780. (let* ((ewoc ert--results-ewoc)
  1781. (pos (ert--stats-test-pos stats test))
  1782. (node (ewoc-nth ewoc pos)))
  1783. (when (ert--ewoc-entry-hidden-p (ewoc-data node))
  1784. (setf (ert--ewoc-entry-hidden-p (ewoc-data node))
  1785. (ert-test-result-expected-p test result)))
  1786. (aset ert--results-progress-bar-string pos
  1787. (ert-char-for-test-result result
  1788. (ert-test-result-expected-p
  1789. test result)))
  1790. (ert--results-update-stats-display-maybe ewoc stats)
  1791. (ewoc-invalidate ewoc node))))))))
  1792. (ert-run-tests
  1793. selector
  1794. listener)))
  1795. ;;;###autoload
  1796. (defalias 'ert 'ert-run-tests-interactively)
  1797. ;;; Simple view mode for auxiliary information like stack traces or
  1798. ;;; messages. Mainly binds "q" for quit.
  1799. (define-derived-mode ert-simple-view-mode special-mode "ERT-View"
  1800. "Major mode for viewing auxiliary information in ERT.")
  1801. ;;; Commands and button actions for the results buffer.
  1802. (define-derived-mode ert-results-mode special-mode "ERT-Results"
  1803. "Major mode for viewing results of ERT test runs.")
  1804. (loop for (key binding) in
  1805. '(;; Stuff that's not in the menu.
  1806. ("\t" forward-button)
  1807. ([backtab] backward-button)
  1808. ("j" ert-results-jump-between-summary-and-result)
  1809. ("L" ert-results-toggle-printer-limits-for-test-at-point)
  1810. ("n" ert-results-next-test)
  1811. ("p" ert-results-previous-test)
  1812. ;; Stuff that is in the menu.
  1813. ("R" ert-results-rerun-all-tests)
  1814. ("r" ert-results-rerun-test-at-point)
  1815. ("d" ert-results-rerun-test-at-point-debugging-errors)
  1816. ("." ert-results-find-test-at-point-other-window)
  1817. ("b" ert-results-pop-to-backtrace-for-test-at-point)
  1818. ("m" ert-results-pop-to-messages-for-test-at-point)
  1819. ("l" ert-results-pop-to-should-forms-for-test-at-point)
  1820. ("h" ert-results-describe-test-at-point)
  1821. ("D" ert-delete-test)
  1822. ("T" ert-results-pop-to-timings)
  1823. )
  1824. do
  1825. (define-key ert-results-mode-map key binding))
  1826. (easy-menu-define ert-results-mode-menu ert-results-mode-map
  1827. "Menu for `ert-results-mode'."
  1828. '("ERT Results"
  1829. ["Re-run all tests" ert-results-rerun-all-tests]
  1830. "--"
  1831. ["Re-run test" ert-results-rerun-test-at-point]
  1832. ["Debug test" ert-results-rerun-test-at-point-debugging-errors]
  1833. ["Show test definition" ert-results-find-test-at-point-other-window]
  1834. "--"
  1835. ["Show backtrace" ert-results-pop-to-backtrace-for-test-at-point]
  1836. ["Show messages" ert-results-pop-to-messages-for-test-at-point]
  1837. ["Show `should' forms" ert-results-pop-to-should-forms-for-test-at-point]
  1838. ["Describe test" ert-results-describe-test-at-point]
  1839. "--"
  1840. ["Delete test" ert-delete-test]
  1841. "--"
  1842. ["Show execution time of each test" ert-results-pop-to-timings]
  1843. ))
  1844. (define-button-type 'ert--results-progress-bar-button
  1845. 'action #'ert--results-progress-bar-button-action
  1846. 'help-echo "mouse-2, RET: Reveal test result")
  1847. (define-button-type 'ert--test-name-button
  1848. 'action #'ert--test-name-button-action
  1849. 'help-echo "mouse-2, RET: Find test definition")
  1850. (define-button-type 'ert--results-expand-collapse-button
  1851. 'action #'ert--results-expand-collapse-button-action
  1852. 'help-echo "mouse-2, RET: Expand/collapse test result")
  1853. (defun ert--results-test-node-or-null-at-point ()
  1854. "If point is on a valid ewoc node, return it; return nil otherwise.
  1855. To be used in the ERT results buffer."
  1856. (let* ((ewoc ert--results-ewoc)
  1857. (node (ewoc-locate ewoc)))
  1858. ;; `ewoc-locate' will return an arbitrary node when point is on
  1859. ;; header or footer, or when all nodes are invisible. So we need
  1860. ;; to validate its return value here.
  1861. ;;
  1862. ;; Update: I'm seeing nil being returned in some cases now,
  1863. ;; perhaps this has been changed?
  1864. (if (and node
  1865. (>= (point) (ewoc-location node))
  1866. (not (ert--ewoc-entry-hidden-p (ewoc-data node))))
  1867. node
  1868. nil)))
  1869. (defun ert--results-test-node-at-point ()
  1870. "If point is on a valid ewoc node, return it; signal an error otherwise.
  1871. To be used in the ERT results buffer."
  1872. (or (ert--results-test-node-or-null-at-point)
  1873. (error "No test at point")))
  1874. (defun ert-results-next-test ()
  1875. "Move point to the next test.
  1876. To be used in the ERT results buffer."
  1877. (interactive)
  1878. (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-next
  1879. "No tests below"))
  1880. (defun ert-results-previous-test ()
  1881. "Move point to the previous test.
  1882. To be used in the ERT results buffer."
  1883. (interactive)
  1884. (ert--results-move (ewoc-locate ert--results-ewoc) 'ewoc-prev
  1885. "No tests above"))
  1886. (defun ert--results-move (node ewoc-fn error-message)
  1887. "Move point from NODE to the previous or next node.
  1888. EWOC-FN specifies the direction and should be either `ewoc-prev'
  1889. or `ewoc-next'. If there are no more nodes in that direction, an
  1890. error is signaled with the message ERROR-MESSAGE."
  1891. (loop
  1892. (setq node (funcall ewoc-fn ert--results-ewoc node))
  1893. (when (null node)
  1894. (error "%s" error-message))
  1895. (unless (ert--ewoc-entry-hidden-p (ewoc-data node))
  1896. (goto-char (ewoc-location node))
  1897. (return))))
  1898. (defun ert--results-expand-collapse-button-action (button)
  1899. "Expand or collapse the test node BUTTON belongs to."
  1900. (let* ((ewoc ert--results-ewoc)
  1901. (node (save-excursion
  1902. (goto-char (ert--button-action-position))
  1903. (ert--results-test-node-at-point)))
  1904. (entry (ewoc-data node)))
  1905. (setf (ert--ewoc-entry-expanded-p entry)
  1906. (not (ert--ewoc-entry-expanded-p entry)))
  1907. (ewoc-invalidate ewoc node)))
  1908. (defun ert-results-find-test-at-point-other-window ()
  1909. "Find the definition of the test at point in another window.
  1910. To be used in the ERT results buffer."
  1911. (interactive)
  1912. (let ((name (ert-test-at-point)))
  1913. (unless name
  1914. (error "No test at point"))
  1915. (ert-find-test-other-window name)))
  1916. (defun ert--test-name-button-action (button)
  1917. "Find the definition of the test BUTTON belongs to, in another window."
  1918. (let ((name (button-get button 'ert-test-name)))
  1919. (ert-find-test-other-window name)))
  1920. (defun ert--ewoc-position (ewoc node)
  1921. ;; checkdoc-order: nil
  1922. "Return the position of NODE in EWOC, or nil if NODE is not in EWOC."
  1923. (loop for i from 0
  1924. for node-here = (ewoc-nth ewoc 0) then (ewoc-next ewoc node-here)
  1925. do (when (eql node node-here)
  1926. (return i))
  1927. finally (return nil)))
  1928. (defun ert-results-jump-between-summary-and-result ()
  1929. "Jump back and forth between the test run summary and individual test results.
  1930. From an ewoc node, jumps to the character that represents the
  1931. same test in the progress bar, and vice versa.
  1932. To be used in the ERT results buffer."
  1933. ;; Maybe this command isn't actually needed much, but if it is, it
  1934. ;; seems like an indication that the UI design is not optimal. If
  1935. ;; jumping back and forth between a summary at the top of the buffer
  1936. ;; and the error log in the remainder of the buffer is useful, then
  1937. ;; the summary apparently needs to be easily accessible from the
  1938. ;; error log, and perhaps it would be better to have it in a
  1939. ;; separate buffer to keep it visible.
  1940. (interactive)
  1941. (let ((ewoc ert--results-ewoc)
  1942. (progress-bar-begin ert--results-progress-bar-button-begin))
  1943. (cond ((ert--results-test-node-or-null-at-point)
  1944. (let* ((node (ert--results-test-node-at-point))
  1945. (pos (ert--ewoc-position ewoc node)))
  1946. (goto-char (+ progress-bar-begin pos))))
  1947. ((and (<= progress-bar-begin (point))
  1948. (< (point) (button-end (button-at progress-bar-begin))))
  1949. (let* ((node (ewoc-nth ewoc (- (point) progress-bar-begin)))
  1950. (entry (ewoc-data node)))
  1951. (when (ert--ewoc-entry-hidden-p entry)
  1952. (setf (ert--ewoc-entry-hidden-p entry) nil)
  1953. (ewoc-invalidate ewoc node))
  1954. (ewoc-goto-node ewoc node)))
  1955. (t
  1956. (goto-char progress-bar-begin)))))
  1957. (defun ert-test-at-point ()
  1958. "Return the name of the test at point as a symbol, or nil if none."
  1959. (or (and (eql major-mode 'ert-results-mode)
  1960. (let ((test (ert--results-test-at-point-no-redefinition)))
  1961. (and test (ert-test-name test))))
  1962. (let* ((thing (thing-at-point 'symbol))
  1963. (sym (intern-soft thing)))
  1964. (and (ert-test-boundp sym)
  1965. sym))))
  1966. (defun ert--results-test-at-point-no-redefinition ()
  1967. "Return the test at point, or nil.
  1968. To be used in the ERT results buffer."
  1969. (assert (eql major-mode 'ert-results-mode))
  1970. (if (ert--results-test-node-or-null-at-point)
  1971. (let* ((node (ert--results-test-node-at-point))
  1972. (test (ert--ewoc-entry-test (ewoc-data node))))
  1973. test)
  1974. (let ((progress-bar-begin ert--results-progress-bar-button-begin))
  1975. (when (and (<= progress-bar-begin (point))
  1976. (< (point) (button-end (button-at progress-bar-begin))))
  1977. (let* ((test-index (- (point) progress-bar-begin))
  1978. (test (aref (ert--stats-tests ert--results-stats)
  1979. test-index)))
  1980. test)))))
  1981. (defun ert--results-test-at-point-allow-redefinition ()
  1982. "Look up the test at point, and check whether it has been redefined.
  1983. To be used in the ERT results buffer.
  1984. Returns a list of two elements: the test (or nil) and a symbol
  1985. specifying whether the test has been redefined.
  1986. If a new test has been defined with the same name as the test at
  1987. point, replaces the test at point with the new test, and returns
  1988. the new test and the symbol `redefined'.
  1989. If the test has been deleted, returns the old test and the symbol
  1990. `deleted'.
  1991. If the test is still current, returns the test and the symbol nil.
  1992. If there is no test at point, returns a list with two nils."
  1993. (let ((test (ert--results-test-at-point-no-redefinition)))
  1994. (cond ((null test)
  1995. `(nil nil))
  1996. ((null (ert-test-name test))
  1997. `(,test nil))
  1998. (t
  1999. (let* ((name (ert-test-name test))
  2000. (new-test (and (ert-test-boundp name)
  2001. (ert-get-test name))))
  2002. (cond ((eql test new-test)
  2003. `(,test nil))
  2004. ((null new-test)
  2005. `(,test deleted))
  2006. (t
  2007. (ert--results-update-after-test-redefinition
  2008. (ert--stats-test-pos ert--results-stats test)
  2009. new-test)
  2010. `(,new-test redefined))))))))
  2011. (defun ert--results-update-after-test-redefinition (pos new-test)
  2012. "Update results buffer after the test at pos POS has been redefined.
  2013. Also updates the stats object. NEW-TEST is the new test
  2014. definition."
  2015. (let* ((stats ert--results-stats)
  2016. (ewoc ert--results-ewoc)
  2017. (node (ewoc-nth ewoc pos))
  2018. (entry (ewoc-data node)))
  2019. (ert--stats-set-test-and-result stats pos new-test nil)
  2020. (setf (ert--ewoc-entry-test entry) new-test
  2021. (aref ert--results-progress-bar-string pos) (ert-char-for-test-result
  2022. nil t))
  2023. (ewoc-invalidate ewoc node))
  2024. nil)
  2025. (defun ert--button-action-position ()
  2026. "The buffer position where the last button action was triggered."
  2027. (cond ((integerp last-command-event)
  2028. (point))
  2029. ((eventp last-command-event)
  2030. (posn-point (event-start last-command-event)))
  2031. (t (assert nil))))
  2032. (defun ert--results-progress-bar-button-action (button)
  2033. "Jump to details for the test represented by the character clicked in BUTTON."
  2034. (goto-char (ert--button-action-position))
  2035. (ert-results-jump-between-summary-and-result))
  2036. (defun ert-results-rerun-all-tests ()
  2037. "Re-run all tests, using the same selector.
  2038. To be used in the ERT results buffer."
  2039. (interactive)
  2040. (assert (eql major-mode 'ert-results-mode))
  2041. (let ((selector (ert--stats-selector ert--results-stats)))
  2042. (ert-run-tests-interactively selector (buffer-name))))
  2043. (defun ert-results-rerun-test-at-point ()
  2044. "Re-run the test at point.
  2045. To be used in the ERT results buffer."
  2046. (interactive)
  2047. (destructuring-bind (test redefinition-state)
  2048. (ert--results-test-at-point-allow-redefinition)
  2049. (when (null test)
  2050. (error "No test at point"))
  2051. (let* ((stats ert--results-stats)
  2052. (progress-message (format "Running %stest %S"
  2053. (ecase redefinition-state
  2054. ((nil) "")
  2055. (redefined "new definition of ")
  2056. (deleted "deleted "))
  2057. (ert-test-name test))))
  2058. ;; Need to save and restore point manually here: When point is on
  2059. ;; the first visible ewoc entry while the header is updated, point
  2060. ;; moves to the top of the buffer. This is undesirable, and a
  2061. ;; simple `save-excursion' doesn't prevent it.
  2062. (let ((point (point)))
  2063. (unwind-protect
  2064. (unwind-protect
  2065. (progn
  2066. (message "%s..." progress-message)
  2067. (ert-run-or-rerun-test stats test
  2068. ert--results-listener))
  2069. (ert--results-update-stats-display ert--results-ewoc stats)
  2070. (message "%s...%s"
  2071. progress-message
  2072. (let ((result (ert-test-most-recent-result test)))
  2073. (ert-string-for-test-result
  2074. result (ert-test-result-expected-p test result)))))
  2075. (goto-char point))))))
  2076. (defun ert-results-rerun-test-at-point-debugging-errors ()
  2077. "Re-run the test at point with `ert-debug-on-error' bound to t.
  2078. To be used in the ERT results buffer."
  2079. (interactive)
  2080. (let ((ert-debug-on-error t))
  2081. (ert-results-rerun-test-at-point)))
  2082. (defun ert-results-pop-to-backtrace-for-test-at-point ()
  2083. "Display the backtrace for the test at point.
  2084. To be used in the ERT results buffer."
  2085. (interactive)
  2086. (let* ((test (ert--results-test-at-point-no-redefinition))
  2087. (stats ert--results-stats)
  2088. (pos (ert--stats-test-pos stats test))
  2089. (result (aref (ert--stats-test-results stats) pos)))
  2090. (etypecase result
  2091. (ert-test-passed (error "Test passed, no backtrace available"))
  2092. (ert-test-result-with-condition
  2093. (let ((backtrace (ert-test-result-with-condition-backtrace result))
  2094. (buffer (get-buffer-create "*ERT Backtrace*")))
  2095. (pop-to-buffer buffer)
  2096. (let ((inhibit-read-only t))
  2097. (buffer-disable-undo)
  2098. (erase-buffer)
  2099. (ert-simple-view-mode)
  2100. ;; Use unibyte because `debugger-setup-buffer' also does so.
  2101. (set-buffer-multibyte nil)
  2102. (setq truncate-lines t)
  2103. (ert--print-backtrace backtrace)
  2104. (debugger-make-xrefs)
  2105. (goto-char (point-min))
  2106. (insert "Backtrace for test `")
  2107. (ert-insert-test-name-button (ert-test-name test))
  2108. (insert "':\n")))))))
  2109. (defun ert-results-pop-to-messages-for-test-at-point ()
  2110. "Display the part of the *Messages* buffer generated during the test at point.
  2111. To be used in the ERT results buffer."
  2112. (interactive)
  2113. (let* ((test (ert--results-test-at-point-no-redefinition))
  2114. (stats ert--results-stats)
  2115. (pos (ert--stats-test-pos stats test))
  2116. (result (aref (ert--stats-test-results stats) pos)))
  2117. (let ((buffer (get-buffer-create "*ERT Messages*")))
  2118. (pop-to-buffer buffer)
  2119. (let ((inhibit-read-only t))
  2120. (buffer-disable-undo)
  2121. (erase-buffer)
  2122. (ert-simple-view-mode)
  2123. (insert (ert-test-result-messages result))
  2124. (goto-char (point-min))
  2125. (insert "Messages for test `")
  2126. (ert-insert-test-name-button (ert-test-name test))
  2127. (insert "':\n")))))
  2128. (defun ert-results-pop-to-should-forms-for-test-at-point ()
  2129. "Display the list of `should' forms executed during the test at point.
  2130. To be used in the ERT results buffer."
  2131. (interactive)
  2132. (let* ((test (ert--results-test-at-point-no-redefinition))
  2133. (stats ert--results-stats)
  2134. (pos (ert--stats-test-pos stats test))
  2135. (result (aref (ert--stats-test-results stats) pos)))
  2136. (let ((buffer (get-buffer-create "*ERT list of should forms*")))
  2137. (pop-to-buffer buffer)
  2138. (let ((inhibit-read-only t))
  2139. (buffer-disable-undo)
  2140. (erase-buffer)
  2141. (ert-simple-view-mode)
  2142. (if (null (ert-test-result-should-forms result))
  2143. (insert "\n(No should forms during this test.)\n")
  2144. (loop for form-description in (ert-test-result-should-forms result)
  2145. for i from 1 do
  2146. (insert "\n")
  2147. (insert (format "%s: " i))
  2148. (let ((begin (point)))
  2149. (ert--pp-with-indentation-and-newline form-description)
  2150. (ert--make-xrefs-region begin (point)))))
  2151. (goto-char (point-min))
  2152. (insert "`should' forms executed during test `")
  2153. (ert-insert-test-name-button (ert-test-name test))
  2154. (insert "':\n")
  2155. (insert "\n")
  2156. (insert (concat "(Values are shallow copies and may have "
  2157. "looked different during the test if they\n"
  2158. "have been modified destructively.)\n"))
  2159. (forward-line 1)))))
  2160. (defun ert-results-toggle-printer-limits-for-test-at-point ()
  2161. "Toggle how much of the condition to print for the test at point.
  2162. To be used in the ERT results buffer."
  2163. (interactive)
  2164. (let* ((ewoc ert--results-ewoc)
  2165. (node (ert--results-test-node-at-point))
  2166. (entry (ewoc-data node)))
  2167. (setf (ert--ewoc-entry-extended-printer-limits-p entry)
  2168. (not (ert--ewoc-entry-extended-printer-limits-p entry)))
  2169. (ewoc-invalidate ewoc node)))
  2170. (defun ert-results-pop-to-timings ()
  2171. "Display test timings for the last run.
  2172. To be used in the ERT results buffer."
  2173. (interactive)
  2174. (let* ((stats ert--results-stats)
  2175. (start-times (ert--stats-test-start-times stats))
  2176. (end-times (ert--stats-test-end-times stats))
  2177. (buffer (get-buffer-create "*ERT timings*"))
  2178. (data (loop for test across (ert--stats-tests stats)
  2179. for start-time across (ert--stats-test-start-times stats)
  2180. for end-time across (ert--stats-test-end-times stats)
  2181. collect (list test
  2182. (float-time (subtract-time end-time
  2183. start-time))))))
  2184. (setq data (sort data (lambda (a b)
  2185. (> (second a) (second b)))))
  2186. (pop-to-buffer buffer)
  2187. (let ((inhibit-read-only t))
  2188. (buffer-disable-undo)
  2189. (erase-buffer)
  2190. (ert-simple-view-mode)
  2191. (if (null data)
  2192. (insert "(No data)\n")
  2193. (insert (format "%-3s %8s %8s\n" "" "time" "cumul"))
  2194. (loop for (test time) in data
  2195. for cumul-time = time then (+ cumul-time time)
  2196. for i from 1 do
  2197. (let ((begin (point)))
  2198. (insert (format "%3s: %8.3f %8.3f " i time cumul-time))
  2199. (ert-insert-test-name-button (ert-test-name test))
  2200. (insert "\n"))))
  2201. (goto-char (point-min))
  2202. (insert "Tests by run time (seconds):\n\n")
  2203. (forward-line 1))))
  2204. ;;;###autoload
  2205. (defun ert-describe-test (test-or-test-name)
  2206. "Display the documentation for TEST-OR-TEST-NAME (a symbol or ert-test)."
  2207. (interactive (list (ert-read-test-name-at-point "Describe test")))
  2208. (when (< emacs-major-version 24)
  2209. (error "Requires Emacs 24"))
  2210. (let (test-name
  2211. test-definition)
  2212. (etypecase test-or-test-name
  2213. (symbol (setq test-name test-or-test-name
  2214. test-definition (ert-get-test test-or-test-name)))
  2215. (ert-test (setq test-name (ert-test-name test-or-test-name)
  2216. test-definition test-or-test-name)))
  2217. (help-setup-xref (list #'ert-describe-test test-or-test-name)
  2218. (called-interactively-p 'interactive))
  2219. (save-excursion
  2220. (with-help-window (help-buffer)
  2221. (with-current-buffer (help-buffer)
  2222. (insert (if test-name (format "%S" test-name) "<anonymous test>"))
  2223. (insert " is a test")
  2224. (let ((file-name (and test-name
  2225. (symbol-file test-name 'ert-deftest))))
  2226. (when file-name
  2227. (insert " defined in `" (file-name-nondirectory file-name) "'")
  2228. (save-excursion
  2229. (re-search-backward "`\\([^`']+\\)'" nil t)
  2230. (help-xref-button 1 'help-function-def test-name file-name)))
  2231. (insert ".")
  2232. (fill-region-as-paragraph (point-min) (point))
  2233. (insert "\n\n")
  2234. (unless (and (ert-test-boundp test-name)
  2235. (eql (ert-get-test test-name) test-definition))
  2236. (let ((begin (point)))
  2237. (insert "Note: This test has been redefined or deleted, "
  2238. "this documentation refers to an old definition.")
  2239. (fill-region-as-paragraph begin (point)))
  2240. (insert "\n\n"))
  2241. (insert (or (ert-test-documentation test-definition)
  2242. "It is not documented.")
  2243. "\n")))))))
  2244. (defun ert-results-describe-test-at-point ()
  2245. "Display the documentation of the test at point.
  2246. To be used in the ERT results buffer."
  2247. (interactive)
  2248. (ert-describe-test (ert--results-test-at-point-no-redefinition)))
  2249. ;;; Actions on load/unload.
  2250. (add-to-list 'find-function-regexp-alist '(ert-deftest . ert--find-test-regexp))
  2251. (add-to-list 'minor-mode-alist '(ert--current-run-stats
  2252. (:eval
  2253. (ert--tests-running-mode-line-indicator))))
  2254. (add-to-list 'emacs-lisp-mode-hook 'ert--activate-font-lock-keywords)
  2255. (defun ert--unload-function ()
  2256. "Unload function to undo the side-effects of loading ert.el."
  2257. (ert--remove-from-list 'find-function-regexp-alist 'ert-deftest :key #'car)
  2258. (ert--remove-from-list 'minor-mode-alist 'ert--current-run-stats :key #'car)
  2259. (ert--remove-from-list 'emacs-lisp-mode-hook
  2260. 'ert--activate-font-lock-keywords)
  2261. nil)
  2262. (defvar ert-unload-hook '())
  2263. (add-hook 'ert-unload-hook 'ert--unload-function)
  2264. (provide 'ert)
  2265. ;;; ert.el ends here