Getting current test name and directory

It can be the case that while writing a test you need to know what’s the current test name or directory. Perhaps to write an output file or to adapt your shared code to a particularity of a given test.

The naïve approach would be to just pass your test name to the function that needs it, or perhaps define a global variable with the test name.

However, we can get that information more elegantly by using a bit of python introspection. For this we will use the sys module and the inspect module to get the path to the test file being executed as such:

  1. def testFilePath():
  2.     import sys, inspect
  3.     return inspect.getfile(sys.modules['__main__'])

It works because the main module of a python script is the module where the main program is executed. It represents the module that is created by the very first script that was called. In squish this is the file where your test is defined.

Having that we can get the directory in which the test is saved:

  1. def testDirPath():
  2.     return os.path.dirname(testFilePath())

And knowing that the test name is the directory name in which the test file is saved we can get it as such:

  1. def testName():
  2.     return os.path.basename(testDirPath())