Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing python package bin scripts best practice

Tags:

python

testing

myproject/
    bin/
        myscript
    mypackage/
        __init__.py
        core.py
        tests/
            __init__.py
            test_mypackage.py
    setup.py

What is the best way to test the script myscript?

From SO research, it seems the only answer I've found is to write a test in tests called test_myscript and use something like

import subprocess

process = subprocess.Popen('myscript arg1 arg2')
print process.communicate()

in my test case to run the script and then test the results. Is there a better way? Or any other suggestions for different ways? And should I put the test suite in bin/tests or in mypackage/tests?

like image 891
vovel Avatar asked Jul 18 '13 20:07

vovel


1 Answers

I don't believe there is any "best practices" about where to put tests. See how many different opinions are there: Where do the Python unit tests go?

I'd personally have one and only tests directory on the top-level, near your bin and mypackage directories - as, for example, django has.

For running your bin script and getting results you can use:

  • subprocess (as you've mentioned), but using check_output:

    import subprocess
    output = subprocess.check_output("cat /etc/services", shell=True)
    
  • scripttest module

    • was designed to test command-line scripts - looks like the tool for a job
    • also see this article
  • cli and it's cli.test module (haven't ever used personally)

Hope that helps.

like image 167
alecxe Avatar answered Oct 12 '22 23:10

alecxe