Home > Blockchain >  Unit-testing a .pl Perl file
Unit-testing a .pl Perl file

Time:02-22

I am brand new to Perl, but am trying to add some functionality to Sanoid (https://github.com/jimsalterjrs/sanoid), which is written in Perl as a single script without .pm Module files (as far as I understand these things).

I wanted to add some simple unit tests to a new subroutine I have added and I was expecting to be able to do this as easily as in Python, where you can just import the name of the other file and test subroutine return values from various inputs.

I have read a number of testing tutorials and think I follow how to do the actual testing, but I'm struggling at the first hurdle of importing the script I want to test.

From what I have read, the main way to import things is to turn it into a .pm module and use it, but I do not want to attempt rearchitecting someone's code just for testing (particularly when I'm so new to Perl). The alternative seems to be to require or do the file, which I understand will execute the file (which isn't ideal as this does things even if called without arguments) and means I need to add a 1; to the end of the file to ensure it returns true when required.

It looks like I can use unless (caller) to rearrange things so that nothing is executed if it is required, but I wanted to check I had not missed something obvious.

CodePudding user response:

There's really no difference between Perl and Python here. Just like in Python, loading a file as a module in Perl executes it.

But just like in Python, you can check if the module was executed as a script or not in Perl.

# Python
if __name__ == "__main__":
   main()
# Perl
main() if !caller();

Such a file is called a "modulino".

That said, I don't like the practice (in either language). If you want a module, write a module. That's just my opinion.

  • Related