@MasterCopipaster

Как замокать путь для os.curdir в тесте?

Доброе время суток, у меня есть вот такой простой класс который просто создает файл на диске

import os


class DiskPid:
    """
    Responsible for creating the process ID file - this is necessary so that you can send signals to
    the process in the demon mode
    """
    __POSTFIX = '.pid'
    __file = None

    @staticmethod
    def set():
        """
        Installs the file with the process ID
        :return:
        """
        pid = os.getpid()
        root = os.path.abspath(os.curdir)
        DiskPid.__file = os.path.join(root, "storage", str(pid) + DiskPid.__POSTFIX)
        with open(DiskPid.__file, 'w') as file:
            pass

    @staticmethod
    def unset():
        """
        Delete the file with the process ID
        :return:
        """
        try:
            os.remove(DiskPid.__file)
        except FileNotFoundError:
            pass  # Just skip if the file is not found
        except Exception as e:
            print(f"An error occurred while deleting the file {DiskPid.__file}: {e}")


Мне нужно написать unittest который проверит работу этого класса
Сам тест у меня получился едва ли сложнее чем класс

import unittest
import os
from src.kernel.store.disk.disk_pid import DiskPid


class TestDiskPid(unittest.TestCase):
    """
    Unit tests for DiskPid class.
    """

    def testSetAndUnset(self):
        """
        Test the normal operation of setting and unsetting the pid file.
        """
        # Call the set method to create a pid file
        DiskPid.set()

        # Verify the file was created
        self.assertTrue(os.path.exists(DiskPid._DiskPid__file))

        # Call the unset method to delete the pid file
        DiskPid.unset()

        # Verify the file was deleted
        self.assertFalse(os.path.exists(DiskPid._DiskPid__file))


if __name__ == '__main__':
    unittest.main()


однако при запуске в тестируемом классе
root = os.path.abspath(os.curdir)

определяется не от корня проекта а от корня файла с тестом

root
     ./store
     ./tests/disk/test_disk_pid.py

Должен быть определен обсалютный путь от ./store
но определяется абсолютный путь от ./tests/disk/
Получается что когда запускаешь код он ищет файл /var/project/store/files.pid
но если запускаешь тест он ищет файл /var/project/tests/disk/store/files.pid
Подскажите пожалуйста как это можно победить что бы путь к папке в тесте был такой же как и при запуске программы?
  • Вопрос задан
  • 48 просмотров
Решения вопроса 1
Vindicar
@Vindicar
RTFM!
Просто сменить текущий рабочий каталог самому?
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы