aboutsummaryrefslogtreecommitdiff
path: root/testrunner.scm
blob: c3fa0ae30baba31458fbb04f5420efa3f044ecad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#!/usr/bin/env bash
# -*- mode: scheme; geiser-scheme-implementation: guile -*-

make calp unit-test-deps

root=$(dirname "$(realpath "$0")")
eval "$(env __PRINT_ENVIRONMENT=1 ${root}/calp)"


exec "$GUILE" --debug --no-auto-compile -e main -s "$0" "$@"
!#

;;; Commentary:
;;; Code:

(use-modules (glob)
             (system vm coverage)
             (srfi srfi-1)
             (srfi srfi-18)
             (srfi srfi-64)
             (srfi srfi-71)
             ((hnh util) :select (->> for group-by))
             (hnh util path)
             (hnh util type)
             ((hnh util lens) :select (modify cdr* car* compose-lenses))
             (hnh util object)
             (hnh util coverage)
             (ice-9 getopt-long)
             (ice-9 control)
             (ice-9 format))



(define-syntax with-mutex
  (syntax-rules ()
    ((_ mutex body ...)
     (dynamic-wind
       (lambda () (mutex-lock! mutex))
       (lambda () body ...)
       (lambda () (mutex-unlock! mutex))))))

(define-syntax-rule (begin-thread forms ...)
  (let ((thread (make-thread (lambda () forms ...))))
    (thread-start! thread)
    thread))



(define print
  (let ((lock (make-mutex)))
    (lambda (string)
      (with-mutex lock
        (display string)))))

(define (println x) (print (format #f "~a~%" x)))

(define (module->source-file module-name)
  ;; Guile has `module-filepath` built in, but that returns paths relative
  ;; to ONE of the items in %load-path, and we wont know which one.
  (realpath
   (string-append
    (path-join
     (cons "module"
           (map symbol->string module-name)))
    ".scm")))

(define current-filename (make-parameter #f))

(define (construct-test-runner)
  (define runner (test-runner-null))
  (test-runner-aux-value!
   runner
   `((thread-name . ,(thread-name (current-thread)))))
  #;
  (test-runner-on-test-begin! runner
    (lambda (runner)
      (test-runner-aux-value! runner #t)))
  (test-runner-on-test-end! runner
    (lambda (runner)
      (case (test-result-kind runner)
        ((pass)
         (if (getenv "VERBOSE")
             (println (format #f "~a SUCCEED ~a"
                              (current-filename)
                              (test-runner-test-name runner)))
             (display #\#)))
        ((fail)
         (println (format #f "~a FAIL ~a"
                          (current-filename)
                          (test-runner-test-name runner))))
        ((xpass xfail skip)
         (println (format #f "~a ~a ~a"
                          (current-filename)
                          (test-result-kind runner)
                          (test-runner-test-name runner)))))))
  runner)


(define (test-runner-processed runner)
  (+ (test-runner-pass-count runner)
     (test-runner-fail-count runner)
     (test-runner-xfail-count runner)
     (test-runner-skip-count runner)))


;;; TODO this procedure is also present (albeit embedded) in (hnh test testrunner). Make it a procedure
(define (test-runner-test-description runner)
  (format #f
          "~a (~a) ~a"
          (assoc-ref (test-runner-aux-value runner) 'thread-name)
          (test-runner-processed runner)
          (cond ((test-runner-test-name runner)
                 (negate string-null?) => identity)
                (else
                 (string-join (test-runner-group-path runner) " → ")))))

(define runners '())
(define runner-mutex (make-mutex))
(sigaction SIGINT
(lambda _
    (display
    (string-join (map test-runner-test-description runners) "\n"))))


(define-type (job)
  (jobname type: string?)
  (job-thunk type: thunk?))


(define* (maybe-with-code-coverage thunk key: (coverage? #f))
  (if coverage?
      (with-code-coverage
       (lambda () (catch #t thunk (lambda _ #f))))
      (values #f (catch #t thunk (lambda _ #f)))))

(define* (prepare-jobs test-files key: (coverage? #f))
  (for entry in test-files
       (job
        jobname: (basename entry)
        job-thunk:
        (lambda ()
          (parameterize ((current-filename (basename entry)))
            (test-begin entry)
            (with-mutex runner-mutex
              (set! runners (cons (test-runner-get) runners)))
            (let ((coverage module-names
                            (maybe-with-code-coverage
                             (lambda () (load entry))
                             coverage?: coverage?)))
              (let ((tested-files (map module->source-file module-names)))
                (test-end entry)
                (println (format #f "Completed ~a" entry))
                (if coverage
                    (let ((lcov-data
                           (call-with-output-string
                             (lambda (port) (coverage-data->lcov coverage port)))))
                      (filter (lambda (coverage)
                                (member (filename coverage)
                                        tested-files))
                              (parse-coverage lcov-data)))
                    '()))))))))


(define* (make-work-pool jobs key: (thread-count 1))
  (define job-pool jobs)
  (define pool-mutex (make-mutex))

  (define results (list))
  (define results-mutex (make-mutex))

  (define (pool-worker)
    (call/ec
     (lambda (return)
       (while #t
         (let ((job (with-mutex pool-mutex
                      (if (null? job-pool)
                          (return #f)
                          (let ((job (car job-pool)))
                            (set! job-pool (cdr job-pool))
                            job)))))
           (catch #t
             (lambda ()
               (let ((result ((job-thunk job))))
                 (with-mutex results-mutex
                   (set! results (cons result results)))))
             (lambda args
               (println (format #f "Job [~a] failed: ~s"
                                (jobname job)
                                ;; TODO better error formatting
                                args)))))))))

  (define threads (map (lambda (i) (make-thread pool-worker (format #f "Worker ~a" i)))
                       (iota thread-count)))

  (for-each thread-start! threads)

  (begin-thread (for-each thread-join! threads)
                results))


;;; Checks if the given argument is truthy.
;;; Raises 'wrong-number-of-args otherwise.
(define-syntax-rule (assert-arg name)
  (unless name
    (scm-error 'wrong-number-of-args "run-tests"
               "Missing required argument ~a"
               '(name) #f)))




(define option-spec
  '((help (single-char #\h))
    (verbose (single-char #\v))
    (suite (value #t))
    (file (value #t))
    (list (single-char #\l))
    (nice (value #t))
    (threads (value #t))
    (coverage (value optional))
    ))

(define help "
run-unit-tests [flags ...]

Run calp's unit tests. While running, Ctrl-C prints the current
status of each file's tests.

Flags:
--help|-h
  print this help
--verbose|-v
  Enables verbose output. This can also be done by setting the
  environment variable VERBOSE.
--suite
  Limit execution to a single test suite. Should be given as a
  directory, and that directory should contain a number of test
  files. See files in tests/unit for available suites.
  Mutualy exclusive with --file.
--file
  Only runs tests from the given file.
  Mutually exlusive with --suite.
--list|-l
  Don't run test, but list all files which would have been ran.
--nice
  How much do incrument the nice value
--threads
  How many threads to spawn for running tests.
--coverage [output-filename]
  Generate code coverage data, this causes the tests to be quite
  a bit slower.
")


(define (main args)
  (define options (getopt-long args option-spec))

  (when (option-ref options 'help #f)
    (display help)
    (exit 0))

  (when (option-ref options 'verbose #f)
    (setenv "VERBOSE" "1"))

  (define test-files
    (cond ((option-ref options 'suite #f)
           => (lambda (suite)
                (glob (path-append suite "*"))))
          ((option-ref options 'file #f) => list)
          (else (glob "tests/unit/**/*.scm"))))

  (nice (string->number (option-ref options 'nice "10")))

  (test-runner-factory construct-test-runner)

  (define coverage
    (let ((cov (option-ref options 'coverage #f)))
      (cond ((string? cov) cov)
            (cov "coverage.info")
            (else #f))))

  ((@ (hnh util exceptions) warnings-are-errors) #t)

  (if (option-ref options 'list #f)
      (format #t "Gathered the following tests:~%~y~%" test-files)
      (let ((results (thread-join!
                      (make-work-pool
                       (prepare-jobs test-files coverage?: coverage)
                       thread-count: (string->number
                                      (option-ref options 'threads "1"))))))
        (define merged-coverages
          (map (lambda (group) (reduce merge-coverage #f (cdr group)))
               (group-by filename (concatenate results))))

        (unless (null? merged-coverages)
          (with-output-to-file coverage
            (lambda ()
              (display "TN:") (newline)
              (for-each output-coverage merged-coverages)))))))