Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override Perl's open() function but use the same filehandle for testing?

I am currently adding some unit tests to some legacy code and I find myself with the need to override an open function. The 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 a file handle that I have provided from my tests rather than what it thinks its opening.

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

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

... it does work and the code in test finishes up reading from my test file. However it will only continue to work as long as I use the same filehandle name "F" as the code in test.

If there a way to make this test code less fragile so that if the filehandle name is changed in the live code the test won't fail?

Thanks

like image 335
Vagnerr Avatar asked Jan 24 '23 03:01

Vagnerr


1 Answers

Why don't you simply use the parameters your live code provides to open?

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

Keep in mind that this will break horribly as soon as you use the three-argument-form of open. If anything, this question offers yet more prove that the three-argument version is superior.

like image 129
innaM Avatar answered Jan 29 '23 22:01

innaM