在Mojolicious中编写用于检查文件附件类型的测试失败

问题描述:

我正试图在Mojolicious中编写测试以检查图像附件是否从窗体正确发送。 我有一个包含<input type="file" name="image_upload" accept="image/*">的表单。在控制器中,我正在检查$self->req->upload('image_upload')->headers->content_type =~ /image/。另一方面,测试在发布请求内发送图像文件form => {image_upl => { content => 'abc', filename => 'x.png' }}。运行该应用程序运行良好,但该检查在测试代码内部失败。我不太了解如何设置这些标题,以便我可以在发布请求中发送模拟图像。在Mojolicious中编写用于检查文件附件类型的测试失败

下面是代码:

#Router. 
$if_admin->post('/attachment/:page_id/add')->name('on_attachment_add') 
    ->to('attachment#on_add'); 

# Client side (Mojolicious template). 
<%= form_for 'on_attachment_add' => { page_id => $self->stash('id') } 
     => (method => 'POST') => (enctype => "multipart/form-data") 
     => begin %> 
    <input type="file" name="image_upload" accept="image/*"> 
% end 

# Controller (on_add) 
my $self = shift; 
my $image_file = $self->req->upload('image_upload'); 
if (!$image_file || $image_file->slurp eq "" || !$image_file->headers || 
    !$image_file->headers->content_type || 
    !($image_file->headers->content_type =~ /image/)) { 
    $self->render(
    template => 'validation/invalid_data', 
    status => 400 
); 
} 

# test. 
$t->post_ok('/attachment/test_page/add' => form => { 
    image_upload => { content => 'aaa', filename => 'x.png' }, 
    image_name => 'new_image.jpg' 
})->status_is(200); 
+0

这个巨大的条件很难阅读。不是很好维护。 – simbabque

+1

嗯simbabque你是对的,我试图获得MVP,所以我把所有的检查都放在那里。我正在改变它更清楚 – Bianca

看这里http://mojolicious.org/perldoc/Mojo/UserAgent/Transactor#tx后,我加入'Content-Type' => 'image/png'为这种形式的哈希参考:

$t->post_ok('/attachment/test_page/add' => form => { image_upload => 
    { content => 'abc', filename => 'x.png', 'Content-Type' => 'image/png' }, 
    image_name => 'new_image.jpg' 
})->status_is(200); 

这解决了这个问题。