For details about how to write unit test cases in Django and use test_setting and test runner for testing, see the adventures of Django unit test.
CodeIt's easy to understand. I don't have to explain it. If you need to copy the file and modify it as needed, it is not difficult.
Test_settings.py
Coverage_modules = [ ' Testapp. Models ' , ' Testapp. Lib ' , ' Testapp. Common ' ]
Test_runner= 'Testapp. testrunner. test_runner_with_coverage'
Testrunner. py
Code Import OS, shutil, sys, unittest
# look for coverage. py in _ file _/lib as well as sys. path
sys. path = [OS. path. join (OS. path. dirname ( __ file __ ), " lib " )] + sys. path
FromCoverageImportCoverage
FromInspectImportGetmembers, ismodule
FromDjango. Test. SimpleImportRun_tests as django_test_runner
FromDjango. confImportSettings
Def Get_all_coverage_modules (module_path ):
"""
Returns all possible modules to report coverage on, even if they
Aren't loaded.
"""
App_path = Module_path.split ( ' . ' )
App_package = _ Import __ (Module_path, {},{}, app_path [ - 1 ])
App_dirpath = App_package. _ Path __ [ - 1 ]
Mod_list = []
For Root, dirs, files In OS. Walk (app_dirpath ):
Root_path = App_path + Root [Len (app_dirpath):]. Split (OS. Path. SEP )[ 1 :]
For File In Files:
If File. Lower (). endswith ( ' . Py ' ):
Mod_name = File [: - 3 ]. Lower ()
Try :
MoD = _ Import __ ( ' . ' . Join (root_path + [Mod_name]), {},{},
Mod_name)
Except Importerror:
Pass
Else :
Mod_list.append (MOD)
ReturnMod_list
Def Test_runner_with_coverage (test_labels, verbosity = 1 , Interactive = True, extra_tests = []):
""" Custom test runner. follows the Django. Test. Simple. run_tests () interface. """
# Start code coverage before anything else if necessary
Cov = None
If Hasattr (settings, ' Coverage_modules ' ):
Cov = Coverage ()
Cov. use_cache ( 1 ) # Do not cache any of the coverage. py stuff
# Cov. exclude ('If _ name _ =. _ main __.:')
Cov. Start ()
Test_results=Django_test_runner (test_labels, verbosity, interactive, extra_tests)
#Stop code coverage after tests have completed
IfHasattr (settings,'Coverage_modules'):
Cov. Stop ()
# Print Code metrics Header
Print ''
Print ' ---------------------------------------------------------------------- '
Print ' Unit test code coverage results '
Print ' ---------------------------------------------------------------------- '
# Report code coverage metrics
If Hasattr (settings, ' Coverage_modules ' ):
Coverage_modules = []
For Module In Settings. coverage_modules:
Coverage_modules.extend (get_all_coverage_modules (module ))
cov. report (coverage_modules, show_missing = 1 )
# cov.html _ report (directory = 'covhtml ')
# cov. combine ()
cov. save ()
#Print Code metrics footer
Print '----------------------------------------------------------------------'
ReturnTest_results