Python tox 和 py.test:如何 运行 只是一个测试而不是整个测试套件

Python tox and py.test: how to run just a single test rather than the whole test suite

我是 Django 的新手,刚开始测试所以请多多包涵。

尝试在终端上 运行 对我在 Django 项目中开发的代码进行新测试,但不幸的是我继承了几个测试失败(已经通过分析我之前的提交确认)。我正在尝试 run/fix 只是我的 test/code。不修复所有失败的测试(至少现在不是)。今天我们 运行 在主项目文件夹中 运行ning tox 进行测试,tox 最终调用 py.test,使用不同的数据库(在 development/production我们使用 Postgresql,但对于测试我们使用 SQLite)。这是tox.ini配置

[tox]
envlist = unit
skipsdist = True

[testenv:unit]
deps = -rrequirements/test.txt
commands =
    bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test'
    py.test -n 4

passenv = *
setenv =
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
whitelist_externals =
    /bin/bash

[flake8]
max-line-length = 110 

[pytest]
setenv=
    DJANGO_SETTINGS_MODULE=telessaude.settings.test
python_files = **/tests.py **/tests/*.py **/tests.py
norecursedirs = requirements .tox media

这是我的测试,位于 ~/project_name/servicos/tests.py

# encoding: utf-8
from fluxos.tests import BaseFluxoTestCase
from core.tests import BaseTestCase
from servicos.models import Estomatologia


class EstomatologiaTestCase(BaseTestCase):

    def testa_formata_campos(self):
        estomato = Estomatologia()
        return_value = estomato.formata_campos()
        self.assertEquals(return_value['comorbidades_paciente'], '')

    ...

对于这个新创建的测试,我应该如何处理 tox 或 py.test 到 运行?谢谢!


更新 1:不幸的是,建议的答案没有用。当我 运行 按照 phd 和 Windsooon 的建议进行单个测试时,tox 似乎没有 运行ning 任何测试。我写了一个失败的测试(故意),当我 运行 使用 tox 命令进行所有测试时,错误显示:

    def test_formata_campos_para_estomatologia(self):
        estomatologia = Estomatologia()
        retorno = formata_campos(estomatologia)
>       self.assertIn('objetivos', retorno) E       AssertionError: 'objetivos' not found in {'comorbidades_paciente': '', 'tempo_transcorrido': '', 'sinais_e_sintomas_locais': ''}

但是当我运行只单独测试时,测试通过了!我得到这个结果:

tox -e py27 -- servicos.tests:FormatacaoDeCamposTestCase.test_formata_campos_para_estomatologia
py27 installed: 
py27 runtests: PYTHONHASHSEED='3025337440'
______________________________________________________________ summary ______________________________________________________________
  py27: commands succeeded
  congratulations :)

在互联网上搜索,我发现我必须有 {posargs} 否则 tox 将忽略我提供给它的任何内容。但是,只有我的命令的第二行会使用它。第一行将测试数据库设置为 SQLite(用于测试的更快的数据库集)。这可能是 tox 上的错误吗?知道如何解决这个问题吗?


更新 2:@phd 的答案是最接近的,但我不得不调整一些东西:

最终命令如下所示:

tox -- folder1/folder2/file_name.py::ClassName::test_method_name

尝试

tox -e py27 -- test_file_name_here.py:TestClassName.test_method_name

您应该准备 tox.ini 接受命令行参数并将它们传递给 pytest:

[testenv:…]
commands =
    py.test -n 4 {posargs}

之后您可以传递尽可能少或尽可能多的参数:

tox -e $TOXENV -- test1.py test2.py…