Jacob Shafi Jacob Shafi - 4 months ago 35
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.


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

class TestOutputMethods(unittest.TestCase):

def setUp(self):

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)


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

def get_args():



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

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