Commits

kkub...@bcc190cf-cafb-0310-a4f2-bffc1f526a37  committed b3fdd7e

[gsoc2009-testing] Add test_models loading code. Not very clean yet, but it works

  • Participants
  • Parent commits 059d740
  • Branches soc2009/test-improvements

Comments (0)

Files changed (4)

File django/test/testcases.py

               named fixtures.
             * If the Test Case class has a 'urls' member, replace the
               ROOT_URLCONF with it.
+            * If the Test Case class has a 'test_models' member, load the relivent
+              named models.
             * Clearing the mail test outbox.
         """
+        self._test_model_setup()
         self._fixture_setup()
         self._urlconf_setup()
         mail.outbox = []
             # that we're using *args and **kwargs together.
             call_command('loaddata', *self.fixtures, **{'verbosity': 0})
 
+    def _test_model_setup(self):
+        if hasattr(self, 'test_models'):
+            print self.test_models
+            if self.__module__.endswith('tests'):
+                app_label = self.__module__.split('.')[:-1][-1]
+            else:
+                app_label = self.__module__.split('.')[:-2][-1]
+            from django.db.models.loading import cache
+            from django.utils import importlib
+            from django.db import models
+            #importlib.import_module()
+            cache.write_lock.acquire()
+            try:
+                app_mods = cache.app_models[app_label]
+                for tm in self.test_models:
+                    print "importing %s " % tm
+                    im = importlib.import_module(tm)
+                    #cache.app_store[im] = len(cache.app_store)
+                    print "finding model classes"
+                    mod_classes =  [f for f in im.__dict__.values() if hasattr(f,'__bases__') and issubclass(f,models.Model)]
+                    print "Found models %s " % mod_classes
+                    for mc in mod_classes:
+                        print "Adding %s to AppCache" % mc
+                        app_mods[mc.__name__.lower()] = mc
+            finally:
+                cache.write_lock.release()
+            #call_command('syncdb', **{'verbosity': 0})
+        
+        
     def _urlconf_setup(self):
         if hasattr(self, 'urls'):
             self._old_root_urlconf = settings.ROOT_URLCONF
 
             * Putting back the original ROOT_URLCONF if it was changed.
         """
+        self._test_model_teardown()
         self._fixture_teardown()
         self._urlconf_teardown()
 
     def _fixture_teardown(self):
         pass
 
+    def _test_model_teardown(self):
+        if hasattr(self, 'test_models'):
+            print self.test_models
+            if self.__module__.endswith('tests'):
+                app_label = self.__module__.split('.')[:-1][-1]
+            else:
+                app_label = self.__module__.split('.')[:-2][-1]
+            from django.db.models.loading import cache
+            from django.utils import importlib
+            from django.db import models
+            #importlib.import_module()
+            # cc = cache.get_app(app_label)
+            #            del cache.app_store[cc]
+            #            #del cache.app_models[app_label]
+            #            cache.loaded = False
+            #            print cache.handled
+            #            print '.'.join(cc.__name__.split('.')[:-1])
+            #            print cc.__package__
+            #            del cache.handled[cc.__package__]
+            #            cache._populate()
+            #            print cache.get_app(app_label)
+            #cc = cache.get_app(app_label)
+            
+            #reload(cache.get_app(app_label))
+            cache.write_lock.acquire()
+            try:
+               app_mods = cache.app_models[app_label]
+               print app_mods
+               for tm in self.test_models:
+                   print "importing %s " % tm
+                   im = importlib.import_module(tm)
+                   #cache.app_store[im] = len(cache.app_store)
+                   print "finding model classes"
+                   mod_classes =  [f for f in im.__dict__.values() if hasattr(f,'__bases__') and issubclass(f,models.Model)]
+                   print "Found models %s " % mod_classes
+                   for mc in mod_classes:
+                       print "Deleting %s from AppCache" % mc
+                       del app_mods[mc.__name__.lower()]
+            finally:
+               cache.write_lock.release()
     def _urlconf_teardown(self):
         if hasattr(self, '_old_root_urlconf'):
             settings.ROOT_URLCONF = self._old_root_urlconf

File tests/regressiontests/admin_views/test_models.py

+# -*- coding: utf-8 -*-
+import tempfile
+import os
+from django.core.files.storage import FileSystemStorage
+from django.db import models
+from django.contrib import admin
+from django.core.mail import EmailMessage
+
+class SectionTest(models.Model):
+    """
+    A simple section that links to articles, to test linking to related items
+    in admin views.
+    """
+    name = models.CharField(max_length=100)
+
+admin.site.register(SectionTest, save_as=True)

File tests/regressiontests/admin_views/tests.py

     Person, Persona, Picture, Podcast, Section, Subscriber, Vodcast, \
     Language, Collector, Widget, Grommet, DooHickey, FancyDoodad, Whatsit
 
+from test_models import SectionTest
+
 try:
     set
 except NameError:
 
 class AdminViewBasicTest(TestCase):
     fixtures = ['admin-views-users.xml', 'admin-views-colors.xml', 'admin-views-fabrics.xml']
-
+    test_models = ['regressiontests.admin_views.test_models']
     # Store the bit of the URL where the admin is registered as a class
     # variable. That way we can test a second AdminSite just by subclassing
     # this test case and changing urlbit.
     urlbit = 'admin'
 
     def setUp(self):
+        from django.contrib import admin
+        admin.autodiscover()
         self.client.login(username='super', password='secret')
 
     def tearDown(self):
+        from django.contrib import admin
+        admin.autodiscover()
         self.client.logout()
 
     def testTrailingSlashRequired(self):
         response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit)
         self.failUnlessEqual(response.status_code, 200)
 
+    def testBasicAddGetTest(self):
+        """
+        A smoke test to ensure GET on the add_view works.
+        """
+        response = self.client.get('/test_admin/%s/admin_views/sectiontest/add/' % self.urlbit)
+        self.failUnlessEqual(response.status_code, 200)
+    
     def testAddWithGETArgs(self):
         response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'})
         self.failUnlessEqual(response.status_code, 200)
         self.client.login(username='super', password='secret')
         response = self.client.get('/test_admin/%s/my_view/' % self.urlbit)
         self.assert_(response.content == "Django is a magical pony!", response.content)
+    
+    def testBasicAddGetTest(self):
+        """
+        A smoke test to ensure GET on the add_view works.
+        """
+        response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit)
+        self.failUnlessEqual(response.status_code, 200)
 
 def get_perm(Model, perm):
     """Return the permission object, for the Model"""
 
     def tearDown(self):
         self.client.logout()
-
+        
+    def testBasicAddGetTest(self):
+        """
+        A smoke test to ensure GET on the add_view works.
+        """
+        from django.contrib import admin
+        admin.site.unregister(SectionTest)
+        import regressiontests.admin_views.urls
+        reload(regressiontests.admin_views.urls)
+        response = self.client.get('/test_admin/admin/admin_views/sectiontest/add/')
+        self.failUnlessEqual(response.status_code, 404)
+        
     def test_get_change_view(self):
         "Retrieving the object using urlencoded form of primary key should work"
         response = self.client.get('/test_admin/admin/admin_views/modelwithstringprimarykey/%s/' % quote(self.pk))

File tests/runtests.py

 #!/usr/bin/env python
-
 import os, sys, traceback
 import unittest
 import django