unit testing a Minion task

60 views
Skip to first unread message

Sandeep Chayapathi

unread,
Dec 5, 2016, 9:07:33 PM12/5/16
to Mojolicious
Hi all
  I have a minion task that downloads an image,  crops it and saves to a AWS S3 bucket. I want to unit test this code to make sure 
   a. the image is cropped
   b. writes to S3 without any issue

  whats the best strategy to test this code ? Any tips / hints are welcome. The Minion task looks like this

package Acme::Task::ImageCrop;
use Mojo::Base 'Mojolicious::Plugin';
use XML::FeedPP;
use Mojo::UserAgent;
use Imager;
use File::Fetch;
use File::Temp qw/ tempdir tempfile /;


sub register {
 
my ($self, $app) = @_;
 
  $app
->minion->add_task(image_crop => \&image_crop);
}


sub image_crop {
   
eval{
        _image_crop
(@_);
   
};


   
if($@){
        $_
[0]->app->log->debug("Error: " . $@);
   
}
}


sub _image_crop {
   
my $job = shift;
   
my $url = shift;
   
my $id = shift;


    $job
->app->log->debug("cropping " . $url . " , id: " . $id);


   
# download url to a temporary folder
   
my $dir = tempdir(CLEANUP => 1);


    $job
->app->log->debug( "temp dir : " . $dir);


   
my $where =  File::Fetch
                       
->new( uri => $url )
                       
->fetch( to => $dir );
   


   
# create 2 crops - original size (to strip metadata) and a thumbnail
   
my $src_image = Imager->new(file => $where) or die Imager->errstr;


   
my $thumbnail = $src_image->scale( xpixels => 160 );
   
my $original = $src_image->copy();


   
my ($t_fh, $thumbnail_file) = tempfile( DIR => $dir, SUFFIX => ".png", CLEANUP => 1 );
   
my ($o_fh, $original_file) = tempfile( DIR => $dir, SUFFIX => ".png", CLEANUP => 1 ) ;


    $thumbnail
->write( file => $thumbnail_file ) or die $thumbnail->errstr;
    $original
->write( file => $original_file ) or die $original->errstr;




   
# store them in S3
   
my $bucket_name =  "files";


   
my $bucket = $job->app->s3->bucket($bucket_name) or
           
die $job->app->s3->err . ": " . $job->app->s3->errstr;


    $bucket
->add_key_filename($id . '/orig.png', $original_file,
                               
{content_type => 'image/png'})
               
or die $job->app->s3->err . ": " . $job->app->s3->errstr;


    $bucket
->add_key_filename($id . '/thumbnail.png', $thumbnail_file,
                               
{content_type => 'image/png'})
               
or die $job->app->s3->err . ": " . $job->app->s3->errstr;


    $job
->app->log->debug("Finished cropping and uploading image");


   
File::Temp::cleanup();
}


1;

Paul Williams

unread,
Dec 15, 2016, 11:28:48 AM12/15/16
to Mojolicious
You should create this as a standalone Perl module and test it as you would any other Perl module (Acme::ImageCrop).

Once you've done that, use Acme::ImageCrop in the task, and pass in the relevant arguments.
Reply all
Reply to author
Forward
0 new messages