Reputation: 17408
I have a python code to test. It's a simple code. The folder structure is as follows.
.
├── code
│ ├── conf.json
│ ├── __init__.py
│ └── a.py
└── test
├── __init__.py
├── a_test.py
Code in a.py:
import json
conf_path = "conf.json"
def run():
with open(conf_oath,'r') as f:
conf = json.load(f)
print(conf)
Code in a_test.py:
import unittest
from os import sys, path
sys.path.append('../code')
from code import a
class Test(unittest.TestCase):
def test_run():
conf = a.run()
print(conf)
if __name__ == '__main__':
unittest.main()
When I run python -m unittest test.a_test
I get the following error -
No such file or directory: 'conf.json'
Where am I going wrong ? How to rectify this ?
Upvotes: 1
Views: 5321
Reputation: 1261
The path of the file is relative to where you execute the test from and not where the test file is located. You can instead get the full path to the file using the os library.
import json
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
conf_path = os.path.join(dir_path, 'conf.json')
def run():
with open(conf_path, 'r') as f:
conf = json.load(f)
print(conf)
Upvotes: 5