美文网首页
pytest-django简单使用记录

pytest-django简单使用记录

作者: wowshiwoniu | 来源:发表于2018-08-16 16:16 被阅读0次

pytest是一款简单的测试库,方便对于自己的代码进行单元测试,简单的学习使用了一下。

安装

  • pytest-django安装
$ pip install pytest-django

运行

  • 建立测试文件
# coding=utf-8
"""
test_1.py 
"""
class TestClass:

    def test_one(self):
        x = "this"
        assert "h" in x

    def test_two(self):
        x = "hello"
        assert x == "hi"
  • 执行
$ pytest test_1.py
  • 结果
tests_1.py .F                                                            [100%]

================================== FAILURES ===================================
_____________________________ TestClass.test_two ______________________________

self = <tests.tests_1.TestClass object at 0x04352690>

    def test_two(self):
        x = "hello"
>       assert x == "hi"
E       AssertionError: assert 'hello' == 'hi'
E         - hello
E         + hi

tests_1.py:11: AssertionError
===================== 1 failed, 1 passed in 0.43 seconds ======================

就这是么容易上手,就可以执行测试单元了

django项目配置

对于django项目,很多地方可能需要引入DJANGO_SETTINGS_MODULE,这个该如何测试,pytest也提供了简单的方法,这里选择了最方便的配置文件.

  • 建立配置文件
    在django项目根目录下,创建pytest.ini文件
[pytest]
# 根据自己项目实际配置文件填充
DJANGO_SETTINGS_MODULE=myproject.settings.development
# 所有以test_开头的文件,在单独运行pytest之时都会被执行
python_files=tests_*.py
# 此项配置python路径,若app在当前目录,可忽略,若app均在指定的目录之下,例如apps,这里指定app文件目录 
python_paths=apps

demo项目目录结构如下:

├─apps
│  ├─app_polls
│  │  ├─migrations
├─configs
├─doc
│  └─source
├─myproject
│  ├─settings
├─requirements
├─static
├─templates
└─tests

  • 执行pytest命令
$ pytest

此时,pytest将会遍历当前项目下以 pytest_ 开头的单元测试文件

若要单独测试某个文件,可直接指定该文件

$ pytest test_xxx.py

相关文章

网友评论

      本文标题:pytest-django简单使用记录

      本文链接:https://www.haomeiwen.com/subject/slhobftx.html