3

I am a newbie , hence any guidance is much appreciated I have a directory structure:

/testcases
 __init__.py, testcases_int/     
                  tc1.py,tc2.py,__init__.py,run.py

My intent is to run each of these tc1.py, tc2.py .. tc(x).py(x= new file will be added on need basis) by run.py I have existing code in run.py and tcx.py as :

#!/usr/bin/env python
import os,glob,subprocess
for name in glob.glob('tc*.py'):
  cmd = 'python name'
  subprocess.call(cmd)

#!/usr/bin/env python
import os,fabric,sys
class tc(object):
  def __init__(self):
     .....
  def step1(self):
     .....
  def step2(self):
     .....
  def runner(self):
     self.step1()
     self.step2()   

However I do not intend to run it as above, instead want to import the classes of tc(x).py into run.py and invoke 'runner' method of each tc(x).py class

I could statically import each of the tc1.py ,tc2.py into run.py, but this directory will keep growing with tc(x).py files, hence I want every time when run.py is executed: -- it will dynamically load all the tc(x).py -- instantiate the class of tc(x).py -- invoke its 'runner' method

Thanks much in advance

pysql
  • 55
  • 9
  • Scratch what I said before. Is there anything else in your modules? or just the classes themselves? (and are they always called tc? are there multiple classes etc...) – NDevox Apr 20 '15 at 15:10
  • Does the run script have to be in `testcases_int`? – Holloway Apr 20 '15 at 15:31

3 Answers3

0

This is a great time to look at the unittest and nose modules to handle testing. Both offer easy ways to automatically discover new tests based on (among other things) the name of the file. For example, all files that begin with tc or test_.

paidhima
  • 2,312
  • 16
  • 13
0

I'd recommend looking at unittest (and similar) modules as paidhima said, but if you want to do it this way, the following isn't particularly elegant, but works for my limited testing assuming you can put the run script in the testcases directory.

folder layout

testcases/
|-- run.py
`-- tests
    |-- __init__.py
    |-- tc1.py
    `-- tc2.py
run.py
import tests
from tests import *

for tc in tests.__all__:
    getattr(tests,tc).tc().runner()
__init__.py
import glob, os
modules = glob.glob(os.path.dirname(__file__)+"/tc*.py")
__all__ = [ os.path.basename(f)[:-3] for f in modules ]
Holloway
  • 6,412
  • 1
  • 26
  • 33
0

In main run method you can get all files from directory How to list all files of a directory? And in cycle use something like this:

for class_name in list_:
   import class_name
   runner_method = getattr(class_name, "runner", None) # if it staticmethod
   if callable(runner_method): 
      runner_method()

Or you can use __all__ in __init__.py for use import *

Community
  • 1
  • 1
oxana
  • 375
  • 1
  • 3
  • 10
  • Silly of me, I did create list of file names but the getattr did not strike. This worked !! – pysql Apr 22 '15 at 09:45