mercredi 1 juin 2016

How to correctly setup a path relative to running script also in tests?

In order to set some paths to access subdirectories of my app (like locale/), I use this in a settings.py:

__process_name = os.path.basename(sys.argv[0])
__abspath = os.path.abspath(sys.argv[0])
__l1 = len(__process_name)
__l2 = len(__abspath)
rootdir = __abspath[:__l2-__l1]

And then, for instance to access to data/:

datadir = rootdir + "data/"

Problem is, when I run this settings.py when I run the tests (e.g. python3 -m py.test), then sys.argv[0] doesn't match myapp anymore and the tests script can't access data/.

I wonder how to deal with this, for instance:

  • Is there a way to get the same rootdir from both myapp and the tests suite?
  • Or, should I keep settings.py for myapp only, and provide the tests suite with the correct (hardcoded) rootdir?
  • Or define a installdir in a configuration file, that would be setup during installation and then used by both my app (instead of the snippet above) and its tests suite?
  • I also thought about replacing sys.argv[0] by 'myappname', but, as there are different directories having the same name, it's not sure to get the right one. (Plus, what if there is one installed version and one dev version at another place: how to make the distinction between them?)

So, what would be the best way to handle this?

Aucun commentaire:

Enregistrer un commentaire