Skip to content

Instantly share code, notes, and snippets.

@andreoss
Created April 26, 2021 00:51
Show Gist options
  • Save andreoss/8dcf79f37ba40dc80c09d452e056d3a6 to your computer and use it in GitHub Desktop.
Save andreoss/8dcf79f37ba40dc80c09d452e056d3a6 to your computer and use it in GitHub Desktop.
Migrate to Junit 5
#!/usr/bin/env perl
use strict;
use File::Find ();
use feature qw(say);
use Carp qw(croak);
use Data::Dumper;
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
sub wanted;
File::Find::find( { wanted => \&wanted }, $ENV{PWD} );
exit;
sub convert_expected {
my %params = @_;
print Dumper( \%params );
say "----";
say "----";
my $result;
if ( $params{expected_type} ) {
$params{doc} =~ s/\n^ \s* [*] \s* [@]throws .*?\s*$//xmgs;
$result = sprintf "%s\t\@Test\n\tvoid %s() { \t %s \n\t}",
$params{doc} || "", $params{test_name},
sprintf(
"\n\t\tAssertions.assertThrows(\n\t\t\t%s,\n\t\t\t() -> {%s\t\t\t}\n\t\t);",
$params{expected_type}, $params{body} =~ s/^/\t\t/gmr );
}
else {
$result = sprintf "%s\t\@Test\n\tvoid %s()%s { \t %s \n\t}",
$params{doc} || "", $params{test_name},
$params{throws} || '',
$params{body};
}
$result =~ s/\t/ /g;
return $result;
}
sub extract_imports {
my $code = shift;
my @result = ( $code =~ m/^import \s (\S+)[;]/xmg );
return \@result;
}
sub handle {
my $name = shift;
my $code = slurp($name);
my $imports = extract_imports($code);
$code =~ s/\n^ import \s \S+ ; $//xmg;
say Dumper($imports);
if ( grep /org.junit.Test/, $imports->@* ) {
push $imports->@*, 'org.junit.jupiter.api.Test';
$code =~ s<
(?<doc> \s{4}[/][*][*] .*? [*][/] \s*)
\s{4} [@]Test([(]expected \s* = \s* (?<expected_type>\S+)[)])? \s*
public (\s+ final)? \s+ void \s+ (?<test_name>\S+)[(][)] (?<throws> \s* throws \s+ \S+)? \s* [{] (?<body>.*?) \n\s{4}[}]
><convert_expected(%+)>sxsge;
}
if ( $code =~ /Assertions[.]/ ) {
push $imports->@*, 'org.junit.jupiter.api.Assertions';
}
my $import_block = join( "\n",
map { "import $_;" } sort { $a cmp $b } grep !/org.junit.Test/,
$imports->@* );
$code =~ s/^package \s \S+[;]\n/$&\n$import_block/xmg;
$code =~ s/^public \s (final \s)? class/final class/xm;
spurt( $name, $code );
}
sub wanted {
if ( /Test.java$/s || /ITCase.java$/s ) {
handle($name);
}
}
sub slurp {
my $file = shift;
croak "Unable to read $file" unless -r $file;
open( my $fh, '<', $file ) or croak "Unable to read $file: $!";
local $/ = undef;
my $cont = <$fh>;
close $fh;
return $cont;
}
sub spurt {
my $file = shift;
croak "Unable to write $file" unless -w $file;
open( my $fh, '>', $file ) or croak("$file: $!");
print $fh (@_);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment