Require identifiers not provided by the module in Racket

Let's say I have a.rkt file:

 #lang racket (define a 12) 

Now I want to write some test cases using the b.rkt file, which requires a.rkt :

 #lang racket (require "a.rkt") a 

Is there a way to get b.rkt to recognize the identifier defined in a.rkt without having provide it from the first file? (Ideal without modifying the first file at all.)

I don't see anything in the documentation for require / provision .

+6
source share
2 answers

As Leif mentions, RackUnit require/expose will allow the use of invalid identifiers in other modules, but its own documentation does not promise a very strong guarantee:

Note that require/expose can be a little fragile, especially if it is mixed with compiled code. Use at your own risk!

Another approach would be to use submodules , which can effectively provide an authorized way to export a private API for use in tests or other means.

For example, consider a module that implements a function to check if a string contains one word:

 #lang racket (provide word?) (define (word? str) (not (ormap space? (string->list str)))) (define (space? c) (eq? c #\space)) 

(This is perhaps not the most realistic example, but carry me.)

Perhaps it would be useful to test the space? function space? to make sure it works, but it probably shouldn't be part of the public API. To create an escape-hatch, you can define a submodule that exports this binding:

 (module+ for-testing (provide space?)) 

The name for-testing arbitrary - it can be anything. In any case, you can now require that the submodule in another module gain access to private bindings:

 #lang racket (require rackunit (submod "a.rkt" for-testing)) (check-true (space? #\space)) (check-false (space? #\a)) 

This is a safer way to identify identifiers from modules without exposing them to all consumers.

+5
source

You can use require/expose in b.rkt to access the binding in a.rkt . b.rkt will look something like this:

 #lang racket (require rackunit) (require/expose "a.rkt" (a)) a 
+5
source

All Articles