I have a super simple test framework in VSCode as follows:
/.vscode
launch.json
settings.json
/python
/resources
data.csv
/src
myapp.py
/test
test_config.py
test_myapp.py
/venv
setting.json
has:
"python.testing.unittestEnabled": false,
"python.testing.pytestEnabled": true,
"python.testing.pytestArgs": [
"."
],
(The following doesn’t even work when unittestEnabled: true)
launch.json
includes:
"cwd": "${workspaceFolder}/python",
"env": {
"PYTHONPATH": "${cwd}"
}
myapp.py
is one simple class/function to test:
import pandas as pd
import sys
sys.path.insert(0, '../src')
class MyApp():
def __init__(self):
self.constant = 42
def get_constant(self):
# pd.read_csv('../resources/some_data.tsv', sep='t') ## TODO: please get this working!
return self.constant
test_myapp.py
uses standard unittest framework to test that class:
import unittest
import sys
sys.path.insert(0, '../src')
from myapp import MyApp
class Test_MyApp(unittest.TestCase):
def test_main_program_loads(self):
app = MyApp()
print(app.get_constant)
self.assertEqual(app.get_constant(), 42)
if __name__ == '__main__':
unittest.main()
In both these files I’ve added sys.path.insert(0, '../src')
so the code/test can be run individually using the ‘play’ button in VSCode title-tab bar.
Following this answer /a/75565473/2523501 I added test_config.py
which got the test passing visually in Testing sidebar (they break without it):
from pathlib import Path
import os
import sys
main_folder = Path(__file__).parent.parent
sys.path.insert(0, str(main_folder))
sys.path.insert(0, str(main_folder / 'src'))
sys.path.insert(0, str(main_folder / 'test'))
sys.path.insert(0, str(main_folder / 'resources'))
os.chdir(main_folder)
No __init__.py
‘s required.
However! As soon as I try and use data.csv
(i.e. uncomment line 10) the Testing UI framework shows failed tests despite the ‘play’ button on both myapp.py and test_myapp.py still working.
Error ends with:
FileNotFoundError: [Errno 2] No such file or directory: '../resources/some_data.tsv'
1
pathlib
is a great library to work with relative and absolute paths. You can try for example to write your file myapp.py
as follows:
import pandas as pd
import sys
sys.path.insert(0, '../src')
from pathlib import Path
CURRENT_FPATH = Path(__file__).parent # src
class MyApp():
def __init__(self):
self.constant = 42
def get_constant(self):
csv_path = CURRENT_FPATH.parent / "resources" / "data.csv"
pd.read_csv(csv_path, sep="t")
return self.constant
Note: in the directory tree, the csv file is located in resources/data.csv
and in your code in resources/some_data.tsv
.