Klimi's new dotfiles with stow.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

823 regels
33 KiB

4 jaren geleden
  1. ;;; cider-test.el --- Test result viewer -*- lexical-binding: t -*-
  2. ;; Copyright © 2014-2019 Jeff Valk, Bozhidar Batsov and CIDER contributors
  3. ;; Author: Jeff Valk <jv@jeffvalk.com>
  4. ;; This program is free software: you can redistribute it and/or modify
  5. ;; it under the terms of the GNU General Public License as published by
  6. ;; the Free Software Foundation, either version 3 of the License, or
  7. ;; (at your option) any later version.
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;; You should have received a copy of the GNU General Public License
  13. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. ;; This file is not part of GNU Emacs.
  15. ;;; Commentary:
  16. ;; This provides execution, reporting, and navigation support for Clojure tests,
  17. ;; specifically using the `clojure.test' machinery. This functionality replaces
  18. ;; the venerable `clojure-test-mode' (deprecated in June 2014), and relies on
  19. ;; nREPL middleware for report running and session support.
  20. ;;; Code:
  21. (require 'button)
  22. (require 'cl-lib)
  23. (require 'easymenu)
  24. (require 'map)
  25. (require 'seq)
  26. (require 'subr-x)
  27. (require 'cider-common)
  28. (require 'cider-client)
  29. (require 'cider-popup)
  30. (require 'cider-stacktrace)
  31. (require 'cider-compat)
  32. (require 'cider-overlays)
  33. ;;; Variables
  34. (defgroup cider-test nil
  35. "Presentation and navigation for test results."
  36. :prefix "cider-test-"
  37. :group 'cider)
  38. (defcustom cider-test-show-report-on-success nil
  39. "Whether to show the `*cider-test-report*` buffer on passing tests."
  40. :type 'boolean
  41. :group 'cider-test
  42. :package-version '(cider . "0.8.0"))
  43. (defcustom cider-auto-select-test-report-buffer t
  44. "Determines if the test-report buffer should be auto-selected."
  45. :type 'boolean
  46. :group 'cider-test
  47. :package-version '(cider . "0.9.0"))
  48. (defcustom cider-test-defining-forms '("deftest" "defspec")
  49. "Forms that define individual tests.
  50. CIDER considers the \"top-level\" form around point to define a test if
  51. the form starts with one of these forms.
  52. Add to this list to have CIDER recognize additional test defining macros."
  53. :type '(repeat string)
  54. :group 'cider-test
  55. :package-version '(cider . "0.15.0"))
  56. (defvar cider-test-last-summary nil
  57. "The summary of the last run test.")
  58. (defvar cider-test-last-results nil
  59. "The results of the last run test.")
  60. (defconst cider-test-report-buffer "*cider-test-report*"
  61. "Buffer name in which to display test reports.")
  62. ;;; Faces
  63. (defface cider-test-failure-face
  64. '((((class color) (background light))
  65. :background "orange red")
  66. (((class color) (background dark))
  67. :background "firebrick"))
  68. "Face for failed tests."
  69. :group 'cider-test
  70. :package-version '(cider . "0.7.0"))
  71. (defface cider-test-error-face
  72. '((((class color) (background light))
  73. :background "orange1")
  74. (((class color) (background dark))
  75. :background "orange4"))
  76. "Face for erring tests."
  77. :group 'cider-test
  78. :package-version '(cider . "0.7.0"))
  79. (defface cider-test-success-face
  80. '((((class color) (background light))
  81. :foreground "black"
  82. :background "green")
  83. (((class color) (background dark))
  84. :foreground "black"
  85. :background "green"))
  86. "Face for passing tests."
  87. :group 'cider-test
  88. :package-version '(cider . "0.7.0"))
  89. ;; Colors & Theme Support
  90. (defvar cider-test-items-background-color
  91. (cider-scale-background-color)
  92. "Background color for test assertion items.")
  93. (defadvice enable-theme (after cider-test-adapt-to-theme activate)
  94. "When theme is changed, update `cider-test-items-background-color'."
  95. (setq cider-test-items-background-color (cider-scale-background-color)))
  96. (defadvice disable-theme (after cider-test-adapt-to-theme activate)
  97. "When theme is disabled, update `cider-test-items-background-color'."
  98. (setq cider-test-items-background-color (cider-scale-background-color)))
  99. ;;; Report mode & key bindings
  100. ;;
  101. ;; The primary mode of interacting with test results is the report buffer, which
  102. ;; allows navigation among tests, jumping to test definitions, expected/actual
  103. ;; diff-ing, and cause/stacktrace inspection for test errors.
  104. (defvar cider-test-commands-map
  105. (let ((map (define-prefix-command 'cider-test-commands-map)))
  106. ;; Duplicates of keys below with C- for convenience
  107. (define-key map (kbd "C-r") #'cider-test-rerun-failed-tests)
  108. (define-key map (kbd "C-t") #'cider-test-run-test)
  109. (define-key map (kbd "C-a") #'cider-test-rerun-test)
  110. (define-key map (kbd "C-n") #'cider-test-run-ns-tests)
  111. (define-key map (kbd "C-s") #'cider-test-run-ns-tests-with-filters)
  112. (define-key map (kbd "C-l") #'cider-test-run-loaded-tests)
  113. (define-key map (kbd "C-p") #'cider-test-run-project-tests)
  114. (define-key map (kbd "C-b") #'cider-test-show-report)
  115. ;; Single-key bindings defined last for display in menu
  116. (define-key map (kbd "r") #'cider-test-rerun-failed-tests)
  117. (define-key map (kbd "t") #'cider-test-run-test)
  118. (define-key map (kbd "a") #'cider-test-rerun-test)
  119. (define-key map (kbd "n") #'cider-test-run-ns-tests)
  120. (define-key map (kbd "s") #'cider-test-run-ns-tests-with-filters)
  121. (define-key map (kbd "l") #'cider-test-run-loaded-tests)
  122. (define-key map (kbd "p") #'cider-test-run-project-tests)
  123. (define-key map (kbd "b") #'cider-test-show-report)
  124. map))
  125. (defconst cider-test-menu
  126. '("Test"
  127. ["Run test" cider-test-run-test]
  128. ["Run namespace tests" cider-test-run-ns-tests]
  129. ["Run namespace tests with filters" cider-test-run-ns-tests-with-filters]
  130. ["Run all loaded tests" cider-test-run-loaded-tests]
  131. ["Run all loaded tests with filters" (apply-partially cider-test-run-loaded-tests 'prompt-for-filters)]
  132. ["Run all project tests" cider-test-run-project-tests]
  133. ["Run all project tests with filters" (apply-partially cider-test-run-project-tests 'prompt-for-filters)]
  134. ["Run tests after load-file" cider-auto-test-mode
  135. :style toggle :selected cider-auto-test-mode]
  136. "--"
  137. ["Interrupt running tests" cider-interrupt]
  138. ["Rerun failed/erring tests" cider-test-rerun-failed-tests]
  139. ["Show test report" cider-test-show-report]
  140. "--"
  141. ["Configure testing" (customize-group 'cider-test)])
  142. "CIDER test submenu.")
  143. (defvar cider-test-report-mode-map
  144. (let ((map (make-sparse-keymap)))
  145. (define-key map (kbd "C-c ,") 'cider-test-commands-map)
  146. (define-key map (kbd "C-c C-t") 'cider-test-commands-map)
  147. (define-key map (kbd "M-p") #'cider-test-previous-result)
  148. (define-key map (kbd "M-n") #'cider-test-next-result)
  149. (define-key map (kbd "M-.") #'cider-test-jump)
  150. (define-key map (kbd "<backtab>") #'cider-test-previous-result)
  151. (define-key map (kbd "TAB") #'cider-test-next-result)
  152. (define-key map (kbd "RET") #'cider-test-jump)
  153. (define-key map (kbd "t") #'cider-test-jump)
  154. (define-key map (kbd "d") #'cider-test-ediff)
  155. (define-key map (kbd "e") #'cider-test-stacktrace)
  156. ;; `f' for "run failed".
  157. (define-key map "f" #'cider-test-rerun-failed-tests)
  158. (define-key map "n" #'cider-test-run-ns-tests)
  159. (define-key map "s" #'cider-test-run-ns-tests-with-filters)
  160. (define-key map "l" #'cider-test-run-loaded-tests)
  161. (define-key map "p" #'cider-test-run-project-tests)
  162. ;; `g' generally reloads the buffer. The closest thing we have to that is
  163. ;; "run the test at point". But it's not as nice as rerunning all tests in
  164. ;; this buffer.
  165. (define-key map "g" #'cider-test-run-test)
  166. (define-key map "q" #'cider-popup-buffer-quit-function)
  167. (easy-menu-define cider-test-report-mode-menu map
  168. "Menu for CIDER's test result mode"
  169. '("Test-Report"
  170. ["Previous result" cider-test-previous-result]
  171. ["Next result" cider-test-next-result]
  172. "--"
  173. ["Rerun current test" cider-test-run-test]
  174. ["Rerun failed/erring tests" cider-test-rerun-failed-tests]
  175. ["Run all ns tests" cider-test-run-ns-tests]
  176. ["Run all ns tests with filters" cider-test-run-ns-tests-with-filters]
  177. ["Run all loaded tests" cider-test-run-loaded-tests]
  178. ["Run all loaded tests with filters" (apply-partially cider-test-run-loaded-tests 'prompt-for-filters)]
  179. ["Run all project tests" cider-test-run-project-tests]
  180. ["Run all project tests with filters" (apply-partially cider-test-run-project-tests 'prompt-for-filters)]
  181. "--"
  182. ["Jump to test definition" cider-test-jump]
  183. ["Display test error" cider-test-stacktrace]
  184. ["Display expected/actual diff" cider-test-ediff]))
  185. map))
  186. (define-derived-mode cider-test-report-mode fundamental-mode "Test Report"
  187. "Major mode for presenting Clojure test results.
  188. \\{cider-test-report-mode-map}"
  189. (setq buffer-read-only t)
  190. (when cider-special-mode-truncate-lines
  191. (setq-local truncate-lines t))
  192. (setq-local sesman-system 'CIDER)
  193. (setq-local electric-indent-chars nil))
  194. ;; Report navigation
  195. (defun cider-test-show-report ()
  196. "Show the test report buffer, if one exists."
  197. (interactive)
  198. (if-let* ((report-buffer (get-buffer cider-test-report-buffer)))
  199. (switch-to-buffer report-buffer)
  200. (message "No test report buffer")))
  201. (defun cider-test-previous-result ()
  202. "Move point to the previous test result, if one exists."
  203. (interactive)
  204. (with-current-buffer (get-buffer cider-test-report-buffer)
  205. (when-let* ((pos (previous-single-property-change (point) 'type)))
  206. (if (get-text-property pos 'type)
  207. (goto-char pos)
  208. (when-let* ((pos (previous-single-property-change pos 'type)))
  209. (goto-char pos))))))
  210. (defun cider-test-next-result ()
  211. "Move point to the next test result, if one exists."
  212. (interactive)
  213. (with-current-buffer (get-buffer cider-test-report-buffer)
  214. (when-let* ((pos (next-single-property-change (point) 'type)))
  215. (if (get-text-property pos 'type)
  216. (goto-char pos)
  217. (when-let* ((pos (next-single-property-change pos 'type)))
  218. (goto-char pos))))))
  219. (declare-function cider-find-var "cider-find")
  220. (defun cider-test-jump (&optional arg)
  221. "Find definition for test at point, if available.
  222. The prefix ARG and `cider-prompt-for-symbol' decide whether to
  223. prompt and whether to use a new window. Similar to `cider-find-var'."
  224. (interactive "P")
  225. (let ((ns (get-text-property (point) 'ns))
  226. (var (get-text-property (point) 'var))
  227. (line (get-text-property (point) 'line)))
  228. (if (and ns var)
  229. (cider-find-var arg (concat ns "/" var) line)
  230. (cider-find-var arg))))
  231. ;;; Error stacktraces
  232. (defvar cider-auto-select-error-buffer)
  233. (defun cider-test-stacktrace-for (ns var index)
  234. "Display stacktrace for the erring NS VAR test with the assertion INDEX."
  235. (let (causes)
  236. (cider-nrepl-send-request
  237. (thread-last
  238. (map-merge 'list
  239. `(("op" "test-stacktrace")
  240. ("ns" ,ns)
  241. ("var" ,var)
  242. ("index" ,index))
  243. (cider--nrepl-print-request-map fill-column))
  244. (seq-mapcat #'identity))
  245. (lambda (response)
  246. (nrepl-dbind-response response (class status)
  247. (cond (class (setq causes (cons response causes)))
  248. (status (when causes
  249. (cider-stacktrace-render
  250. (cider-popup-buffer cider-error-buffer
  251. cider-auto-select-error-buffer
  252. #'cider-stacktrace-mode
  253. 'ancillary)
  254. (reverse causes))))))))))
  255. (defun cider-test-stacktrace ()
  256. "Display stacktrace for the erring test at point."
  257. (interactive)
  258. (let ((ns (get-text-property (point) 'ns))
  259. (var (get-text-property (point) 'var))
  260. (index (get-text-property (point) 'index))
  261. (err (get-text-property (point) 'error)))
  262. (if (and err ns var index)
  263. (cider-test-stacktrace-for ns var index)
  264. (message "No test error at point"))))
  265. ;;; Expected vs actual diffing
  266. (defvar cider-test-ediff-buffers nil
  267. "The expected/actual buffers used to display diff.")
  268. (defun cider-test--extract-from-actual (actual n)
  269. "Extract form N from ACTUAL, ignoring outermost not.
  270. ACTUAL is a string like \"(not (= 3 4))\", of the sort returned by
  271. clojure.test.
  272. N = 1 => 3, N = 2 => 4, etc."
  273. (with-temp-buffer
  274. (insert actual)
  275. (clojure-mode)
  276. (goto-char (point-min))
  277. (re-search-forward "(" nil t 2)
  278. (clojure-forward-logical-sexp n)
  279. (forward-whitespace 1)
  280. (let ((beg (point)))
  281. (clojure-forward-logical-sexp)
  282. (buffer-substring beg (point)))))
  283. (defun cider-test-ediff ()
  284. "Show diff of the expected vs actual value for the test at point.
  285. With the actual value, the outermost '(not ...)' s-expression is removed."
  286. (interactive)
  287. (let* ((expected-buffer (generate-new-buffer " *expected*"))
  288. (actual-buffer (generate-new-buffer " *actual*"))
  289. (diffs (get-text-property (point) 'diffs))
  290. (actual* (get-text-property (point) 'actual))
  291. (expected (cond (diffs (get-text-property (point) 'expected))
  292. (actual* (cider-test--extract-from-actual actual* 1))))
  293. (actual (cond (diffs (caar diffs))
  294. (actual* (cider-test--extract-from-actual actual* 2)))))
  295. (if (not (and expected actual))
  296. (message "No test failure at point")
  297. (with-current-buffer expected-buffer
  298. (insert expected)
  299. (clojure-mode))
  300. (with-current-buffer actual-buffer
  301. (insert actual)
  302. (clojure-mode))
  303. (apply #'ediff-buffers
  304. (setq cider-test-ediff-buffers
  305. (list (buffer-name expected-buffer)
  306. (buffer-name actual-buffer)))))))
  307. (defun cider-test-ediff-cleanup ()
  308. "Cleanup expected/actual buffers used for diff."
  309. (interactive)
  310. (mapc (lambda (b) (when (get-buffer b) (kill-buffer b)))
  311. cider-test-ediff-buffers))
  312. (add-hook 'ediff-cleanup-hook #'cider-test-ediff-cleanup)
  313. ;;; Report rendering
  314. (defun cider-test-type-face (type)
  315. "Return the font lock face for the test result TYPE."
  316. (pcase type
  317. ("pass" 'cider-test-success-face)
  318. ("fail" 'cider-test-failure-face)
  319. ("error" 'cider-test-error-face)
  320. (_ 'default)))
  321. (defun cider-test-type-simple-face (type)
  322. "Return a face for the test result TYPE using the highlight color as foreground."
  323. (let ((face (cider-test-type-face type)))
  324. `(:foreground ,(face-attribute face :background))))
  325. (defun cider-test-render-summary (buffer summary)
  326. "Emit into BUFFER the report SUMMARY statistics."
  327. (with-current-buffer buffer
  328. (nrepl-dbind-response summary (ns var test pass fail error)
  329. (insert (format "Tested %d namespaces\n" ns))
  330. (insert (format "Ran %d assertions, in %d test functions\n" test var))
  331. (unless (zerop fail)
  332. (cider-insert (format "%d failures" fail) 'cider-test-failure-face t))
  333. (unless (zerop error)
  334. (cider-insert (format "%d errors" error) 'cider-test-error-face t))
  335. (when (zerop (+ fail error))
  336. (cider-insert (format "%d passed" pass) 'cider-test-success-face t))
  337. (insert "\n\n"))))
  338. (defun cider-test-render-assertion (buffer test)
  339. "Emit into BUFFER report detail for the TEST assertion."
  340. (with-current-buffer buffer
  341. (nrepl-dbind-response test (var context type message expected actual diffs error gen-input)
  342. (cl-flet ((insert-label (s)
  343. (cider-insert (format "%8s: " s) 'font-lock-comment-face))
  344. (insert-align-label (s)
  345. (insert (format "%12s" s)))
  346. (insert-rect (s)
  347. (insert-rectangle (thread-first s
  348. cider-font-lock-as-clojure
  349. (split-string "\n")))
  350. (beginning-of-line)))
  351. (cider-propertize-region (cider-intern-keys (cdr test))
  352. (let ((beg (point))
  353. (type-face (cider-test-type-simple-face type))
  354. (bg `(:background ,cider-test-items-background-color)))
  355. (cider-insert (capitalize type) type-face nil " in ")
  356. (cider-insert var 'font-lock-function-name-face t)
  357. (when context (cider-insert context 'font-lock-doc-face t))
  358. (when message (cider-insert message 'font-lock-string-face t))
  359. (when expected
  360. (insert-label "expected")
  361. (insert-rect expected)
  362. (insert "\n"))
  363. (if diffs
  364. (dolist (d diffs)
  365. (cl-destructuring-bind (actual (removed added)) d
  366. (insert-label "actual")
  367. (insert-rect actual)
  368. (insert-label "diff")
  369. (insert "- ")
  370. (insert-rect removed)
  371. (insert-align-label "+ ")
  372. (insert-rect added)
  373. (insert "\n")))
  374. (when actual
  375. (insert-label "actual")
  376. (insert-rect actual)))
  377. (when error
  378. (insert-label "error")
  379. (insert-text-button error
  380. 'follow-link t
  381. 'action '(lambda (_button) (cider-test-stacktrace))
  382. 'help-echo "View causes and stacktrace")
  383. (insert "\n"))
  384. (when gen-input
  385. (insert-label "input")
  386. (insert (cider-font-lock-as-clojure gen-input)))
  387. (overlay-put (make-overlay beg (point)) 'font-lock-face bg))
  388. (insert "\n"))))))
  389. (defun cider-test-non-passing (tests)
  390. "For a list of TESTS, each an `nrepl-dict`, return only those that did not pass."
  391. (seq-filter (lambda (test)
  392. (unless (equal (nrepl-dict-get test "type") "pass")
  393. test))
  394. tests))
  395. (defun cider-test-render-report (buffer summary results)
  396. "Emit into BUFFER the report for the SUMMARY, and test RESULTS."
  397. (with-current-buffer buffer
  398. (let ((inhibit-read-only t))
  399. (cider-test-report-mode)
  400. (cider-insert "Test Summary" 'bold t)
  401. (dolist (ns (nrepl-dict-keys results))
  402. (insert (cider-propertize ns 'ns) "\n"))
  403. (cider-insert "\n")
  404. (cider-test-render-summary buffer summary)
  405. (nrepl-dbind-response summary (fail error)
  406. (unless (zerop (+ fail error))
  407. (cider-insert "Results" 'bold t "\n")
  408. ;; Results are a nested dict, keyed first by ns, then var. Within each
  409. ;; var is a sequence of test assertion results.
  410. (nrepl-dict-map
  411. (lambda (ns vars)
  412. (nrepl-dict-map
  413. (lambda (_var tests)
  414. (let* ((problems (cider-test-non-passing tests))
  415. (count (length problems)))
  416. (when (< 0 count)
  417. (insert (format "%s\n%d non-passing tests:\n\n"
  418. (cider-propertize ns 'ns) count))
  419. (dolist (test problems)
  420. (cider-test-render-assertion buffer test)))))
  421. vars))
  422. results)))
  423. (goto-char (point-min))
  424. (current-buffer))))
  425. ;;; Message echo
  426. (defun cider-test-echo-running (ns &optional test)
  427. "Echo a running message for the test NS, which may be a keyword.
  428. The optional arg TEST denotes an individual test name."
  429. (if test
  430. (message "Running test %s in %s..."
  431. (cider-propertize test 'bold)
  432. (cider-propertize ns 'ns))
  433. (message "Running tests in %s..."
  434. (concat (cider-propertize
  435. (cond ((stringp ns) ns)
  436. ((eq :non-passing ns) "failing")
  437. ((eq :loaded ns) "all loaded")
  438. ((eq :project ns) "all project"))
  439. 'ns)
  440. (unless (stringp ns) " namespaces")))))
  441. (defun cider-test-echo-summary (summary results)
  442. "Echo SUMMARY statistics for a test run returning RESULTS."
  443. (nrepl-dbind-response summary (ns test var fail error)
  444. (if (nrepl-dict-empty-p results)
  445. (message (concat (propertize "No assertions (or no tests) were run." 'face 'cider-test-error-face)
  446. "Did you forget to use `is' in your tests?"))
  447. (message (propertize
  448. "%sRan %d assertions, in %d test functions. %d failures, %d errors."
  449. 'face (cond ((not (zerop error)) 'cider-test-error-face)
  450. ((not (zerop fail)) 'cider-test-failure-face)
  451. (t 'cider-test-success-face)))
  452. (concat (if (= 1 ns) ; ns count from summary
  453. (cider-propertize (car (nrepl-dict-keys results)) 'ns)
  454. (propertize (format "%d namespaces" ns) 'face 'default))
  455. (propertize ": " 'face 'default))
  456. test var fail error))))
  457. ;;; Test definition highlighting
  458. ;;
  459. ;; On receipt of test results, failing/erring test definitions are highlighted.
  460. ;; Highlights are cleared on the next report run, and may be cleared manually
  461. ;; by the user.
  462. ;; NOTE If keybindings specific to test sources are desired, it would be
  463. ;; straightforward to turn this into a `cider-test-mode' minor mode, which we
  464. ;; enable on test sources, much like the legacy `clojure-test-mode'. At present,
  465. ;; though, there doesn't seem to be much value in this, since the report buffer
  466. ;; provides the primary means of interacting with test results.
  467. (defun cider-test-highlight-problem (buffer test)
  468. "Highlight the BUFFER test definition for the non-passing TEST."
  469. (with-current-buffer buffer
  470. ;; we don't need the file name here, as we always operate on the current
  471. ;; buffer and the line data is correct even for vars that were
  472. ;; defined interactively
  473. (nrepl-dbind-response test (type line message expected actual)
  474. (when line
  475. (save-excursion
  476. (goto-char (point-min))
  477. (forward-line (1- line))
  478. (search-forward "(" nil t)
  479. (let ((beg (point)))
  480. (forward-sexp)
  481. (cider--make-overlay beg (point) 'cider-test
  482. 'font-lock-face (cider-test-type-face type)
  483. 'type type
  484. 'help-echo message
  485. 'message message
  486. 'expected expected
  487. 'actual actual)))))))
  488. (defun cider-find-var-file (ns var)
  489. "Return the buffer visiting the file in which the NS VAR is defined.
  490. Or nil if not found."
  491. (when-let* ((info (cider-var-info (concat ns "/" var)))
  492. (file (nrepl-dict-get info "file")))
  493. (cider-find-file file)))
  494. (defun cider-test-highlight-problems (results)
  495. "Highlight all non-passing tests in the test RESULTS."
  496. (nrepl-dict-map
  497. (lambda (ns vars)
  498. (nrepl-dict-map
  499. (lambda (var tests)
  500. (when-let* ((buffer (cider-find-var-file ns var)))
  501. (dolist (test tests)
  502. (nrepl-dbind-response test (type)
  503. (unless (equal "pass" type)
  504. (cider-test-highlight-problem buffer test))))))
  505. vars))
  506. results))
  507. (defun cider-test-clear-highlights ()
  508. "Clear highlighting of non-passing tests from the last test run."
  509. (interactive)
  510. (when cider-test-last-results
  511. (nrepl-dict-map
  512. (lambda (ns vars)
  513. (dolist (var (nrepl-dict-keys vars))
  514. (when-let* ((buffer (cider-find-var-file ns var)))
  515. (with-current-buffer buffer
  516. (remove-overlays nil nil 'category 'cider-test)))))
  517. cider-test-last-results)))
  518. ;;; Test namespaces
  519. ;;
  520. ;; Test namespace inference exists to enable DWIM test running functions: the
  521. ;; same "run-tests" function should be able to be used in a source file, and in
  522. ;; its corresponding test namespace. To provide this, we need to map the
  523. ;; relationship between those namespaces.
  524. (defcustom cider-test-infer-test-ns 'cider-test-default-test-ns-fn
  525. "Function to infer the test namespace for NS.
  526. The default implementation uses the simple Leiningen convention of appending
  527. '-test' to the namespace name."
  528. :type 'symbol
  529. :group 'cider-test
  530. :package-version '(cider . "0.7.0"))
  531. (defun cider-test-default-test-ns-fn (ns)
  532. "For a NS, return the test namespace, which may be the argument itself.
  533. This uses the Leiningen convention of appending '-test' to the namespace name."
  534. (when ns
  535. (let ((suffix "-test"))
  536. (if (string-suffix-p suffix ns)
  537. ns
  538. (concat ns suffix)))))
  539. ;;; Test execution
  540. (declare-function cider-emit-interactive-eval-output "cider-eval")
  541. (declare-function cider-emit-interactive-eval-err-output "cider-eval")
  542. (defun cider-test--prompt-for-selectors (message)
  543. "Prompt for test selectors with MESSAGE.
  544. The selectors can be either keywords or strings."
  545. (mapcar
  546. (lambda (string) (replace-regexp-in-string "^:+" "" string))
  547. (split-string
  548. (cider-read-from-minibuffer message))))
  549. (defun cider-test-execute (ns &optional tests silent prompt-for-filters)
  550. "Run tests for NS, which may be a keyword, optionally specifying TESTS.
  551. This tests a single NS, or multiple namespaces when using keywords `:project',
  552. `:loaded' or `:non-passing'. Optional TESTS are only honored when a single
  553. namespace is specified. Upon test completion, results are echoed and a test
  554. report is optionally displayed. When test failures/errors occur, their sources
  555. are highlighted.
  556. If SILENT is non-nil, suppress all messages other then test results.
  557. If PROMPT-FOR-FILTERS is non-nil, prompt the user for a test selector filters.
  558. The include/exclude selectors will be used to filter the tests before
  559. running them."
  560. (cider-test-clear-highlights)
  561. (let ((include-selectors
  562. (when prompt-for-filters
  563. (cider-test--prompt-for-selectors "Test selectors to include (space separated): ")))
  564. (exclude-selectors
  565. (when prompt-for-filters
  566. (cider-test--prompt-for-selectors "Test selectors to exclude (space separated): "))))
  567. (cider-map-repls :clj-strict
  568. (lambda (conn)
  569. (unless silent
  570. (if (and tests (= (length tests) 1))
  571. ;; we generate a different message when running individual tests
  572. (cider-test-echo-running ns (car tests))
  573. (cider-test-echo-running ns)))
  574. (let ((request `("op" ,(cond ((stringp ns) "test")
  575. ((eq :project ns) "test-all")
  576. ((eq :loaded ns) "test-all")
  577. ((eq :non-passing ns) "retest")))))
  578. ;; we add optional parts of the request only when relevant
  579. (when (and (listp include-selectors) include-selectors)
  580. (setq request (append request `("include" ,include-selectors))))
  581. (when (and (listp exclude-selectors) exclude-selectors)
  582. (setq request (append request `("exclude" ,exclude-selectors))))
  583. (when (stringp ns)
  584. (setq request (append request `("ns" ,ns))))
  585. (when (stringp ns)
  586. (setq request (append request `("tests" ,tests))))
  587. (when (or (stringp ns) (eq :project ns))
  588. (setq request (append request `("load?" ,"true"))))
  589. (cider-nrepl-send-request
  590. request
  591. (lambda (response)
  592. (nrepl-dbind-response response (summary results status out err)
  593. (cond ((member "namespace-not-found" status)
  594. (unless silent
  595. (message "No test namespace: %s" (cider-propertize ns 'ns))))
  596. (out (cider-emit-interactive-eval-output out))
  597. (err (cider-emit-interactive-eval-err-output err))
  598. (results
  599. (nrepl-dbind-response summary (error fail)
  600. (setq cider-test-last-summary summary)
  601. (setq cider-test-last-results results)
  602. (cider-test-highlight-problems results)
  603. (cider-test-echo-summary summary results)
  604. (if (or (not (zerop (+ error fail)))
  605. cider-test-show-report-on-success)
  606. (cider-test-render-report
  607. (cider-popup-buffer
  608. cider-test-report-buffer
  609. cider-auto-select-test-report-buffer)
  610. summary
  611. results)
  612. (when (get-buffer cider-test-report-buffer)
  613. (with-current-buffer cider-test-report-buffer
  614. (let ((inhibit-read-only t))
  615. (erase-buffer)))
  616. (cider-test-render-report
  617. cider-test-report-buffer
  618. summary results))))))))
  619. conn))))))
  620. (defun cider-test-rerun-failed-tests ()
  621. "Rerun failed and erring tests from the last test run."
  622. (interactive)
  623. (if cider-test-last-summary
  624. (nrepl-dbind-response cider-test-last-summary (fail error)
  625. (if (not (zerop (+ error fail)))
  626. (cider-test-execute :non-passing)
  627. (message "No prior failures to retest")))
  628. (message "No prior results to retest")))
  629. (defun cider-test-run-loaded-tests (prompt-for-filters)
  630. "Run all tests defined in currently loaded namespaces.
  631. If PROMPT-FOR-FILTERS is non-nil, prompt the user for a test selectors to filter the tests with."
  632. (interactive "P")
  633. (cider-test-execute :loaded nil nil prompt-for-filters))
  634. (defun cider-test-run-project-tests (prompt-for-filters)
  635. "Run all tests defined in all project namespaces, loading these as needed.
  636. If PROMPT-FOR-FILTERS is non-nil, prompt the user for a test selectors to filter the tests with."
  637. (interactive "P")
  638. (cider-test-execute :project nil nil prompt-for-filters))
  639. (defun cider-test-run-ns-tests-with-filters (suppress-inference)
  640. "Run tests filtered by selectors for the current Clojure namespace context.
  641. With a prefix arg SUPPRESS-INFERENCE it will try to run the tests in the
  642. current ns."
  643. (interactive "P")
  644. (cider-test-run-ns-tests suppress-inference nil 't))
  645. (defun cider-test-run-ns-tests (suppress-inference &optional silent prompt-for-filters)
  646. "Run all tests for the current Clojure namespace context.
  647. If SILENT is non-nil, suppress all messages other then test results.
  648. With a prefix arg SUPPRESS-INFERENCE it will try to run the tests in the
  649. current ns. If PROMPT-FOR-FILTERS is non-nil, prompt the user for
  650. test selectors to filter the tests with."
  651. (interactive "P")
  652. (if-let* ((ns (if suppress-inference
  653. (cider-current-ns t)
  654. (funcall cider-test-infer-test-ns (cider-current-ns t)))))
  655. (cider-test-execute ns nil silent prompt-for-filters)
  656. (if (eq major-mode 'cider-test-report-mode)
  657. (when (y-or-n-p (concat "Test report does not define a namespace. "
  658. "Rerun failed/erring tests?"))
  659. (cider-test-rerun-failed-tests))
  660. (unless silent
  661. (message "No namespace to test in current context")))))
  662. (defvar cider-test-last-test-ns nil
  663. "The ns of the last test ran with `cider-test-run-test'.")
  664. (defvar cider-test-last-test-var nil
  665. "The var of the last test ran with `cider-test-run-test'.")
  666. (defun cider-test-update-last-test (ns var)
  667. "Update the last test by setting NS and VAR.
  668. See `cider-test-rerun-test'."
  669. (setq cider-test-last-test-ns ns
  670. cider-test-last-test-var var))
  671. (defun cider-test-run-test ()
  672. "Run the test at point.
  673. The test ns/var exist as text properties on report items and on highlighted
  674. failed/erred test definitions. When not found, a test definition at point
  675. is searched."
  676. (interactive)
  677. (let ((ns (get-text-property (point) 'ns))
  678. (var (get-text-property (point) 'var)))
  679. (if (and ns var)
  680. ;; we're in a `cider-test-report-mode' buffer
  681. ;; or on a highlighted failed/erred test definition
  682. (progn
  683. (cider-test-update-last-test ns var)
  684. (cider-test-execute ns (list var)))
  685. ;; we're in a `clojure-mode' buffer
  686. (let* ((ns (clojure-find-ns))
  687. (def (clojure-find-def)) ; it's a list of the form (deftest something)
  688. (deftype (car def))
  689. (var (cadr def)))
  690. (if (and ns (member deftype cider-test-defining-forms))
  691. (progn
  692. (cider-test-update-last-test ns (list var))
  693. (cider-test-execute ns (list var)))
  694. (message "No test at point"))))))
  695. (defun cider-test-rerun-test ()
  696. "Re-run the test that was previously ran."
  697. (interactive)
  698. (if (and cider-test-last-test-ns cider-test-last-test-var)
  699. (cider-test-execute cider-test-last-test-ns cider-test-last-test-var)
  700. (user-error "No test to re-run")))
  701. ;;; Auto-test mode
  702. (defun cider--test-silently ()
  703. "Like `cider-test-run-tests', but with less feedback.
  704. Only notify the user if there actually were any tests to run and only after
  705. the results are received."
  706. (when (cider-connected-p)
  707. (let ((cider-auto-select-test-report-buffer nil)
  708. (cider-test-show-report-on-success nil))
  709. (cider-test-run-ns-tests nil 'soft))))
  710. ;;;###autoload
  711. (define-minor-mode cider-auto-test-mode
  712. "Toggle automatic testing of Clojure files.
  713. When enabled this reruns tests every time a Clojure file is loaded.
  714. Only runs tests corresponding to the loaded file's namespace and does
  715. nothing if no tests are defined or if the file failed to load."
  716. nil (cider-mode " Test") nil
  717. :global t
  718. (if cider-auto-test-mode
  719. (add-hook 'cider-file-loaded-hook #'cider--test-silently)
  720. (remove-hook 'cider-file-loaded-hook #'cider--test-silently)))
  721. (provide 'cider-test)
  722. ;;; cider-test.el ends here