Search code examples
testingmoduleraku

Raku generic code to test if modules load


This is a generic code code in /t to test if .rakumod modules in /lib load.

use lib $*PROGRAM.sibling('../lib');
use Test;

my @dir = dir($*PROGRAM.sibling('../lib'), test => { $_ ~~ /.*rakumod/  } );
plan @dir.elems;

sub module( IO $dir ) {
  $dir.basename.Str ~~ /(\w+)\.rakumod/;
  return $0.Str;
}

for  @dir.map(&module) -> $module {
  use-ok $module, "This module loads: $module";
}

Before going any further (recursively looking at lib sub-folders ), I wonder in this is the right approach.

Thanks!


Solution

  • If you are testing a well-formed distribution then you should be using:

    use lib $*PROGRAM.parent(2);
    

    By pointing use lib at the directory containing your META6.json instead of the lib directory you help ensure that the provides entry of the META6.json file is up to date (since files not listed in the META6.json but that do exist inside lib won't be seen).

    (I'd even take it one step further and say don't use use lib '...' at all, and instead run your tests using raku -I .... For instance -- what if you want to run these tests (for whatever reason) on the installed copy of some distribution?)

    With that said you could skip the directory recursion by using the META6 data. One method would be to read the META6.json directly, but a better way of doing so would be to get the module names from the distribution itself:

    # file: zef/t/my-test.t
    # cwd: zef/
    
    use lib $*PROGRAM.parent(2); # or better: raku -I. t/my-test.t
    use Test;
    
    my $known-module = CompUnit::DependencySpecification.new(short-name => "Zef");
    my $comp-unit    = $*REPO.resolve($known-module);
    my @module-names = $comp-unit.distribution.meta<provides>.keys;
    
    use-ok($_) for @module-names;