2016-03-31 4 views
1

私は次の関数のためのユニットテストを書くのです:Pythonのユニットテスト:アサーションエラー問題

def _parse_args(): 
    parser = argparse.ArgumentParser(
     description='Script to configure appliance.' 
    ) 
    parser.add_argument('--config_file', 
         help='Path to a JSON configuration file') 
    print parser.parse_args() 
    return parser.parse_args() 

私は、configファイルは、上記の関数ではprint文を使用して検証(その後、指定されていない機能を実行すると、 ):私のユニットテストで parser.parse_args()=Namespace(config_file=None)

私は与えられていない設定ファイルで関数を実行してのassertEqualsを含める:

self.assertEquals(my_script._parse_args(), 'Namespace(config_file=None)') 

しかし、これはAssertionErrorがを生成します。

AssertionError: Namespace(config_file=None) != 'Namespace(config_file=None)' 

私は引用符なしにユニットテストを変更する場合:

self.assertEquals(my_script._parse_args(), Namespace(config_file=None)) 

私はNameErrorを得る:

NameError: global name 'Namespace' is not defined 

は明らかに相場を使用することではありませんこれを行う正しい方法ですが、どうすればNamespace(config_file=None)が発生していると主張するのですか?

答えて

1

変更

self.assertEquals(my_script._parse_args(), Namespace(config_file=None)) 

self.assertEquals(my_script._parse_args(), argparse.Namespace(config_file=None)) 

Namespaceにインポート​​モジュールの属性です。あなた自身でNamespaceをインポートしませんでした。引数なしであなたのコードを実行するための

デモ:あなたはprint parser.parse_args()を呼び出すことによって取得することを、Namespaceオブジェクトではなく、それの文字列表現を返します_parse_args()

print _parse_args() == argparse.Namespace(config_file=None) # True 
1

返されたNamespaceオブジェクトのconfig_file属性を確認してください。

self.assertIsNone(my_script._parse_args().config_file) 
0

あなたの機能。

my_script._parse_args().config_file 

、それがNoneでない場合は主張:

をあなたの関数で

見てみましょう:アクセスは、それが保持して属性にオブジェクトの場合

def _parse_args(): 
    #some code 
    print parser.parse_args() <-- prints the string representation of the Namespace object 'Namespace(config_file=None)' 
    return parser.parse_args() <-- returns the Namespace object 

は、あなたは、ドット表記を使用することができます返さ

self.assertIsNone(my_script._parse_args().config_file) 

また、任意の名前空間オブジェクトを作成するには、そのコンストラクタ:

argparse.Namespace (config_file = None, another_arg='some value') 

とassertEqualでそれを使用します。

self.assertEqual(my_script._parse_args(), argparse.Namespace (config_file = None))