簡體   English   中英

Python tox和py.test:如何運行單個測試而不是整個測試套件

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

我剛接觸Django並進行測試,請耐心等待。

試圖在終端上運行我在Django項目中開發的代碼的新測試,但不幸的是我繼承了幾個測試失敗(已經通過分析我之前的提交已經確認)。 我正在嘗試運行/修復我的測試/代碼。 沒有修復所有的故障測試(至少現在不是)。 今天我們通過在主項目文件夾中運行tox來運行測試,並且tox最終調用py.test ,使用不同的數據庫(在開發/生產中我們使用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似乎沒有運行任何測試。 我寫了一個失敗的測試(故意),當我用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的答案是最接近的答案,但我必須適應一些事情:

  • 需要使用2個冒號而不是1個
  • 必須使用2個冒號而不是點來從方法名稱中分離方法名稱
  • 還必須刪除“-e”參數,因為我的tox.ini文件中沒有設置該環境。

最終命令如下所示:

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

您應該准備tox.ini接受命令行參數並將它們傳遞給pytest:

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

之后,您可以傳遞少量或多個參數:

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

嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM