Python unit testing in emacs org mode

Using emacs org and babel1, I want to quickly note ideas in python. Now usually I start scripting up to a certain level of complexity / exhaustion which inevitably leads me to setup a complete python project folder in order to get proper unit testing.

Following setup allows me to stay in org mode and unit test. All together.

(defun ndk/org-babel-evaluate-test-block-from-code-block ()
  (interactive)
  (save-excursion
    (org-babel-goto-named-src-block "python_code")
    (org-babel-tangle '(4))
    (org-babel-goto-named-src-block "pytest_python_code")
    (org-babel-execute-src-block)))

(define-key evil-normal-state-map (kbd ", SPC") #'ndk/org-babel-evaluate-test-block-from-code-block)

Evaluating the upper elisp code block binds itself to , SPC .

Now hitting , SPC in block python_code, exports it and subsequently runs the unit test from block pytest_python_code

All while I’m staying in the code, at the same cursor position. No need to jump between code blocks. Beautiful quietness.

#+NAME: python_code
#+BEGIN_SRC python :tangle /tmp/hello.py
 import pytest

 def test_func():
     assert 1 == 1
#+END_SRC

#+NAME: pytest_python_code
#+BEGIN_SRC sh  :results output
  pytest /tmp/hello.py
  rm -f /tmp/hello.py
#+END_SRC
============================= test session starts ==============================
platform linux -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /tmp
plugins: cov-2.12.1, pycharm-0.6.0, vcr-1.0.2, hypothesis-6.15.0
collected 1 item

../../../tmp/hello.py .                                                  [100%]

============================== 1 passed in 0.01s ===============================