2013-10-02 9 views
14

Python unittest utilizzando nosetests per provare con Python Class and Module fixtures, per avere una configurazione minima tra i miei test.Python unitest - Utilizzare le variabili definite nelle funzioni di installazione del modulo e di livello di classe, nei test

Il problema che sto affrontando è che non sono sicuro di come utilizzare le variabili definite nel setupUpModule e le setUpClass funzioni nel mio test (ad esempio: - test_1).

questo è quello che sto usando per provare:

import unittest 

def setUpModule(): 
    a = "Setup Module variable" 
    print "Setup Module" 

def tearDownModule(): 
    print "Closing Module" 

class TrialTest(unittest.TestCase): 
    @classmethod 
    def setUpClass(cls): 
     print a #<====== 
     b = "Setup Class variable" 

    @classmethod 
    def tearDownClass(cls): 
     print "Closing Setup Class" 

    def test_1(self): 
     print "in test 1" 
     print a #<====== 
     print b #<====== 

    def test_2(self): 
     print "in test 2" 

    def test_3(self): 
     print "in test 3" 

    def test_4(self): 
     print "in test 4" 

    def test_5(self): 
     print "in test 5" 

if __name__ == "__main__": 
    unittest.main() 

L'errore che ottengo è:

Setup Module 
ERROR 
Closing Module 

====================================================================== 
ERROR: test suite for <class 'one_setup.TrialTest'> 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/Library/Python/2.7/site-packages/nose/suite.py", line 208, in run 
    self.setUp() 
    File "/Library/Python/2.7/site-packages/nose/suite.py", line 291, in setUp 
    self.setupContext(ancestor) 
    File "/Library/Python/2.7/site-packages/nose/suite.py", line 314, in setupContext 
    try_run(context, names) 
    File "/Library/Python/2.7/site-packages/nose/util.py", line 469, in try_run 
    return func() 
    File "/Users/patila14/Desktop/experimental short scripts/one_setup.py", line 13, in setUpClass 
    print a 
NameError: global name 'a' is not defined 

---------------------------------------------------------------------- 

, naturalmente, se fare gloabl a e global b, funzionerà. C'è un modo migliore?

+0

Eventuali duplicati di [unittest Setup/tearDown per diversi test] (https://stackoverflow.com/questions/8389639/unittest-setup-teardown-for-several-tests) –

risposta

12

Per str variabile a, l'unica soluzione è global a. Se si guarda il Python 2 unittest source code, setupModule() non sembra fare nulla di magico, quindi si applicano tutte le normali regole dello spazio dei nomi.

Se a fosse una variabile mutabile, come una lista, è possibile definirla a livello globale e quindi aggiungerla a setupModule.

Variabile b è più facile da utilizzare perché è definito all'interno di una classe. Prova questo:

@classmethod 
def setUpClass(cls): 
    cls.b = "Setup Class variable" 

def test_1(self): 
    print self.b 
Problemi correlati