What is the proper and fail-safe way to open non py file from not current directory?
To be more specific, I have a method, which validates API response with JSON schema, contained in file schema.json:
def foo():
json_data = collect_json_data()
schema = json.load(open('./schema/schema.json'))
jsonschema.validate(json_data, schema)
And got the following project structure:
D:\projects\project-pytest\.
│ .gitignore
│ LICENSE
│ README.md
│ requirenments.txt
│ runner_01.cmd
│ structure.txt
│
├───tests
│ │ runner_02.cmd
│ │ file_with_tests.py
│ │
│ ├───schema
│ │ schema.json
My goal is to run tests not only from the directory project-pytest\tests\
by exectuting command python -m pytest file_with_tests.py
, but also from parent directory, by executing runner_01.cmd
, with command python -m pytest -v .\tests\file_with_tests.py
inside.
Now the second way fails with FileNotFoundError: [Errno 2] No such file or directory: './schema/schema.json'
.
I tried using import os
:
schema_path = os.path.abspath('schema.json')
schema = json.load(open(schema_path))
but in this case absolute path ignores schema.json
parent directory - FileNotFoundError: [Errno 2] No such file or directory: 'D:\\Git\\testarea-pytest\\schema.json'
.
How should I open my schema.json
placed in different sub-directory and be able to run commands:
python -m pytest -v .\tests\file_with_tests.py
from project-pytest
folder
and
python -m pytest -v file_with_tests.py
from project-pytest\tests\
folder
without failing test because of FileNotFoundError
.