How can I override the Perl open () function, but use the same file descriptor for testing?

I am currently adding some unit tests to some deprecated code, and I am in need to override the public function. Live code looks something like this.

if ( !open( F, $filetoopen) ){ # do stuff with <F> } 

What I want to do is make sure that β€œF” contains the file descriptor that I provided from my tests, and not what it considers to be its discovery.

I have the following code in my .t file ...

 BEGIN { *CORE::GLOBAL::open = sub { open(F,$testfiletoopen); }; }; 

... it works, and the code in the test ends up reading from my test file. However, it will continue to work only as long as I use the single file name β€œF” as the code in the test.

If there is a way to make this test code less fragile, so that when the file name changes in live code, the test will not work?

thanks

+4
source share
1 answer

Why don't you just use the options that your live code opens?

 BEGIN { *CORE::GLOBAL::open = sub { open $_[0], $newfilename }; }; 

Keep in mind that this will destroy horribly once you use an open form with three arguments. In any case, this question offers even more confirmation that the version with three arguments is superior.

+9
source

All Articles