Jacob Shafi Jacob Shafi - 2 months ago 19
Python Question

Why is my python unittest script calling my script when I am importing it?

I am trying to test a python script and when I import the script into my testing suite, it calls the script. In my example below I import list3rdparty and once I run the test it immediate calls list3rdparty. I do not want this to happen. I would like the test to only call the functions within every test case.

list3rdpartytest.py

import unittest
from list3rdparty import * ## this is where the script is being imported


class TestOutputMethods(unittest.TestCase):


def setUp(self):
pass

def test_no_args_returns_help(self):
args = []
self.assertEqual(get_third_party(args), help())

##get_third_party is a function in list3rdparty##


if __name__ == '__main__':
unittest.main(warnings = False)


list3rdparty.py

def get_third_party(args_array):
##does a bunch of stuff



def get_args():
get_third_party(sys.argv)

get_args()

Answer

You probably have code at the module level which will be executed on import. For example, if you had a file with the following, it will print the string the first time it's imported.

import something
from whatever import another

print 'ding'

To avoid this, put the code inside a block like this:

if __name__ == '__main__':
    # your module-level code here
    get_args()

This will only run the code if it's being called directly from the command line.