Skip to content

Instantly share code, notes, and snippets.

@codyc4321
Created March 23, 2016 16:17
Show Gist options
  • Save codyc4321/81cbb25f99f2af709c03 to your computer and use it in GitHub Desktop.
Save codyc4321/81cbb25f99f2af709c03 to your computer and use it in GitHub Desktop.
test all your models with model_mommy, see which ones need special self referencing FK support or which one can't find the db table
#!/usr/bin/env python
# coding: utf-8
import os, sys, subprocess, time, re, ast
HOMEPATH = os.path.expanduser("~")
PROJECT_PATH = "{}/path/".format(HOMEPATH)
MOMMY_PATH = os.path.join(PROJECT_PATH, "yourpath/model_mommy")
MOMMY_TESTPATH = os.path.join(MOMMY_PATH, "tests")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your.project.settings")
import django
django.setup()
from django.apps import apps
import ipdb; ipdb.set_trace()
from clientsite.utils import write_content, append_content
model_info = apps.all_models
MAIN_IMPORT = """\
from django.test import TestCase
from clientsite.{app}.models import (
{models}
)
from model_mommy import mommy
"""
TEST_BLOCK = """\
class {base_model}MommyCreationTests(TestCase):
def setUp(self):
self.model = {base_model}
def test_mommy_creates(self):
x = mommy.make(self.model)
x.save()
self.assertTrue(x.pk)
def test_mommy_isinstance(self):
x = mommy.make(self.model)
self.assertTrue(isinstance(x, self.model))
"""
def generate_models_import_statement(app_name, classes):
def process_names(classes):
starter = ",\n ".join(classes)
final = " " + starter + "\n"
final_without_extra_newline = final[:-1]
return final_without_extra_newline
processed_classes = process_names(classes)
return MAIN_IMPORT.format(app=app_name, models=processed_classes)
def generate_test_writepath(app_name):
filename = "test_" + app_name + "_mommy_creation.py"
return os.path.join(MOMMY_TESTPATH, filename)
for app_name in model_info:
writepath = generate_test_writepath(app_name)
models_ordereddict = model_info[app_name]
if models_ordereddict:
model_names = []
for model_name in models_ordereddict:
model = models_ordereddict[model_name]
correct_name = model.__name__
model_names.append(correct_name)
import_statement = generate_models_import_statement(app_name, model_names)
write_content(writepath, import_statement)
for name in model_names:
append_content(writepath, TEST_BLOCK.format(base_model=name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment