Tuesday, March 18, 2008

PHP Test Trick

This is a trick that works in a lot of languages. Say you have a file containing a library that also has some utility in it's own right. As an example, I wrote a metadata parser at Grooveshark called MetaShark. It's basically a file containing a bunch of "utility functions" that are invoked via a call to main() inside of the file. It came time to write a unit test for the parser, but I didn't want to call main() from inside of the test suite because that would have the unwanted side effect of processing the current batch of jobs. Instead I want to test the methods individually and make MetaShark just work as a library. All you have to do to make this work is something simple like this:

if ($argv[0] == basename(__FILE__)) {
main();
}

or in Ruby:

if __FILE__ == $0
main()
end

Extrapolate to your language of choice.

1 comment:

ps axu -o user | grep -i root said...

For python:

if __name__ == '__main__' :
main()