(define-module (tests)
  #:use-module (ice-9 exceptions)
  #:use-module (fibers)
  #:use-module (knots)
  #:export (run-fibers-for-tests
            assert-no-heap-growth))

(define* (run-fibers-for-tests thunk #:key (drain? #t))
  (let ((result
         (run-fibers
          (lambda ()
            (with-exception-handler
                (lambda (exn)
                  exn)
              (lambda ()
                (simple-format #t "running ~A\n" thunk)
                (with-exception-handler
                    (lambda (exn)
                      (print-backtrace-and-exception/knots exn)
                      (raise-exception exn))
                  (lambda ()
                    (start-stack #t (thunk))))
                #t)
              #:unwind? #t))
          #:hz 0
          #:parallelism 1
          #:drain? drain?)))
    (if (exception? result)
        (raise-exception result)
        result)))

(define (assert-no-heap-growth thunk)
  (thunk))
