Home > OS >  How can I load all fixtures inside particular directory while writing TestCases in Django using Pyte
How can I load all fixtures inside particular directory while writing TestCases in Django using Pyte

Time:12-21

I have multiple fixtures(json files) inside admin folder and I need to load all the fixtures of that directory without manually writing all fixture's locations.

I have tried the below code but it's not working

@pytest.fixture(scope='session')
def load_admin_data(django_db_setup, django_db_blocker):
    fixtures = [
        'fixtures_for_tests/admin/*.json'
    ]

    with django_db_blocker.unblock():
        call_command('loaddata', *fixtures)

I need to give each and every fixture's location like shown below:

@pytest.fixture(scope='session')
def load_admin_data(django_db_setup, django_db_blocker):
    fixtures = [
        'fixtures_for_tests/admin/data1.json',
        'fixtures_for_tests/admin/data2.json',
    ]

    with django_db_blocker.unblock():
        call_command('loaddata', *fixtures)

Note: One approach which I figure out is to get all fixture locations using some script

is there any other way to give fixture location using some regex pattern while loaddata?

I'm expecting that I'm able to give a dynamic path or regex pattern of fixture location

CodePudding user response:

You can use glob from python which is used to return all file paths that match a specific pattern

import glob

@pytest.fixture(scope="session")
def load_admin_data(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        for json_file in glob.glob('fixtures_for_tests/admin/*'):
            call_command('loaddata',json_file)

Also if you want to add more folders, you can do it by

import glob

@pytest.fixture(scope="session")
def django_db_setup1(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        call_command('loaddata',
                     glob.glob('fixtures_for_tests/basic_fixtures/*'), glob.glob('fixtures_for_tests/admins/*'))
  • Related