2012-03-22 14 views
2

私はpythonのnoobです。 私はPythonユニットテストがどのようにビルドされ、実際のアプリケーションのために実行されることになっているのか混乱しています。つまり、メインメソッドから始まるプログラムを持っていれば、このプログラムのユニットテストを同じエントリーポイント? 私は、通常の実行(以下を参照)の代わりにユニットテストを実行するようにプログラムに指示する必要があるパラメータの1つを作成しようとしていますが、unittest.main()が受け入れることができるすべてのパラメータを受け入れることもできます。私が取っているアプローチが正しいかどうか、私はニシキヘビの方法または下記の例で任意のヘルプで実際のプログラムの実行やユニットテストを分離するより良い方法についてのアドバイスをいただければ幸いです。プログラムのオプションとしてpython単体テストを実行する

class MyClass 
    def write_to_file(self, file): 
     open(file, 'w').write("Hello world!") 

class MyClassTest (unittest.TestCase) 
    self.mc = MyClass() 
    self.test_file = os.path.join(os.path.curdir, "a_file.txt") 
    def setUp(self): 
     pass 

    def test_write_to_file(self): 
     try: 
      write_to_file(self.test_file) 
     except IOError: 
      self.fail("Error!") 
if __name__== "__main__": 
    parser = argparse.ArgumentParser(description="Some desc") 
    group = parser.add_mutually_exclusive_group() 
    group.add_argument("-w", "--write", help=': write hello world to given file') 
    group.add-argument("-t", "--test", help=': run unit tests, use "all" to run all tests') 
    args = parser.parse_args(sys.argv[1:]) 
    mcl = MyClass() 

    if args.write: 
     mcl.write_to_file(args.write) 
     # below is the questionnable part 
    if args.test: 
     #removing -t or --test argument because otherwise unittest.main() will complain 
     del sys.argv[1:] 
     if args.test == "all": 
      unittest.main() 
     else: 
     # Adding the argument that was specified after the -t into the sys.argv to be picked up by the unittest.main() - doesn't work correctly (1) 
      sys.argv.append(args.test) 
      unittest.main() 

を(1)私は「場合m MyClassを-t MyTestCaseオプションで指定しています。ヘルプメッセージunittest.main()に基づいて実行できると思っていますが、AttributeErrorがあります: 'module'オブジェクトには属性がありませんMyTestCase

ありがとう!

答えて

1

クラス(テスト対象のユニット)をファイルに入れ、 "main"プログラムとユニットテストを2つのファイルに追加します。後者は実行可能なスクリプトです。最初のものは単にそれらによってインポートされます。

+0

私は配置パターンを変更したくないので、モジュールからユニットテストを抽出しただけで機能します。ありがとう! –

関連する問題