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?

2
  • Should the projects the scripts come from be testing them? Commented Jul 18, 2013 at 20:07
  • 1
    If not the project that the script is from, then what should test the script? Commented Jul 18, 2013 at 20:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.