django测试入门案例/常见的测试问题/返回空数据/单元测试与客户端&数据库数据/测试工具的使用
MDN系列教程:
Django文档:
其他参考
测试数据库
不会使用“实际”(生产)数据库单独的空白数据库临时数据(需要编写相关代码手动的创建符合测试要求(能够达到测试目的的数据,可能是精心设计的数据,未必是随意产生的数据)!)临时数据库(自动创建)python manage.py shellpython shellpython shellpython manage.py test
> 无论测试是通过还是失败,当所有测试执行完毕后,测试数据库都会被销毁。
test --keepdb
运行测试时从生产数据库中查找数据?
真实的数据库
入门案例
- 编写你的第一个 Django 应用,第 5 部分 | Django 文档 | Django (djangoproject.com)
- 该教程的源代码在github上有相关仓库(注意克隆下来的仓库可能是空的,但是不影响单元测试,数据可以在测试中创建,结束后销毁)
manage.py test 的使用帮助
python manage.py test --help
usage: manage.py test [-h] [--noinput] [--failfast] [--testrunner TESTRUNNER]
[-t TOP_LEVEL] [-p PATTERN] [--keepdb]
[--shuffle [SEED]] [-r] [--debug-mode] [-d]
[--parallel [N]] [--tag TAGS]
[--exclude-tag EXCLUDE_TAGS] [--pdb] [-b]
[--no-faulthandler] [--timing] [-k TEST_NAME_PATTERNS]
[--version] [-v {0,1,2,3}] [--settings SETTINGS]
[--pythonpath PYTHONPATH] [--traceback] [--no-color]
[--force-color]
[test_label ...]
Discover and run tests in the specified modules or the current directory.
positional arguments:
test_label Module paths to test; can be modulename,
modulename.TestCase or modulename.TestCase.test_method
options:
-h, --help show this help message and exit
--noinput, --no-input
Tells Django to NOT prompt the user for input of any
kind.
--failfast Tells Django to stop running the test suite after
first failed test.
--testrunner TESTRUNNER
Tells Django to use specified test runner class
instead of the one specified by the TEST_RUNNER
setting.
-t TOP_LEVEL, --top-level-directory TOP_LEVEL
Top level of project for unittest discovery.
-p PATTERN, --pattern PATTERN
The test matching pattern. Defaults to test*.py.
--keepdb Preserves the test DB between runs.
--shuffle [SEED] Shuffles test case order.
-r, --reverse Reverses test case order.
--debug-mode Sets settings.DEBUG to True.
-d, --debug-sql Prints logged SQL queries on failure.
--parallel [N] Run tests using up to N parallel processes. Use the
value "auto" to run one test process for each
processor core.
--tag TAGS Run only tests with the specified tag. Can be used
multiple times.
--exclude-tag EXCLUDE_TAGS
Do not run tests with the specified tag. Can be used
multiple times.
--pdb Runs a debugger (pdb, or ipdb if installed) on error
or failure.
-b, --buffer Discard output from passing tests.
--no-faulthandler Disables the Python faulthandler module during tests.
--timing Output timings, including database set up and total
run time.
-k TEST_NAME_PATTERNS
Only run test methods and classes that match the
pattern or substring. Can be used multiple times. Same
as unittest -k option.
--version Show program's version number and exit.
-v {0,1,2,3}, --verbosity {0,1,2,3}
Verbosity level; 0=minimal output, 1=normal output,
2=verbose output, 3=very verbose output
--settings SETTINGS The Python path to a settings module, e.g.
"myproject.settings.main". If this isn't provided, the
DJANGO_SETTINGS_MODULE environment variable will be
used.
--pythonpath PYTHONPATH
A directory to add to the Python path, e.g.
"/home/djangoprojects/myproject".
--traceback Raise on CommandError exceptions.
--no-color Don't colorize the command output.
--force-color Force colorization of the command output.
运行测试实例
pmg test word.test_dict.DictTestCase --keepdb --verbosity 2
pmg=python manage.pyword.test_dict.DictTestCase--verbosity 2
PS D:\repos\ELA\backEnd\ela> pmg test word.test_dict.DictTestCase --keepdb --verbosity 2
Found 5 test(s).
Using existing test database for alias 'default' ('test_ela4')...
Operations to perform:
Synchronize unmigrated apps: coreapi, django_filters, drf_yasg, messages, rest_framework, staticfiles
Apply all migrations: admin, auth, contenttypes, polls, scoreImprover, sessions, user, word
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Running migrations:
Applying user.0019_alter_user_examdate_alter_user_name_and_more... OK
System check identified no issues (0 silenced).
test_demo (word.test_dict.DictTestCase) ... ['apple', 'ˈæp(ə)l', 'apples', 'NULL', 'NULL', 'NULL', 'NULL', "['n. 苹果']"]
@test_url /word/test/
{'spelling': 'apple', 'phnetic': 'ˈæp(ə)l', 'explains': "['n. 苹果']"}
@res.type: <class 'dict'="">
@res <response status_code="200," "application="" json"="">
@res.data {'spelling': 'apple', 'phnetic': 'ˈæp(ə)l', 'explains': "['n. 苹果']"}
ok
test_false_is_true (word.test_dict.DictTestCase) ... Method: test_false_is_true.
ok
test_no_explain (word.test_dict.DictTestCase) ... ok
test_one_plus_one_equals_two (word.test_dict.DictTestCase) ... Method: test_one_plus_one_equals_two.
ok
test_reverse (word.test_dict.DictTestCase) ... @type_res: <class 'rest_framework.response.response'="">
@res.content {"detail":"Not found."}
@type_res_list: <class 'django.http.response.httpresponsepermanentredirect'="">
@res.content_list
ok
----------------------------------------------------------------------
Ran 5 tests in 1.358s
OK
Preserving test database for alias 'default' ('test_ela4')...
verbosity=3
PS D:\repos\ELA\backEnd\ela> pmg test word.test_dict.DictTestCase --keepdb --verbosity 3
Found 5 test(s).
Using existing test database for alias 'default' ('test_ela4')...
Operations to perform:
Synchronize unmigrated apps: coreapi, django_filters, drf_yasg, messages, rest_framework, staticfiles
Apply all migrations: admin, auth, contenttypes, polls, scoreImprover, sessions, user, word
Running pre-migrate handlers for application main
Running pre-migrate handlers for application scoreImprover
Running pre-migrate handlers for application word
Running pre-migrate handlers for application user
Running pre-migrate handlers for application admin
Running pre-migrate handlers for application polls
Running pre-migrate handlers for application auth
Running pre-migrate handlers for application contenttypes
Running pre-migrate handlers for application sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Running migrations:
No migrations to apply.
Running post-migrate handlers for application main
Running post-migrate handlers for application scoreImprover
Running post-migrate handlers for application word
Running post-migrate handlers for application user
Running post-migrate handlers for application admin
Running post-migrate handlers for application polls
Running post-migrate handlers for application auth
Running post-migrate handlers for application contenttypes
Running post-migrate handlers for application sessions
System check identified no issues (0 silenced).
test_demo (word.test_dict.DictTestCase) ... ['apple', 'ˈæp(ə)l', 'apples', 'NULL', 'NULL', 'NULL', 'NULL', "['n. 苹果']"]
@test_url /word/test/
{'spelling': 'apple', 'phnetic': 'ˈæp(ə)l', 'explains': "['n. 苹果']"}
@res.type: <class 'dict'="">
@res <response status_code="200," "application="" json"="">
@res.data {'spelling': 'apple', 'phnetic': 'ˈæp(ə)l', 'explains': "['n. 苹果']"}
ok
test_false_is_true (word.test_dict.DictTestCase) ... Method: test_false_is_true.
ok
test_no_explain (word.test_dict.DictTestCase) ... ok
test_one_plus_one_equals_two (word.test_dict.DictTestCase) ... Method: test_one_plus_one_equals_two.
ok
test_reverse (word.test_dict.DictTestCase) ... @type_res: <class 'rest_framework.response.response'="">
@res.content {"detail":"Not found."}
@type_res_list: <class 'django.http.response.httpresponsepermanentredirect'="">
@res.content_list
ok
----------------------------------------------------------------------
Ran 5 tests in 1.278s
OK
Preserving test database for alias 'default' ('test_ela4')...
PS D:\repos\ELA\backEnd\ela>
在测试中创建测试数据setUpTestData()&setUp()
setUpTestData()在任何测试方法不会修改或更改的对象setUp()测试函数之前设置可能被测试修改的