Create a keybinding for running Python tests

This commit is contained in:
Ohad Livne 2025-06-04 22:44:58 +03:00
parent 4c8feb9cc6
commit 4304c91381
Signed by: libohad-dev
GPG key ID: 34FDC68B51191A4D

View file

@ -168,10 +168,41 @@
(lsp)) (lsp))
(pyvenv-deactivate)))) (pyvenv-deactivate))))
(defun symbols-at-point ()
(let* ((lsp--document-symbols-request-async t)
(symbols (lsp--get-document-symbols))
(symbols-hierarchy (lsp--symbols->document-symbols-hierarchy symbols)))
(mapcar (lambda (symb)
(list (gethash "name" symb) (lsp--get-symbol-type symb)))
symbols-hierarchy)))
(defun python-test-at-point ()
(let ((symbols (symbols-at-point)))
(pcase symbols
(`((,class "Class") (,method "Method") . ,_)
(if (equal "test_" (substring method 0 5))
`(,class ,method)
`(,class)))
(`((,class "Class") . ,_) `(,class))
(_ ()))))
(defun python-test-name-at-point ()
(let* ((path (mapcar #'substring-no-properties lsp-headerline--path-up-to-project-segments))
(filename (f-no-ext (f-filename (buffer-file-name)))))
(string-join (append path (list filename) (python-test-at-point)) ".")))
(defun python-run-test-at-point ()
(interactive)
(let ((python (executable-find "python"))
(test-name (python-test-name-at-point)))
(compile (concat python " -m unittest " test-name))))
(use-package python (use-package python
:bind (:map python-mode-map :bind (:map python-mode-map
("C-c C-p" . nil) ("C-c C-p" . nil)
("C-c C-l" . nil)) ("C-c C-l" . nil)
("C-c C-t" . python-run-test-at-point)
("C-M-t" . recompile))
:hook ((python-mode . load-python-env))) :hook ((python-mode . load-python-env)))
; Requires the Python package "black" ; Requires the Python package "black"