簡體   English   中英

在Perl單元測試期間更改環境變量

[英]Change Environment Variables During Perl Unit Testing

我正在嘗試為此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 pathelse path進行單元測試,但是,如果我根本不需要更改processBuildSubs.pm代碼,則對我來說是最好的。 這是我目前無法控制的外部文件。 我只是負責對它進行單元測試(盡管我確實知道,如果我們也可以更改源代碼,可以對其進行更有效的測試)。

因此,為了測試兩個路徑,我們需要相應地設置環境變量URI_BASEURI_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文件中設置環境。

如果可以提供更多信息,請告訴我。

您是否不想為單獨的測試環境使用單獨的腳本?

# 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 ...

通過在BEGIN塊中設置%ENV ,在加載任何其他模塊之前,可以在編譯時將不同的環境變量提供給其他模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM