1;; run the test suit:
2
3;;; --- helpers for misc tests ---
4(defun princ-error (c) (format t "~&[~A]: ~A~%" (type-of c) c))
5(defmacro handler-return (block value)
6  `(lambda (c) (princ-error c) (return-from ,block ,value)))
7(defmacro check-os-error (form acceptable)
8  (let ((errvar (gensym "ERROR-")))
9    `(handler-case ,form
10       (os-error (,errvar)
11         (princ-error ,errvar)
12         (case (os-error-code ,errvar)
13           (,acceptable T)
14           (t (os-error-code ,errvar)))))))
15(defun show (object &key ((:pretty *print-pretty*) *print-pretty*))
16  "Print the object on its own line and return it. Used in many tests!"
17  (fresh-line) (prin1 object) (terpri) object)
18#+clisp (progn
19(defun kill-down (name)
20  (dolist (f (directory (ext:string-concat name "**/*")))
21    (format t "~&removing file ~S~%" f)
22    (delete-file f)))
23(defun rmrf (name)
24  (ext:dir (ext:string-concat name "**/*"))
25  (ext:dir (ext:string-concat name "**/"))
26  (kill-down name)
27  (dolist (d (directory (ext:string-concat name "**/")))
28    (format t "~&removing directory ~S~%" d)
29    (ext:delete-directory d)))
30(defun prepare-directory (name)
31  (ensure-directories-exist name :verbose t)
32  (kill-down name))
33(defun cmd-args ()
34  "Command and arg list for cloning this clisp process.
35This will not work right after (cd) if -M was a relative pathname."
36  (let* ((argv (ext:argv))
37         (lispinit-pos (position "-M" argv :test #'string=))
38         (lispinit (and lispinit-pos (aref argv (1+ lispinit-pos))))
39         (args (list "-q" "-norc" "-B" (namestring *lib-directory*))))
40    (values (aref argv 0)
41            (if lispinit
42                (nconc args (list "-M" lispinit))
43                args))))
44(export '(kill-down rmrf prepare-directory cmd-args))
45)
46(defun show-file (file)         ; return line count
47  (with-open-file (st file :direction :input)
48    (format t "~&~S: ~:D byte~:P:~%" file (file-length st))
49    (loop :for l = (read-line st nil nil) :while l :count t
50      :do (format t "--> ~S~%" l))))
51(defun finish-file (file) (prog1 (show-file file) (delete-file file)))
52(defun post-compile-file-cleanup (file)
53  (delete-file file)
54  (delete-file (compile-file-pathname file))
55  #+clisp (delete-file (make-pathname :type "lib" :defaults file)))
56(defun symbol-cleanup (s)
57  #+CLISP (proclaim `(ext:notspecial ,s)) ; constants cannot be makunbound
58  #+CLISP (let ((tldl (sys::top-level-declarations)))
59            (when tldl
60              (setf (cdr tldl) (delete s (cdr tldl) :test #'eq))))
61  #+XCL(subr 84 ;sys::%p-set-cdr-content
62              s 0 (sys::%p-get-content 'sys::%void-value 0) 0)
63  #+ALLEGRO (setf (excl::symbol-bit s 'excl::.globally-special.) nil)
64  #+CMU (setf (ext:info variable kind s) ':global)
65  #+SBCL (setf (sb-int:info :variable :kind s) ':global)
66  #+OpenMCL (proclaim `(ccl::notspecial ,s))
67  (setf (find-class s) nil
68        (symbol-plist s) '())
69  (makunbound s)
70  (fmakunbound s)
71  (unintern s))
72(defun symbols-cleanup (l)      ; drop many symbols
73  (loop for s in l unless (symbol-cleanup s) collect s))
74(defvar *run-test-truename*)
75;; export symbols used by tests
76(export '(princ-error show show-file finish-file post-compile-file-cleanup
77          type-error-handler handler-return check-os-error symbols-cleanup
78          symbol-cleanup *run-test-truename* with-ignored-errors diff-seq))
79;;; end helpers
80
81#+OLD-CLISP
82;; Binding *ERROR-HANDLER* is a hammer technique for catching errors. It also
83;; disables CLCS processing and thus breaks tests that rely on the condition
84;; system, such as:
85;;   - the compile-file on structure literal test in clos.lisp
86;;   - all tests that use IGNORE-ERRORS
87(defmacro with-ignored-errors (&rest forms)
88  (let ((b (gensym)))
89    `(BLOCK ,b
90       (LET ((*ERROR-HANDLER*
91              #'(LAMBDA (&REST ARGS)
92                  (with-standard-io-syntax
93                    (let* ((*print-readably* nil)
94                           (error-message (apply #'format nil (cdr args))))
95                      (terpri) (princ error-message)
96                      (return-from ,b (values 'error error-message)))))))
97         ,@forms))))
98
99#+(or (and AKCL (not GCL)) ECL)
100(defmacro with-ignored-errors (&rest forms)
101  (let ((b (gensym))
102        (h (gensym)))
103    `(BLOCK ,b
104       (LET ((,h (SYMBOL-FUNCTION 'SYSTEM:UNIVERSAL-ERROR-HANDLER)))
105         (UNWIND-PROTECT
106           (PROGN (SETF (SYMBOL-FUNCTION 'SYSTEM:UNIVERSAL-ERROR-HANDLER)
107                        #'(LAMBDA (&REST ARGS) (RETURN-FROM ,b 'ERROR)))
108                  ,@forms)
109           (SETF (SYMBOL-FUNCTION 'SYSTEM:UNIVERSAL-ERROR-HANDLER) ,h))))))
110
111#+ALLEGRO
112(defmacro with-ignored-errors (&rest forms)
113  (let ((r (gensym)))
114    `(LET ((,r (MULTIPLE-VALUE-LIST (EXCL:ERRORSET (PROGN ,@forms)))))
115       (IF (CAR ,r) (VALUES-LIST (CDR ,r)) 'ERROR))))
116
117#-(or OLD-CLISP (and AKCL (not GCL)) ECL ALLEGRO)
118(defmacro with-ignored-errors (&rest forms)
119  (let ((b (gensym)))
120    `(BLOCK ,b
121       (HANDLER-BIND
122         ((ERROR #'(LAMBDA (CONDITION)
123                     (PRINC-ERROR CONDITION)
124                     (RETURN-FROM ,b (values 'ERROR
125                                             (princ-to-string condition))))))
126         ,@forms))))
127
128(defun merge-extension (type filename)
129  (make-pathname :type type :defaults filename))
130
131;; (lisp-implementation-type) may return something quite long, e.g.,
132;; on CMUCL it returns "CMU Common Lisp".
133(defvar lisp-implementation
134  #+CLISP "CLISP" #+(and AKCL (not GCL)) "AKCL" #+GCL "GCL" #+ECL "ECL" #+ALLEGRO "ALLEGRO" #+CMU "CMUCL"
135  #-(or CLISP AKCL GCL ECL ALLEGRO CMU) (lisp-implementation-type))
136
137(defvar *eval-method* :eval)
138(defvar *eval-out* nil)
139(defvar *eval-err* nil)
140(defvar *eval-times* nil)
141(defun my-eval (form)
142  (when *eval-out* (get-output-stream-string *eval-out*))
143  (when *eval-err* (get-output-stream-string *eval-err*))
144  (when *eval-times* (setq form `(times ,form)))
145  (ecase *eval-method*
146    (:eval (eval form))
147    (:compile (funcall (compile nil `(lambda () ,form))))
148    (:both (let ((e-value (eval form))
149                 (c-value (funcall (compile nil `(lambda () ,form)))))
150             (unless (equalp e-value c-value)
151               (error "eval: ~S; compile: ~S" e-value c-value))
152             e-value))))
153
154;; compare 2 sequences:
155;; list of (pos first second);
156;; last 3 elements can be smaller length, tail1, tail2
157(defun diff-seq (s1 s2 &key (test #'eql))
158  (let ((pos 0))
159    (nconc
160     (delete nil
161             (map 'list (lambda (e1 e2)
162                          (prog1 (unless (funcall test e1 e2)
163                                   (list pos e1 e2))
164                            (incf pos)))
165                  s1 s2))
166     (let ((l1 (length s1)) (l2 (length s2)))
167       (cond ((< l1 l2) (list l1 nil (subseq s2 l1)))
168             ((< l2 l1) (list l2 (subseq s1 l2) nil)))))))
169
170(defgeneric pretty-compare (result my-result log)
171  (:documentation "print a pretty comparison of two results")
172  (:method ((result sequence) (my-result sequence) (log stream))
173    (let ((pos (mismatch result my-result :test #'equalp)))
174      (let ((*print-length* 10))
175        (if pos
176            (flet ((pretty-tail-10 (seq)
177                     (if (and (> (length seq) (+ pos 10))
178                              (typep seq 'string))
179                         (concatenate 'string (subseq seq pos (+ pos 10)) "...")
180                         (subseq seq pos))))
181              (format log "~&Differ at position ~:D: ~S vs ~S~%CORRECT: ~S~%~7A: ~S~%"
182                      pos
183                      (if (< pos (length result))
184                          (elt result pos) 'end-of-sequence)
185                      (if (< pos (length my-result))
186                          (elt my-result pos) 'end-of-sequence)
187                      (pretty-tail-10 result)
188                      lisp-implementation
189                      (pretty-tail-10 my-result)))
190            (format log "~&Type mismatch: ~S should be ~S~%"
191                    (type-of my-result) (type-of result))))))
192  (:method ((result pathname) (my-result pathname) (log stream))
193    (dolist (slot '(pathname-host pathname-device pathname-directory
194                    pathname-name pathname-type pathname-version))
195      (let ((s-r (funcall slot result)) (s-m (funcall slot my-result)))
196        (format log "~&~S:~%CORRECT: ~S~%~7A: ~S~%~:[ DIFFERENT!~;same~]~%"
197                slot s-r lisp-implementation s-m (equal s-r s-m)))))
198  (:method ((result t) (my-result t) (log stream)))) ; do nothing
199
200(defun type-error-handler (err)
201  "Print the condition and THROW.
202Usage: (handler-bind ((type-error #'type-error-handler)) ...)"
203  (princ-error err)
204  (let ((da (type-error-datum err)) (et (type-error-expected-type err)))
205    (show (list :datum da :expected-type et) :pretty t)
206    (throw 'type-error-handler (typep da et))))
207
208(defvar *test-ignore-errors* t)
209(defvar *test-result-in-file* t
210  "T: CLISP-style: evaluation result in the file after the test form.
211NIL: sacla-style: forms should evaluate to non-NIL.")
212(defun do-test (stream log)
213  (let ((eof stream) (error-count 0) (total-count 0))
214    (loop
215      (let ((form (read stream nil eof)) out err (result nil))
216        (when (or (eq form eof) (eq result eof)) (return))
217        (if *test-result-in-file*
218            (setq result (read stream))
219            (setq form `(not ,form)))
220        (incf total-count)
221        (show form)
222        (multiple-value-bind (my-result error-message)
223            (if *test-ignore-errors*
224                (with-ignored-errors (my-eval form)) ; return ERROR on errors
225                (my-eval form)) ; don't disturb the condition system when testing it!
226          (setq out (and *eval-out* (get-output-stream-string *eval-out*))
227                err (and *eval-err* (get-output-stream-string *eval-err*)))
228          (cond ((eql result my-result)
229                 (format t "~&EQL-OK: ~S~%" result))
230                ((equal result my-result)
231                 (format t "~&EQUAL-OK: ~S~%" result))
232                ((equalp result my-result)
233                 (format t "~&EQUALP-OK: ~S~%" result))
234                (t
235                 (incf error-count)
236                 (format t "~&ERROR!! ~S should be ~S !~%" my-result result)
237                 (format log "~&Form: ~S~%CORRECT: ~S~%~7A: ~S~%~@[~A~%~]"
238                             form result lisp-implementation
239                             my-result error-message)
240                 (pretty-compare result my-result log)
241                 (format log "~[~*~:;OUT:~%~S~%~]~[~*~:;ERR:~%~S~]~2%"
242                         (length out) out (length err) err)
243                 (force-output log))))))
244    (values total-count error-count)))
245
246(defmacro check-ignore-errors (&body body)
247  `(handler-case (progn ,@body)
248     (type-error (c)
249       (if (ignore-errors
250             (typep (type-error-datum c) (type-error-expected-type c)))
251           (format nil "[~S --> ~A]: ~S is of type ~S" ',body c
252                   (type-error-datum c) (type-error-expected-type c))
253           c))
254     (stream-error (c)
255       (if (streamp (stream-error-stream c)) c
256           (format nil "[~S --> ~A]: ~S is not a ~S" ',body c
257                   (stream-error-stream c) 'stream)))
258     (file-error (c)
259       (let ((path (file-error-pathname c)))
260         (if (or (pathnamep path) (stringp path) (characterp path)) c
261             (format nil "[~S --> ~A]: ~S is not a ~S" ',body c
262                     (file-error-pathname c) 'pathname))))
263     (package-error (c)
264       (let ((pack (package-error-package c)))
265         (if (or (packagep pack) (stringp pack) (characterp pack)) c
266             (format nil "[~S --> ~A]: ~S is not a ~S" ',body c
267                     (package-error-package c) 'package))))
268     (cell-error (c)
269       (if (cell-error-name c) c
270           (format nil "[~S --> ~A]: no cell name" ',body c)))
271     (error (c) c)
272     (:no-error (v) (format t "~&no error, value: ~S~%" v))))
273
274(defun do-errcheck (stream log)
275  (let ((eof "EOF") (error-count 0) (total-count 0))
276    (loop
277      (let ((form (read stream nil eof))
278            (errtype (read stream nil eof)))
279        (when (or (eq form eof) (eq errtype eof)) (return))
280        (incf total-count)
281        (show form)
282        (let ((my-result (check-ignore-errors (my-eval form)))
283              (out (and *eval-out* (get-output-stream-string *eval-out*)))
284              (err (and *eval-err* (get-output-stream-string *eval-err*))))
285          (multiple-value-bind (typep-result typep-error)
286              (ignore-errors (typep my-result errtype))
287            (cond ((and (not typep-error) typep-result)
288                   (format t "~&OK: ~S~%" errtype))
289                  (t
290                   (incf error-count)
291                   (format t "~&ERROR!! ~S instead of ~S !~%" my-result errtype)
292                   (format log "~&Form: ~S~%CORRECT: ~S~%~7A: ~S~%~
293                                ~[~*~:;OUT:~%~S~%~]~[~*~:;ERR:~%~S~]~2%"
294                               form errtype lisp-implementation my-result
295                               (length out) out (length err) err)
296                   (force-output log)))))))
297    (values total-count error-count)))
298
299(defvar *run-test-tester* #'do-test)
300(defvar *run-test-type* "tst")
301(defvar *run-test-erg* "erg")
302(defvar *run-test-own-package* t)
303(defun run-test (testname
304                 &key ((:tester *run-test-tester*) *run-test-tester*)
305                      ((:ignore-errors *test-ignore-errors*)
306                        *test-ignore-errors*)
307                      ((:eval-method *eval-method*) *eval-method*)
308                      (logname testname)
309                      ((:own-package *run-test-own-package*)
310                       *run-test-own-package*)
311                      ((:times *eval-times*) *eval-times*)
312                 &aux (logfile (merge-extension *run-test-erg* logname))
313                      error-count total-count *run-test-truename*)
314  (with-open-file (s (merge-extension *run-test-type* testname)
315                     :direction :input)
316    (setq *run-test-truename* (truename s))
317    (format t "~&~s: started ~s~%" 'run-test s)
318    (with-open-file (log logfile :direction :output
319                                 #+(or CMU SBCL) :if-exists
320                                 #+(or CMU SBCL) :supersede
321                                 #+ANSI-CL :if-exists #+ANSI-CL :new-version)
322      (setq logfile (truename log))
323      (let* ((*package*
324              (if *run-test-own-package*
325                  (make-package (namestring logfile)
326                                :use (cons *package*
327                                           (package-use-list *package*)))
328                  *package*))
329             (*print-circle* t) (*print-pretty* nil)
330             (*eval-err* (make-string-output-stream))
331             (*error-output* (make-broadcast-stream *error-output* *eval-err*))
332             (*eval-out* (make-string-output-stream))
333             (*standard-output* (make-broadcast-stream *standard-output*
334                                                       *eval-out*)))
335        (setf (values total-count error-count)
336              (funcall *run-test-tester* s log))
337        (when *run-test-own-package*
338          (delete-package *package*)))))
339  (format t "~&~s: finished ~s (~:d error~:p out of ~:d test~:p)~%"
340          'run-test testname error-count total-count)
341  (if (zerop error-count)
342      (delete-file logfile)
343      (format t "~s: see ~a~%" 'run-test logfile))
344  (list logname total-count error-count))
345
346(defun report-results (res &key (here (truename "./")))
347  "res = list of RUN-TEST return values (testname total-count error-count)"
348  (let ((error-count (reduce #'+ res :key #'third)))
349    (format
350     t "~&finished ~3d file~:p:~31T ~3:d error~:p out of~50T ~6:d test~:p~%"
351     (length res) error-count (reduce #'+ res :key #'second))
352    (loop :for rec :in res :for count :upfrom 1 :do
353      (format t "~&~3d ~25@a:~31T ~3:d error~:p out of~50T ~6:d test~:p~%"
354              count (enough-namestring (first rec) here)
355              (third rec) (second rec)))
356    error-count))
357
358;; see makemake.in:
359;; (run-some-tests :dirlist '("zlib" "pcre") :srcdir "../modules/")
360(defun run-some-tests (&key (dirlist '("./")) (srcdir "./") (outdir "./")
361                       ((:eval-method *eval-method*) *eval-method*))
362  "Run tst files in DIRLIST under SRCDIR, writing erg under OUTDIR."
363  (let ((files
364         (let (#+clisp (custom:*merge-pathnames-ansi* t))
365           (mapcan (lambda (dir)
366                     (directory (make-pathname
367                                 :name :wild :type *run-test-type*
368                                 :defaults (merge-pathnames dir srcdir))))
369                   dirlist)))
370        (src-true (truename srcdir)))
371    (if files
372        (report-results
373         (mapcar (lambda (file)
374                   (run-test file :logname
375                             (merge-pathnames (enough-namestring file src-true)
376                                              outdir)))
377                 files)
378         :here outdir)
379        (warn "no ~S files in directories ~S" *run-test-type* dirlist))))
380
381(defparameter *all-tests*
382  '(#-(or AKCL ECL)   ("alltest")
383                      ("array")
384    #-OpenMCL         ("backquot")
385    #+CLISP           ("bin-io")
386    #-(and AKCL (not GCL)) ("characters")
387    #+(or CLISP ALLEGRO CMU OpenMCL LISPWORKS) ("clos")
388    #+CLISP           ("defhash")
389    #+(and CLISP UNICODE) ("encoding")
390                      ("eval20")
391    #+CLISP           ("ext-clisp")
392    #+(and CLISP FFI) ("ffi")
393                      ("floeps")
394    #-OpenMCL         ("format")
395    #+CLISP           ("genstream")
396    #+(or CLISP XCL)  ("hash")
397                      ("hashlong")
398    #+CLISP           ("hashtable")
399                      ("iofkts")
400                      ("lambda")
401                      ("lists151")
402    #-(or GCL OpenMCL) ("lists152")
403                      ("lists153")
404                      ("lists154")
405                      ("lists155")
406                      ("lists156")
407                      ("list-set")
408    #+(or CLISP GCL ALLEGRO CMU SBCL OpenMCL LISPWORKS) ("loop")
409                      ("macro8")
410                      ("map")
411    #+(or CLISP ALLEGRO OpenMCL LISPWORKS) ("mop")
412                      ("number")
413    #+CLISP           ("number2")
414    #-(or AKCL ALLEGRO CMU OpenMCL) ("pack11")
415    #+(or XCL CLISP)  ("path")
416                      ("readtable")
417    #-CMU             ("setf")
418    #+(and CLISP SOCKETS) ("socket")
419                      ("steele7")
420    #-ALLEGRO         ("streams")
421                      ("streamslong")
422                      ("strings")
423    #-(or AKCL ECL)   ("symbol10")
424                      ("symbols")
425                      ("time")
426    #+XCL             ("tprint")
427                      ("tread")
428                      ("type")
429    #-(or)            ("unportable")
430    #+(and CLISP mt)  ("mt")
431    #+CLISP           ("weak")
432    #+(or CLISP ALLEGRO CMU19 OpenMCL LISPWORKS) ("weakhash")
433    #+(or CLISP LISPWORKS) ("weakhash2")
434                      ("bind" :eval-method :eval :logname "bind-eval")
435                      ("bind" :eval-method :compile :logname "bind-compile")
436    #+(or CLISP ALLEGRO CMU LISPWORKS) ("conditions" :ignore-errors nil)
437    #+CLISP           ("restarts" :ignore-errors nil)
438                      ("excepsit" :tester do-errcheck)
439    ))
440
441(defun test-weakptr ()
442  (let ((tmp (list "weakptr" 0 0)))
443    (dotimes (i 20 tmp)
444      (let ((weak-res (run-test "weakptr")))
445        (incf (second tmp) (second weak-res))
446        (incf (third tmp) (third weak-res))))))
447
448(defun run-all-tests (&key (disable-risky t)
449                      ((:eval-method *eval-method*) *eval-method*))
450  (let ((res ())
451        #+CLISP (custom:*load-paths* nil)
452        (*features* (if disable-risky *features*
453                        (cons :enable-risky-tests *features*))))
454    (dolist (args *all-tests*)
455      (push (apply #'run-test args) res))
456    #+(or CLISP ALLEGRO CMU SBCL LISPWORKS)
457    (push (test-weakptr) res)
458    (report-results (nreverse res))))
459
460#+(and clisp mt)
461(defun run-all-tests-parallel (&key (concurrency 5) (disable-risky t)
462                               ((:eval-method *eval-method*) *eval-method*))
463  (let ((res ()) (lock (mt:make-mutex :name "res"))
464        (total (1+ (length *all-tests*)))
465        (custom:*load-paths* nil)
466        (*features* (if disable-risky *features*
467                        (cons :enable-risky-tests *features*))))
468    (macrolet ((run (body)
469                 `(mt:make-thread
470                   (lambda ()
471                     (let ((ans ,body))
472                       (mt:with-mutex-lock (lock)
473                         (push ans res))))
474                   :cstack-size 16777216)))
475      (dolist (args *all-tests*)
476        (let ((args args))
477          ;; this is "poor man" concurrency control - not exact at all
478          (loop until
479            (>= concurrency
480                (count t (mapcar #'mt:thread-active-p (mt:list-threads))))
481             :do (sleep 1))
482          (run (apply #'run-test args))))
483      (run (test-weakptr))
484      (loop :until (= total (length res)) :do (sleep 1))
485      (report-results (nreverse res)))))
486