我正在尝试为这个perl模块函数编写一些单元测试,但是我遇到了一些环境变量问题。我将首先列出文件,然后更详细地解释这个问题。
processBuildSubs.pm
package processBuildSubs;
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;
use HTTP::Status;
# Declare environment variables used in this package that are needed
use constant URI_BASE => $ENV {"URI_BASE"};
use constant URI_RESOURCE => $ENV {"URI_RESOURCE"};
# Shell Environment Related Constants visible.
# Make visible.
our $URI_BASE = URI_BASE;
our $URI_RESOURCE = URI_RESOURCE;
sub populatePartitions
{
# Define locals
my $url;
my $ua = new LWP::UserAgent;
$url = "$URI_BASE"."$URI_RESOURCE"."/some/path";
# Make a request to the $url
$res = $ua->request (GET $url);
if ($res->code() != HTTP::Status->RC_OK() )
{
# The request didn't return 200 OK so it's in here now.
}
else
{
# The request returned 200 OK, so now it's here.
}
}
我希望能够对if path
和else path
进行单元测试,但是,如果我不需要更改processBuildSubs.pm
代码,那么对我来说最好所有。这是我目前无法控制的外部文件。我只是负责单元测试它(虽然我知道如果我们也可以更改源代码,它可以更有效地测试。)
因此,为了测试两个路径,我们需要相应地设置环境变量URI_BASE
和URI_RESOURCE
,以便请求失败一次,然后再次成功。 (我有兴趣学习如何在将来的时间中删除此调用,但这是为另一个问题保留的。)
这是我的测试文件:
processBuildSubs.t
use strict;
use Test::More qw(no_plan);
BEGIN { use_ok('processBuildSubs') };
# Test 1 of populatePartitions() function
my $processBuildProdsCall = processBuildSubs::populatePartitions();
is( $populatePartitionsCall, 0, "populatePartitions() Test for 0 Val Passed" );
# Test 2 of populatePartitions() function
# I need to change some environment variables that processBuildSubs depends on here.
my $processBuildProdsCall = processBuildSubs::populatePartitions();
is( $populatePartitionsCall, 0, "populatePartitions() Test for 0 Val Passed" );
我们现在改变环境变量的最佳尝试是使用类似的外部shell脚本(但最好在上面文件中的my
调用之间进行更改):
run_tests.sh
#!/bin/bash
# Run the tests once
perl ./BuildProcess.pl
perl ./Build testcover # Ultimately calls the processBuildSubs.t test file
# Now export some variables so the other test passes.
export URI_BASE="https://some-alias/"
export URI_RESOURCE="some-resource"
# Then run the test suite again with the env set so the else condition passes.
perl ./BuildProcess.pl
perl ./Build testcover
正如您所看到的,这将是一种糟糕的做事方式,因为我们每次都使用不同的环境运行整个测试套件。理想情况下,我们希望在测试之间尽可能在processBuildSubs.t
文件中设置我们的环境。
如果我可以提供任何进一步的信息,请告诉我。
答案 0 :(得分:0)
您是否反对为单独的测试环境设置单独的脚本?
# processBuildSubs.t
BEGIN {
@ENV{"URI_BASE","URI_RESOURCE"} = ("https://some-alias/","some-resource");
}
use Test::More;
... tests go here ...
# processBuildSubs-env2.t
BEGIN {
@ENV{"URI_BASE","URI_RESOURCE"} = ("https://another-alias/","another-resource");
}
use Test::More;
... tests go here ...
通过在%ENV
块中设置BEGIN
,在加载任何其他模块之前,可以在编译时为其他模块提供不同的环境变量。