Django

Code

Changeset 3689

Show
Ignore:
Timestamp:
08/31/06 09:29:47 (2 years ago)
Author:
russellm
Message:

Refs #2333 - Added more documentation for testing framework, and clarified some code as a result of trying to describe it.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/test/simple.py

    r3658 r3689  
    6262        suite.addTest(test) 
    6363 
    64     old_name = create_test_db(verbosity) 
     64    old_name = settings.DATABASE_NAME 
     65    create_test_db(verbosity) 
    6566    management.syncdb(verbosity, interactive=False) 
    6667    unittest.TextTestRunner(verbosity=verbosity).run(suite) 
  • django/trunk/django/test/utils.py

    r3673 r3689  
    5151                
    5252    connection.close() 
    53     old_database_name = settings.DATABASE_NAME 
    5453    settings.DATABASE_NAME = TEST_DATABASE_NAME 
    5554 
     
    5756    # the side effect of initializing the test database. 
    5857    cursor = connection.cursor() 
    59              
    60     return old_database_name 
    6158 
    6259def destroy_test_db(old_database_name, verbosity=1): 
  • django/trunk/docs/django-admin.txt

    r3678 r3689  
    346346options. 
    347347 
     348--noinput 
     349--------- 
     350 
     351Inform django-admin that the user should NOT be prompted for any input. Useful if 
     352the django-admin script will be executed as an unattended, automated script. 
     353 
     354--noreload 
     355---------- 
     356 
     357Disable the use of the auto-reloader when running the development server. 
     358 
    348359--version 
    349360--------- 
     
    355366    0.9.1 
    356367    0.9.1 (SVN) 
     368 
     369--verbosity 
     370----------- 
     371 
     372Example usage:: 
     373 
     374    django-admin.py syncdb --verbosity=2 
     375 
     376Verbosity determines the amount of notification and debug information that  
     377will be printed to the console. '0' is no output, '1' is normal output, 
     378and `2` is verbose output. 
    357379 
    358380Extra niceties 
  • django/trunk/docs/settings.txt

    r3643 r3689  
    755755.. _How invalid variables are handled: http://www.djangoproject.com/documentation/templates_python/#how-invalid-variables-are-handled 
    756756 
     757TEST_RUNNER 
     758----------- 
     759 
     760**New in Django development version** 
     761 
     762Default: ``'django.test.simple.run_tests'`` 
     763 
     764The name of the method to use for starting the test suite. See  
     765`Testing Django Applications`_. 
     766 
     767.. _Testing Django Applications: ../testing/ 
     768 
    757769TIME_FORMAT 
    758770----------- 
  • django/trunk/docs/testing.txt

    r3678 r3689  
    55**New in Django development version**. 
    66 
    7 .. XXX insert quick introduction to testing (and why you'd want to do it) 
    8  
    9 .. note:: 
    10      
     7Automated testing is an extremely useful weapon in the bug-killing arsenal 
     8of the modern developer. When initially writing code, a test suite can be 
     9used to validate that code behaves as expected. When refactoring or 
     10modifying code, tests serve as a guide to ensure that behavior hasn't 
     11changed as a result of the refactor. 
     12 
     13Testing an web application is a complex task, as there are many 
     14components of a web application that must be validated and tested. To 
     15help you test your application, Django provides a test execution 
     16framework, and range of utilities that can be used to stimulate and 
     17inspect various facets of a web application. 
     18 
    1119    This testing framework is currently under development, and may change 
    12     slightly before the next official Django release.   
    13      
     20    slightly before the next official Django release. 
     21 
    1422    (That's *no* excuse not to write tests, though!) 
    1523 
     
    2432Doctests use Python's standard doctest_ module, which searches for tests in 
    2533your docstrings. Django's test runner looks for doctests in your ``models.py`` 
    26 file, and executes any that it finds. 
     34file, and executes any that it finds. Django will also search for a file 
     35called ``tests.py`` in the application directory (i.e., the directory that 
     36holds ``models.py``). If a ``tests.py`` is found, it will also be searched 
     37for doctests. 
    2738 
    2839.. admonition:: What's a **docstring**? 
     
    3041    A good explanation of docstrings (and some guidlines for using them 
    3142    effectively) can be found in :PEP:`257`: 
    32          
    33         A docstring is a string literal that occurs as the first statement in  
     43 
     44        A docstring is a string literal that occurs as the first statement in 
    3445        a module, function, class, or method definition.  Such a docstring 
    3546        becomes the ``__doc__`` special attribute of that object. 
    36          
     47 
    3748    Since tests often make great documentation, doctest lets you put your 
    3849    tests directly in your docstrings. 
     
    4556 
    4657    from django.db import model 
    47      
     58 
    4859    class Animal(models.Model): 
    4960        """ 
    5061        An animal that knows how to make noise 
    51          
     62 
    5263        # Create some animals 
    5364        >>> lion = Animal.objects.create(name="lion", sound="roar") 
    5465        >>> cat = Animal.objects.create(name="cat", sound="meow") 
    55          
     66 
    5667        # Make 'em speak 
    5768        >>> lion.speak() 
     
    6071        'The cat says "meow"' 
    6172        """ 
    62          
     73 
    6374        name = models.CharField(maxlength=20) 
    6475        sound = models.CharField(maxlength=20) 
    65          
     76 
    6677        def speak(self): 
    6778            return 'The %s says "%s"' % (self.name, self.sound) 
     
    8192 
    8293Like doctests, Django's unit tests use a standard library module: unittest_. 
    83 Django's test runner looks for unit test cases in a ``tests.py`` file in your 
    84 app (i.e. in the same directory as your ``models.py`` file)
     94As with doctests, Django's test runner looks for any unit test cases defined 
     95in ``models.py``, or in a ``tests.py`` file in your application directory
    8596 
    8697An equivalent unittest test case for the above example would look like:: 
     
    8899    import unittest 
    89100    from myapp.models import Animal 
    90      
     101 
    91102    class AnimalTestCase(unittest.TestCase): 
    92          
     103 
    93104        def setUp(self): 
    94105            self.lion = Animal.objects.create(name="lion", sound="roar") 
    95106            self.cat = Animal.objects.create(name="cat", sound="meow") 
    96          
     107 
    97108        def testSpeaking(self): 
    98109            self.assertEquals(self.lion.speak(), 'The lion says "roar"') 
    99110            self.assertEquals(self.cat.speak(), 'The cat says "meow"') 
    100              
     111 
    101112When you `run your tests`_, the test utility will find all the test cases 
    102113(that is, subclasses of ``unittest.TestCase``) in ``tests.py``, automatically 
     
    120131write. 
    121132 
    122 For developers new to testing, however, this choice can seem  
     133For developers new to testing, however, this choice can seem 
    123134confusing, so here are a few key differences to help you decide weather 
    124135doctests or unit tests are right for you. 
     
    137148coming from Java.  Since ``unittest`` is inspired by Java's JUnit, if 
    138149you've used testing frameworks in other languages that similarly were 
    139 inspired by JUnit, ``unittest`` should also feel pretty familiar.   
     150inspired by JUnit, ``unittest`` should also feel pretty familiar. 
    140151 
    141152Since ``unittest`` is organized around classes and methods, if you need 
    142153to write a bunch of tests that all share similar code, you can easily use 
    143 subclass to abstract common tasks; this makes test code shorter and cleaner.  
     154subclass to abstract common tasks; this makes test code shorter and cleaner. 
    144155There's also support for explicit setup and/or cleanup routines, which give 
    145156you a high level of control over the environment your test cases run in. 
     
    149160in different circumstances. 
    150161 
     162Testing utilities 
     163================= 
     164 
     165Test Client 
     166----------- 
     167 
     168A dummy browser; instruments the template generation process... 
     169 
     170Fixtures 
     171-------- 
     172 
     173Feature still to come... 
     174 
     175 
    151176Running tests 
    152177============= 
     
    156181    $ ./manage.py test 
    157182 
    158 You'll see a bunch of text flow by as the test database is created, models are 
    159 initialized, and your tests are run. If everything goes well, at the end 
    160 you'll see:: 
     183If you only want to run tests for a particular application, add the 
     184application name to the command line. For example, if your 
     185``INSTALLED_APPS`` contains ``myproject.polls`` and ``myproject.animals``, 
     186but you only want to run the animals unit tests, run:: 
     187 
     188    $ ./manage.py test animals 
     189 
     190When you run your tests, you'll see a bunch of text flow by as the test 
     191database is created and models are initialized. This test database is 
     192created from scratch every time you run your tests. The test database 
     193gets its name by prepending ``test_`` to the database name specified by 
     194``settings.DATABASE_NAME``; all other database settings will the same as 
     195they would be for the project normally. 
     196 
     197Once the test database has been established, Django will run your tests. 
     198If everything goes well, at the end you'll see:: 
    161199 
    162200    ---------------------------------------------------------------------- 
     
    190228 
    191229    FAILED (failures=1) 
    192      
     230 
     231When the tests have all been executed, the test database is destroyed. 
     232 
     233Using a different testing framework 
     234=================================== 
     235 
     236Doctest and Unittest are not the only Python testing frameworks. While 
     237Django doesn't provide explicit support these alternative frameworks, 
     238it does provide a mechanism to allow you to invoke tests constructed for 
     239an alternative framework as if they were normal Django tests. 
     240 
     241When you run ``./manage.py test``, Django looks at the ``TEST_RUNNER`` 
     242setting to determine what to do. By default, ``TEST_RUNNER`` points to ``django.test.simple.run_tests``. This method defines the default Django 
     243testing behaviour. This behaviour involves: 
     244 
     245#. Creating the test database 
     246#. Running ``syncdb`` to install models and initial data into the test database 
     247#. Looking for Unit Tests and Doctests in ``models.py`` and ``tests.py`` file for each installed application 
     248#. Running the Unit Tests and Doctests that are found 
     249#. Destroying the test database. 
     250 
     251If you define your own test runner method and point ``TEST_RUNNER`` 
     252at that method, Django will execute your test runner whenever you run 
     253``./manage.py test``. In this way, it is possible to use any test 
     254framework that can be executed from Python code. 
     255 
     256Defining a test runner 
     257---------------------- 
     258By convention, a test runner should be called ``run_tests``; however, you 
     259can call it anything you want. The only requirement is that it accept two 
     260arguments: 
     261 
     262``run_tests(module_list, verbosity=1)`` 
     263~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     264 
     265The module list is the list of Python modules that contain the models to be 
     266tested. This is the same format returned by ``django.db.models.get_apps()`` 
     267 
     268Verbosity determines the amount of debug information that will be 
     269provided to the console; '0' is no output, '1' is normal output, 
     270and `2` is verbose output. 
     271 
     272Testing utilities 
     273----------------- 
     274 
     275To assist in the creation of your own test runner, Django provides 
     276a number of utility methods in the ``django.test.utils`` module. 
     277 
     278``create_test_db(verbosity=1, autoclobber=False)``: 
     279~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     280 
     281Creates a new test database, and run ``syncdb`` against it. 
     282 
     283``verbosity`` has the same behaviour as in the test runner. 
     284 
     285``Autoclobber`` describes the behavior that will occur if a database with 
     286the same name as the test database is discovered. If ``autoclobber`` is False, 
     287the user will be asked to approve destroying the existing database. ``sys.exit`` 
     288is called if the user does not approve. If autoclobber is ``True``, the database 
     289will be destroyed without consulting the user. 
     290 
     291``create_test_db()`` has the side effect of modifying 
     292``settings.DATABASE_NAME`` to match the name of the test database. 
     293 
     294``destroy_test_db(old_database_name, verbosity=1)``: 
     295~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
     296 
     297Destroys the database with the name ``settings.DATABASE_NAME`` matching, 
     298and restores the value of ``settings.DATABASE_NAME`` to the provided name. 
     299 
     300``verbosity`` has the same behaviour as in the test runner.