-1

I have the next tree:

root_project/
├── app
│   ├── default_photo_profile.jpg
│   ├── config.py
│   ├── __main__.py  # My app are python package, I'm runnig it via "python -m"
│   └── ...
├── tests
│   ├── test_unit.py  # import config.py inside
│   ├── functional  # import config.py inside
│   ├── pytest.ini
│   └── ...
...

Currently default_photo_profile causing error because tests doesn't have this file.

Reading file in config.py:


DEFAULT_PHOTO_FILE_PATH = Path('default_photo.jpg')
with open(file=DEFAULT_PHOTO_FILE_PATH, mode='rb') as file_obj:
    DEFAULT_PHOTO_BYTES = file_obj.read()

How I can solve this?

I tried:

  1. Patch access to default_photo.jpg with fixture - not helped, error during import stage, not executiion.
  2. set flag to pytest comamnd line: --rootdir app - not helped (don't know why).
  3. try/except for reading the file in app.config.py - may help but it's not my intention, I really want raise error if file not found
  4. Put default_photo.jpg inside EVERY test directory - will help bit dirty.
  5. Patch os.path like suggested in https://stackoverflow.com/a/43003192/11277611 - dirty
  6. Include tests into package (move __main__.py into root_project - not sure that it's a good idea (have not enough experience to decide).
  7. Set absolut path to default_photo.jpg - will fail on the production server.

Probably adoptable solutions (What I want):

  1. Set root dir to root_project.app somehow inside pytest.ini to immitate regular execution.
  2. Set root dir to root_project.tests somehow to place file in root of tests and access from any of tests folder.
salius
  • 918
  • 1
  • 14
  • 30

1 Answers1

0

Try to use following code in config.py:

DEFAULT_PHOTO_FILE_PATH = Path(__file__).parent / 'default_photo.jpg'
with open(file=DEFAULT_PHOTO_FILE_PATH, mode='rb') as file_obj:
    DEFAULT_PHOTO_BYTES = file_obj.read()

Is it what you are trying to achieve?

pL3b
  • 1,155
  • 1
  • 3
  • 18
  • No! It will not help if I will run tests from non root directory, i.e. `python -m pytest /tests/functional/users/foo` – salius Dec 07 '22 at 13:06
  • Did you check it? `Path(__file__)` is independent from workdir. I have tried `pytest D:\repos\stackoverflow\tests\functional\users\foo` which contains test that is using `from app.config import DEFAULT_PHOTO_BYTES` (config is in D:\repos\stackoverflow\app\config.py) – pL3b Dec 07 '22 at 14:47