2016-07-18 110 views
12

dire che ho un po 'di test:Come disabilitare un test usando py.test?

def test_func_one(): 
    ... 

def test_func_two(): 
    ... 

def test_func_three(): 
    ... 

C'è un decoratore o qualcosa di simile che potrei aggiungere alle funzioni per evitare py.test esecuzione proprio questo test? Il risultato potrebbe essere simile ...

@pytest.disable() 
def test_func_one(): 
    ... 

def test_func_two(): 
    ... 

def test_func_three(): 
    ... 

ho cercato qualcosa di simile nella documentazione py.test, ma penso che potrei mancare qualcosa qui.

risposta

15

Pytest ha la cesta e skipif decoratori, simile al Python unittest modulo (che utilizza skip e skipIf), che si trova nella documentazione here .

Esempi dal collegamento può essere trovato qui:

@pytest.mark.skip(reason="no way of currently testing this") 
def test_the_unknown(): 
    ... 

import sys 
@pytest.mark.skipif(sys.version_info < (3,3), 
        reason="requires python3.3") 
def test_function(): 
    ... 

Il primo esempio passa sempre il test, il secondo esempio consente di saltare condizionale test (grande quando test dipendono dalla piattaforma, versione eseguibile, o librerie opzionali.

per esempio, se voglio controllare se qualcuno ha i panda libreria installata per un test.

import sys 
try: 
    import pandas as pd 
except ImportError: 
    pass 

@pytest.mark.skipif('pandas' not in sys.modules, 
        reason="requires the Pandas library") 
def test_pandas_function(): 
    ... 
11

Il skip decorator farebbe il lavoro:

@pytest.mark.skip(reason="no way of currently testing this") 
def test_func_one(): 
    # ... 

(reason argomento è facoltativo, ma è sempre una buona idea per specificare il motivo per cui un test è saltato).

C'è anche skipif() che consente di disabilitare un test se sono soddisfatte alcune condizioni specifiche.


Questi decoratori possono essere applicati a metodi, funzioni o classi.

Per skip all tests in a module, definire una pytestmark variabile globale:

# test_module.py 
pytestmark = pytest.mark.skipif(...) 
+0

Entrambi siete fantastici! È così difficile scegliere quale sia la risposta giusta. Prenderò entrambi in un istante. – ericmjl

2

io non sono so se è deprezzato, ma è anche possibile utilizzare la funzione pytest.skip all'interno di un test:

def test_valid_counting_number(): 
    number = random.randint(1,5) 
    if number == 5: 
     pytest.skip('Five is right out') 
    assert number <= 3 
0

Si consiglia inoltre di eseguire il test anche se si sospetta che test fallirà. Per tale scenario https://docs.pytest.org/en/latest/skipping.html suggerisce di utilizzare decoratore @ pytest.mark.xfail

@pytest.mark.xfail 
def test_function(): 
    ... 

In questo caso, Pytest sarà ancora eseguito il test e si lascia ora se passa o adesso, ma non si lamenterà e pausa la build.