11
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?

vovel
  • 319
  • 3
  • 10

1 Answers1

1

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.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • If the script does not produce output, and instead modifies a database, then what? Normally, I use dependency injection to change the database to a test database that is created in setUp. Is there a way that I can use relative imports to import the script, then do my dependency injection, and then run main(args)? Testing the output is the easy part assuming that it operates on the test database. Ideally, I'd like to continue to use dependency injection. – vovel Jul 19 '13 at 05:43