如何在 lisp 和 emacs 中测试函数

问题描述

如何断言此函数返回了 2012/08(而不是 2012 年 8 月)?

因此,我可以开始在工作中/使用函数本身学习 lisp,直到输出满足为止。

我知道一些 python 单元测试 (pytest) 并且正在寻找类似于 lisp 的东西。但是,我的第一次尝试 [0] C-c eval-bufferInvalid function: "<2012-08-12 Mon>"

失败
(assert (= (org-cv-utils-org-timestamp-to-shortdate ("<2012-08-12 Mon>")) "Aug 2012"))

(defun org-cv-utils-org-timestamp-to-shortdate (date_str)
"Format orgmode timestamp DATE_STR  into a short form date.
Other strings are just returned unmodified

e.g. <2012-08-12 Mon> => Aug 2012
today => today"
  (if (string-match (org-re-timestamp 'active) date_str)
      (let* ((abbreviate 't)
             (dte (org-parse-time-string date_str))
             (month (nth 4 dte))
             (year (nth 5 dte))) ;;'(02 07 2015)))
        (concat
         (calendar-month-name month abbreviate) " " (number-to-string year)))
    date_str))

[0] https://www.emacswiki.org/emacs/UnitTesting

解决方法

(assert (= (org-cv-utils-org-timestamp-to-shortdate ("<2012-08-12 Mon>")) 
           "Aug 2012"))

(defun org-cv-utils-org-timestamp-to-shortdate (...) ...)
  1. 语句按顺序执行,这意味着您的函数只会在断言被评估后定义。这是一个问题,因为断言调用了该函数。您应该在定义函数后重新排序代码以对其进行测试。

  2. 您不能将字符串与 = 进行比较,如果您为 describe-function 调用 = (Ch f),您会看到 = 是一个数字比较(实际上是数字或标记)。对于字符串,您需要使用 string=

  3. 在正常的评估上下文中,即。不是宏或特殊形式,以下内容被视为函数调用:

    ("<2012-08-12 Mon>")
    

    括号是有意义的,上面的形式说:用零个参数调用函数"<2012-08-12 Mon>"。这不是你想要的,这里不需要在字符串周围添加括号。