newLISP unit tests

Started by kinghajj, September 10, 2007, 03:57:41 PM

Previous topic - Next topic

kinghajj

I was reading the book Practical Common Lisp, and found a great implementation of unit tests in Common Lisp. So, I thought I'd re-make them (in my own way, of course,) in newLISP.



nltests.lsp

;; nltests.lsp -- testing macros
;; Copyright (C) 2007 Samuel Fredrickson.

(context 'nltests)

; used to report which tests and sub-tests failed.
(setq *test-name* '())

; set to true if you want tests to report which tests failed
(setq *report-failures* true)

; set to true if you want tests to report which tests passed
(setq *report-passes* nil)

; prints a failure if allowed
(define (report-failure test)
  (if *report-failures*
    (println *test-name* ": " test " FAILED!"))
  nil)

; prints a pass if allowed
(define (report-pass test)
  (if *report-passes*
    (println *test-name* ": " test " passed"))
  true)

; reports the status of a test.
(define (report test)
  (if (eval test)
    (report-pass test)
    (report-failure test)))

; tests tests, returns nil on fail and true on pass.
(define-macro (check tests)
  (apply and (map report tests)))

(context 'MAIN)

; defines a new test.
(define-macro (define-test params)
  (eval (expand
    '(define params
       (let ((nltests:*test-name* (append nltests:*test-name* '(_name))))
         (nltests:check tests)))
    (list
      (list 'params params)
      (list '_name  (params 0))
      (list 'tests  (args))))))


Here's a very simple arithmetic test.

(load "nltests.lsp")

(define-test (test-+)
  (= (+ 5 9) 14)
  (= (+ 4 3) 7))

(define-test (test-*)
  (= (* 4 5) 20)
  (= (* 3 2) 6))

(define-test (test-math)
  (test-+)
  (test-*))


If you want to have fun, try making these tests impossible, then see how the errors are reported. If test-math fails, it tells you the exact hierarchy of the failed test.



Hope you find this useful.

Jeff

#1
Very nice.  Thank you for your contribution!
Jeff

=====

Old programmers don\'t die. They just parse on...



http://artfulcode.net\">Artful code