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

Writing tests in Mojolicious for checking type of file attachment fails

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

代码如下:

#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);

看了这里 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);

这解决了问题。