0

I am looking for an elegant way to detect if my script was ran from a unittest harness or was triggered by normal execution. So far I am looking into the call stack for the 'unittest.py' string. However I am wondering if there is a more pythonic way to achieve the same result.

def hasRunFromUnitTest():
    intest = False
    for path, _, _, _ in traceback.extract_stack():
        if 'unittest.py' in path:
            intest = True
            break
    return intest

Agree with comments below this is clearly a hack however I am using a complex layering of technologies of which I do not always have access to the underlying API/Framework code underneath. In this particular case I have a .Net application launching a custom python environment which is used to build .Net UI. At times the underlying .NET process is never killed on application exit and I need to manually kill it this has the side effect of of killing my unit test harness as well.

Ideally I would be looking for some kind of property or constant in the unittest class.

2
  • 3
    This seems... somewhat foolish. Why do you think you need this? If the code behaves differently under test, what's the point of testing?!
    – jonrsharpe
    Aug 5, 2015 at 9:47
  • 1
    Why do you want to do that? Checking if your script was run from unittest is not elegant in the first place (IMHO). If you really want to do this anyway I think a solution similar to your is the way to do it.
    – skyking
    Aug 5, 2015 at 9:47

1 Answer 1

2

This might be more "pythonic":

def hasRunFromUnitTest():
    return 'unittest' in sys.modules

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.