Is using Python modules main function for validation testing a bad idea?
Question: I'll quickly explain exactly what I mean by this.

I'm working on a project using python, where I have multiple modules doing
segments of work. Let's say for example I have a module called `Parser.py` and
this module has a function `parseFile()` which my main module `Main.py` calls
in order to parse some files.

As of right now, I'm using a main method inside of the Parser.py

    
    
    if __name__ == "__main__":
        line_list = parseFile(sys.argv[1])
    
        out_file = open(sys.argv[2], "w")
        for i in range(len(line_list)):
            out_file.write(line_list[i].get_string(True))
    

It's not important what exactly the parsing does, but the important part is if
you call it, the first argument will be the input file for the parsing, the
second argument is the output file for parsing.

So, what I'm doing essentially, is I'm using a batch file to validate the
results of my parser by a typical input, output, baseline system...

    
    
    ECHO Set the test, source, input, output and baseline directories
    set TESTDIR=%CD%
    set SRCDIR=%CD%\..\pypro\src
    set INDIR=%CD%\input
    set OUTDIR=%CD%\output
    set BASEDIR=%CD%\baseline
    
    
    :: Parser.py main method is base for unit testing on parsing
    ECHO Begin Parser testing
    cd %INDIR%\Parser
    FOR %%G IN (*.psma) DO %SRCDIR%\Parser.py %%G %OUTDIR%\Parser\%%G
    ECHO Parser testing complete
    
    cd %TESTDIR%
    
    "C:\Program Files\WinMerge\winmergeU.exe" "%OUTDIR%"  "%BASEDIR%" 
    

As you can see it diffs the results against the baseline, so if anything is
changed the programmer knows it is no longer valid, or the requirements are
wrong.

Is there anything wrong with this method? I did it because it would be easy.
My plan is to continue doing this with as many modules that I can which are
valid and make sense to do this way, as well as a suite of pyunit tests inside
pydev...


Answer: I think it's a good idea, and it does seem to be a common use case for `if
__name__ == '__main__'` construct. Though this is a more usual structure:

    
    
    def main(argv=None):
        if argv is None:
            argv = sys.argv
        # etc.
    
    if __name__ == "__main__":
        sys.exit(main() or 0)
    

This gives you the additional flexibility to use your `main` from within the
interactive interpreter. There are a few more nice examples from Guido and
others
[here](http://www.artima.com/forums/flat.jsp?forum=106&thread=4829&start=15&msRange=15).

