国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

Django單元測試中Fixtures的使用方法

瀏覽:162日期:2024-10-23 16:04:56

在使用單元測試時,有時候需要測試數(shù)據(jù)庫中有數(shù)據(jù),這時我們可以使用Django的Fixtures來生成測試數(shù)據(jù)。

在對Django項目做單元測試時,我們需要一些初始的數(shù)據(jù)來作為檢測結(jié)果的依據(jù),那么對于我們已經(jīng)有正式數(shù)據(jù)庫的模塊來說,使用Fixture載入數(shù)據(jù)是簡單有效的方法。

首先,你需要一份json格式的數(shù)據(jù)文件,Django對此提供了很好的支持—dumpdata 命令:

python manage.py dumpdata myapp >myapp/fixtures/myapp.json# 這個命令將幫助你把數(shù)據(jù)庫中myapp 導入到myapp/fixtures/test.json中# 這個myapp可以沒有,會把數(shù)據(jù)庫所有數(shù)據(jù)生成Json文件

基礎(chǔ)配置

在settings.py 中配置如下內(nèi)容:

FIXTURE_DIRS = (’/path/to/api/fixtures/’,)

接著在test.py中 加入:

fixtures = [’test.json’]

最后么當然是運行test命令了:

./manage.py test

示例代碼

# coding=utf-8from __future__ import unicode_literalsimport jsonfrom rest_framework import statusfrom rest_framework.test import APITestCaseclass DjangoUnittest01(APITestCase): fixtures = ['my_test.json'] def setUp(self): data = { 'username': ’t1’, 'password': ’admin123’, 'code': 666, } self.client.post(’/base/admin/login/’, data) def test_usergroup_user_information(self):# 以test開頭的方法將會執(zhí)行 url = ’/base/admin/teacher/usergroup/21/user/4/information/?otype=soldier’ response = self.client.get(url) data = { 'update_date': '2018-05-31 16:22:55', 'task': '196311177981753978', 'otype': 'soldier', 'task_name': 'f_test1', 'progress': 1.0, 'id': 871 } self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertDictEqual(response.data['results'][0], data)

測試用例通過

Creating test database for alias ’default’...System check identified no issues (0 silenced)..----------------------------------------------------------------------Ran 1 test in 3.863s

OKDestroying test database for alias ’default’...

常用斷言

assertEqual(a, b) a == b assertNotEqual(a, b) a != b assertTrue(x) bool(x) is True assertFalse(x) bool(x) is False assertIs(a, b) a is b assertIsNot(a, b) a is not b assertIsNone(x) x is None assertIsNotNone(x) x is not None assertIn(a, b) a in b assertNotIn(a, b) a not in b assertIsInstance(a, b) isinstance(a, b) assertNotIsInstance(a, b) not isinstance(a, b)assertListEqual(a, b) lists assertTupleEqual(a, b) tuples assertDictEqual(a, b) dicts

到此這篇關(guān)于Django單元測試中Fixtures用法詳解的文章就介紹到這了,更多相關(guān)Django Fixtures內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標簽: Django
相關(guān)文章:
主站蜘蛛池模板: 道真| 枣强县| 万盛区| 安义县| 肥东县| 梅州市| 聂荣县| 五台县| 大悟县| 彭阳县| 西乌| 平塘县| 遂昌县| 吉木乃县| 筠连县| 海门市| 安宁市| 香河县| 菏泽市| 水城县| 连山| 仪征市| 乌苏市| 湖州市| 淮滨县| 南丹县| 宁明县| 青田县| 敖汉旗| 微博| 九寨沟县| 南雄市| 莲花县| 门源| 平遥县| 兴义市| 临漳县| 桓台县| 嘉黎县| 桃园市| 唐河县|