-1

I am writing tests for model_mommy, very useful fake objects for django. I want a fast way to make the script self-sustaining, and it needs to only write tests for your custom apps in your django project. Right now it may find and write tests for all apps you use, like auth and tagging, which you didn't write. You can use the script if you use mommy (or change for mixer, it should work too). What's a smooth way without a messy os.walk to find which apps are actually mine? Thank you

https://gist.github.com/codyc4321/81cbb25f99f2af709c03

codyc4321
  • 9,014
  • 22
  • 92
  • 165
  • is that really unclear? I want to differentiate between custom and 3rd party apps, hopefully right within the `django.apps.apps` feature. that doesn't seem unclear at all – codyc4321 Mar 23 '16 at 16:32

1 Answers1

0
class ModelRunner(object):

    def __init__(self, starting_path):
        self.start_path = starting_path

    @property
    def model_files(self):
        model_files = []
        for root, dirs, files in os.walk(self.start_path):
            for f in files:
                if self.is_regular_models_file(f):
                    filename = os.path.join(root, f)
                    model_files.append(filename)
            for d in dirs:
                if self.is_models_dir(d):
                    model_files.extend(self.get_models_files_from_models_folder(os.path.join(root, d)))
        return model_files

    def get_models_files_from_models_folder(self, filepath):
        for root, _, files in os.walk(filepath):
            model_files = []
            for f in files:
                if f not in ['__init__.py'] and '.pyc' not in f:
                    filename = os.path.join(root, f)
                    model_files.append(filename)
            return model_files

    @property
    def apps(self):
        apps = []
        for f in self.model_files:
            apps.append(self.get_app_name_from_file(f))
        return apps

    def get_app_name_from_file(self, filepath):

        def find_models_dir(path):
            head, name = os.path.split(path)
            return path if name == 'models' else find_models_dir(head)

        if self.is_regular_models_file(filepath):
            head, _ = os.path.split(filepath)
            _, app_name = os.path.split(head)
            return app_name
        else:
            return find_models_dir(filepath)

    def is_regular_models_file(self, filepath):
        return get_filename(filepath) == 'models.py'

    def is_models_dir(self, filepath):
        return get_filename(filepath) == 'models'
codyc4321
  • 9,014
  • 22
  • 92
  • 165