Accessing resource files in Python unit tests & main code -
Accessing resource files in Python unit tests & main code -
i have python project next directory structure:
project/ project/src/ project/src/somecode.py project/src/mypackage/mymodule.py project/src/resources/ project/src/resources/datafile1.txtin mymodule.py, have class (lets phone call "myclass") needs load datafile1.txt. sort of works when do:
open ("../resources/datafile1.txt")
assuming code creates myclass instance created run somecode.py.
the gotcha have unit tests mymodule.py defined in file, , if leave relative pathname described above, unittest code blows code beingness run project/src/mypackage instead of project/src , relative filepath doesn't resolve correctly.
any suggestions best practice type approach resolve problem? if move testcases project/src clutters main source folder testcases.
in each directory contains python scripts, set python module knows path root of hierarchy. can define single global variable relative path. import module in each script. python searches current directory first utilize version of module in current directory, have relative path root of current directory. utilize find other files. example:
# rootpath.py rootpath = "../../../" # in scripts rootpath import rootpath datapath = os.path.join(rootpath, "src/resources/datafile1.txt") if don't want set additional modules in each directory, utilize approach:
put sentinel file in top level of directory structure, e.g. thisisthetop.txt. have python script move directory hierarchy until finds file. write pathnames relative directory.
possibly file have in project directory can used purpose (e.g. maintain moving until find src directory), or can name project directory in such way create apparent.
python unit-testing resources
Comments
Post a Comment