2012-01-22 8 views
3

Pythonのunittest.Testcase of BasicTestのサブクラスを作成したいと思います。私はBasicTestの各サブクラスが同じルーチンをメインで実行するようにしたいと思います。どうすればこれを達成できますか?サブクラスpython unittest.Testcase、同じメインを呼び出す

例:

in basic_test.py: 

class BasicTest(unittest.TestCase): 

    ... 


if __name__ == '__main__': 
    # Do optparse stuff 
    unittest.main() 



in some_basic_test.py: 

class SomeBasicTest(BasicTest): 
    ... 

if __name__ == '__main__': 
    #call the main in basic_test.py 
+0

関連:[Pythonのunittestモジュールをテストランナーとして使用するときにテストの前に初期化コードを実行する方法](0120-18756) –

答えて

2
# basic_test.py 
class BasicTest(unittest.TestCase): 

    @staticmethod 
    def main(): 
    # Do optparse stuff 
    unittest.main() 

if __name__ == '__main__': 
    BasicTest.main() 



# some_basic_test.py 
class SomeBasicTest(BasicTest): 
    ... 

if __name__ == '__main__': 
    BasicTest.main() 
+1

'BasicTest'から継承している複数のクラスがテストモジュール?初期化コード( 'BasicTest.main()')は、各テストケースからメソッドを実行する前ではなく1回だけ実行されます。 –

1

あなたが(再)、新しいとしてモジュールをインポートすることができない、したがってif __name__=="__main__"コードは一種の到達不能です。

Dorさんの提案などが最も合理的です。 問題のモジュールにアクセスできない場合は、モジュールをメインとして実行するrunpy.run_module()を調べることを検討してください。

1

私は私が何をしたいと思いメイン

に同じルーチンを実行するBasicTestの各サブクラスをご希望の任意のテストケースからテストを実行する前に、いくつかのセットアップ/初期化コードを実行することです。この場合、setUpClassクラスメソッドに興味があるかもしれません。

testA.py

import unittest 


class BasicTest(unittest.TestCase): 

    @classmethod 
    def setUpClass(cls): 
     print 'Preparing to run tests' 


class TestA(BasicTest): 

    def test1(self): 
     print 'testA: test1' 

    def test2(self): 
     print 'testA: test2' 


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

testB.py

import unittest 

from testA import BasicTest 


class TestB(BasicTest): 

    def test1(self): 
     print 'testB: test1' 

    def test2(self): 
     print 'testB: test2' 


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

testA.pyからの出力:

Preparing to run tests 
testA: test1 
testA: test2 
.. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.000s 

OK 

testB.pyからの出力:

Preparing to run tests 
testB: test1 
testB: test2 
.. 
---------------------------------------------------------------------- 
Ran 2 tests in 0.000s 

OK 
+0

unittest.main()が呼び出される前に、私はいくつかのコマンドライン引数を解析しなければならないので、setUpClass – stackOverlord

関連する問題