[racket] module+ test... (require rackunit) results in unbound identifier when used in macro

From: Stephen Chang (stchang at ccs.neu.edu)
Date: Wed Jan 8 17:29:02 EST 2014

The problem is that check-true (and check-false) are not in scope (as
you discovered) during expansion. Here is one way to fix your problem
by recapturing the test expressions to have the proper context. You
can also use syntax-local-introduce instead of the lambda (someone
correct me if this is not proper usage).

#lang racket
(require (for-syntax syntax/parse))

(define-syntax (define/test stx)
  (syntax-parse stx
    [(_ (id arg ...) body ... #:test test-body ...)
     (with-syntax ([id-str (symbol->string (syntax->datum #'id))]
                   [(new-test-body ...)
                    (map
                     (λ (s) (datum->syntax #'here (syntax->datum s)))
                     (syntax->list #'(test-body ...)))])
       #'(begin
           (define (id arg ...) body ...)
           (print id-str)
           (module+ test
             (require rackunit)
             (test-case id-str
                        new-test-body ...))))]))

(define/test (my-fn a b c)
  (print a)
  (print b)
  (print c)
  #:test
  (check-true #t)
  (check-false #t))

On Wed, Jan 8, 2014 at 4:53 PM, Scott Klarenbach <scott at pointyhat.ca> wrote:
> I have the following macro:
>
> (define-syntax (define/test stx)
>   (syntax-parse stx
> [(_ (id arg ...) body ... #:test test-body ...)
> (with-syntax ([id-str (symbol->string (syntax->datum #'id))])
>   #'(begin
>   (define (id arg ...) body ...)
>   (print id-str)
>   (module+ test
> (require rackunit)
> (test-case id-str
>   test-body ...))))]))
>
> Which handles some testing boilerplate and allows me to use it like so:
>
> (define/test (my-fn a b c)
>   (print a)
>   (print b)
>   (print c)
>   #:test
>   (check-true #t)
>   (check-false #t))
>
> The problem is that the (require rackunit) expression inside of (module+
> test) is not being picked up after macro expansion.  Running either the code
> or the tests (via raco test) results in: unbound identifier check-true.
>
> Adding (module+ (require rackunit)) to the top of the file solves the
> problem and both the file and tests run as expected.
>
> What am I missing?
>
> Thanks.
> --
> Talk to you soon,
>
> Scott Klarenbach
>
> PointyHat Software Corp.
> www.pointyhat.ca
> p 604-568-4280
> e scott at pointyhat.ca
> 200-1575 W. Georgia
> Vancouver, BC V6G2V3
>
> _______________________________________
> To iterate is human; to recur, divine
>
> ____________________
>   Racket Users list:
>   http://lists.racket-lang.org/users
>


Posted on the users mailing list.