Directory Structure:
root-folder/
config-folder/
json-file.config
class-folder/
classfile.py
tests/
pytest-file1.py
json-file.config:
{
"setting1": "value1",
"setting2": "value2"
}
Now, Here I need to access json-file.config in my class file. I do not want to use dbutil, how can i access it and read it from json-file.config in my class file??
- For this task, update contents of your class file as mentioned below.
classfile.py
import os
import json
class myclass:
def __init__(self):
# Get the path of the json-file.config
config_file_path = os.path.join(os.path.dirname(__file__), '..', 'config-folder', 'json-file.config')
# Read the JSON config file
with open(config_file_path, 'r') as file:
self.config = json.load(file)
def get_setting(self, key):
return self.config.get(key, "Setting not found")
Explanation:
os.path.join: Constructs the path to the json-file.config file relative to the location of classfile.py by going up one level (..) and then into the config-folder/.
json.load(file): Reads the content of the json-file.config and loads it into a dictionary.
Usage: You can now access the JSON config in your pytest-file1.py by creating an instance of myclass.
Example usage in pytest-file1.py:
from class_folder.classfile import myclass
def test_read_config():
# Create an instance of the class
obj = myclass()
# Access a specific setting from the config
setting_value = obj.get_setting('setting1')
# Example assertion (for pytest)
assert setting_value == "value1"
