Invoking Python scripts from test cases running within a venv

Before the final release, I like to test my Python scripts the way these are supposed to be invoked in actual environment, usually with command line arguments. And this is apart from the unit testing and integration testing that I have for the individual modules. I also use Python venv for development because I don’t like to directly install all the required libs in my operating system, thus keeping the system PATH clean from the development libs. Invoking a Python script within the test cases is easy, you just need to use the os.system() function. But running a Python script from os.system() using the ‘python script-name.py‘ syntax invokes the python executable from the OS even if I am running the outer Python test case from withing a venv.

After looking for a solution for days, I finally found one. It may not be very elegant but it does it’s job and it’s simple. The code looks as below:

import os, sys
executable = sys.executable
result = os.system('{} path-to-your-python-script.py'.format(executable))
assert result == 0

It first gets the Python executable used to run the original script and then use that to invoke the script to test.

Advertisements

I am a software engineer, an open-source enthusiast and a hobbyist blogger.

Tagged with: , , , ,
Posted in Blog, Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: