Django中的单元测试
2017-08-31 00:00
106 查看
摘要: 尽早进行单元测试(UnitTest)是比较好的做法,极端的情况甚至强调“测试先行”。Django支持python的单元测试(unit test)和文本测试(doc test),我们这里主要讨论单元测试的方式
tests.py文件:
实际项目:
你可以有几种方式运行单元测试:
为了避免测试数据造成的影响,测试过程会使用一个单独的数据库,一般使用sqlite数据库
tests.py文件:
from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
实际项目:
import unittest from mock import patch class TestConversion(unittest.TestCase): def test_convert(self): """Test :py:func:``exchange.conversion.convert``""" from exchange.conversion import convert, Price with patch('exchange.conversion.ExchangeRates') as exchange_rates: exchange_rates.get_instance.return_value = \ {'USD': {'GBP': 0.5}} price = Price(3, 'USD') converted_price = convert(price, 'GBP') self.assertEqual(converted_price.value, 1.50) self.assertEqual(converted_price.currency, 'GBP') def test_price(self): """Test :py:class:``exchange.conversion.Price``""" from exchange.conversion import Price with patch('exchange.conversion.ExchangeRates') as exchange_rates: exchange_rates.get_instance.return_value = \ {'USD': {'GBP': 0.5}} price = Price(3, 'USD') converted_price = price.convert('GBP') self.assertEqual(converted_price.value, 1.50) self.assertEqual(converted_price.currency, 'GBP')
你可以有几种方式运行单元测试:
python manage.py test:执行所有的测试用例 python manage.py test app_name, 执行该app的所有测试用例 python manage.py test app_name.case_name: 执行指定的测试用例
为了避免测试数据造成的影响,测试过程会使用一个单独的数据库,一般使用sqlite数据库
相关文章推荐
- Django单元测试二三事
- Django基础,Day6 - 单元测试tests
- Django中的单元测试
- Django之单元测试
- Django单元测试(二)------测试工具
- Django 单元测试
- Django 中的 csrf_token 与单元测试报错处理
- Django单元测试框架总结
- 对Python的Django框架中的项目进行单元测试的方法
- Django单元测试简明实践
- 关于Django的单元测试之session
- Django单元测试简单示例
- Django实战(10):单元测试
- Django单元测试(二)------测试工具
- django单元测试编写
- Django实战(10):单元测试
- django单元测试编写
- 如何进行Django单元测试?
- 物联网笔记-----------Django单元测试,Django bug(二)
- Django基础 4000 ,Day6 - 单元测试tests