newLISP unit tests

Notices and updates
Locked
kinghajj
Posts: 30
Joined: Sun Jul 15, 2007 2:37 pm

newLISP unit tests

Post by 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

Code: Select all

;; 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.

Code: Select all

(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
Posts: 604
Joined: Sat Apr 07, 2007 2:23 pm
Location: Ohio
Contact:

Post by Jeff »

Very nice. Thank you for your contribution!
Jeff
=====
Old programmers don't die. They just parse on...

Artful code

Locked