简体   繁体   中英

FIle Not Found - Python Unit Test

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 ?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM