scoobyrico has asked for the wisdom of the Perl Monks concerning the following question:

I am unit testing a data model in an MVC. What perl module do I use to simulate a file being uploaded from a form? Testing the webpage form itself I would use WWW::Mechanize, but I want to test the model as a stand alone object. Update: I agree with everything you said, however that didn't answer my question. Other than using OPEN, I guess there isn't anything that can help as a test harness to feed files into the api. While this code doesn't answer the question directly if passed into this sub creates the file on the server. Just in case someone was looking for this.
use HTML::TokeParser; # minimalist HTML sanitation/normalization of st +ories use HTML::Entities; # ditto use File::Path; # to save user uploaded media use Path::Class::File; # ditto use Digest::MD5 qw( md5_hex ); # ditto, for creating well-distributed +dir names use Image::Size qw( imgsize ); # capture image dimensions to facilitat +e auto-display sub create { my $self = shift; my $hashref = shift; my $story = $hashref->{'story'} ; my $ext = $hashref->{'ext'} ; my $path = $hashref->{'path'} ; my $width = $hashref->{'width'}; my $height = $hashref->{'height'} ; my $acctid = $hashref->{'acctid'} ; # Sanitize/normalize filename my $name = lc $path; $name =~ s/[^[:print:]¥W]+/_/g; my $path_seed = $acctid . $name; my $md5 = md5_hex($path_seed); my @dirs = ($md5 =~ /^(...)(...)(...)/); my $path_new = Path::Class::File->new(@dirs, $name); my $file_system_path = Path::Class::File->new(Local::Confi +g::MEDIA_DIR_FILE, $path_new->stringify); print STDERR ("Creating directory at $file_system_path¥n") +; eval { mkpath([ $file_system_path->dir ]) }; print STDERR "Opening media file for writing: $file_system +_path¥n"; open my $destination, ">", $file_system_path; my $fh = new IO::File($path, "r") or die "could not open $ +path: $!¥n"; my ( $x, $y ); eval { ( $x, $y ) = imgsize($fh) }; # Might not be an imag +e. while ( <$fh> ) { print $destination $_; } close($destination) or print STDERR ("Could not close $p +ath\n"); my $data_ref = { story => $story, width => $x, height => $y, ext => $ext, path => $path_new->stringify, # Relative path so web s +erver can find it. created => \"NOW()", # " }; #change go ahead and add the data my $schema = Prosper::Base->connect(Local::Config::DNS, Local +::Config::DNS_USERNAME, Local::Config::DNS_PASSWORD); my $media = $schema->resultset("Media")->create( $data_ref); + #add the data to the table return 1; }

Replies are listed 'Best First'.
Re: Unit Testing and adding Files
by moritz (Cardinal) on Feb 05, 2008 at 18:45 UTC
    The model shouldn't have to know about where a file comes from.

    The model has an API, and you should use that to test it.

    Think of the model as being independent from the web front end - ideally it should be.