J
J
Jekson2021-09-16 10:02:58
Python
Jekson, 2021-09-16 10:02:58

Pytest: how to lock a method variable?

There is a dzhangovsky manager command in which the csv file is processed.
app/my_app/my_command.py

class Command(BaseCommand):
    def handle(self,  *args, **options):
        path = (os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv'))
        # остальная логика


I am writing a pytest test for it, the problem is that I can’t figure out how to lock the path variable so that the test does not refer to the real data.csv, but to a temporary test file

@pytest.fixture
def create_test_csv_file(tmpdir_factory):
    # логка по созданию и заполнению тестового файла
    # фикстура возвращает путь к тестовому файлу
    return str(path)

@pytest.mark.django_db
def test_function(mocker, create_test_csv_file):
   # здесь как то надо замокать path 
   что то типа mock_path =  create_test_csv_file
    call_command('my_command')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jekson, 2021-09-16
@Lepilov

Michael thanks for the help. It looks like you still have to change the manager command. Now I settled on such a solution through an additional variable with a default value, maybe it will come in handy for someone

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--path",
            dest="path",
            default=os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')
        )

    def handle(self, *args, **options):
        path = options.get("path")
        ...

Call in test
call_command('my_command', path=create_test_csv_file)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question