【问题标题】:How to write unittest for variable assignment in python?如何在python中为变量赋值编写unittest?
【发布时间】:2016-10-19 01:50:34
【问题描述】:

这是Python 2.7。我有一个名为class A 的类,并且有一些属性我想在用户设置时抛出异常:

myA = A()
myA.myattribute = 9   # this should throw an error

我想写一个unittest 来确保这会引发错误。

创建一个测试类并继承unittest.TestCase后,我尝试写一个这样的测试:

myA = A()
self.assertRaises(AttributeError, eval('myA.myattribute = 9'))

但是,这会引发syntax error。但是,如果我尝试eval('myA.myattribute = 9'),它应该会抛出属性错误。

如何编写单元测试来正确测试?

谢谢。

【问题讨论】:

    标签: python python-2.7 unit-testing python-unittest


    【解决方案1】:

    您还可以使用assertRaises 作为上下文管理器:

    with self.assertRaises(AttributeError):
        myA.myattribute = 9
    

    documentation shows more examples for this if you are interestedassertRaises 的文档也有关于这个主题的更多详细信息。

    来自该文档:

    如果只给出了异常和可能的 msg 参数,则返回一个上下文管理器,以便可以编写被测代码 内联而不是作为函数:

    with self.assertRaises(SomeException):
         do_something()
    

    这正是你想要做的。

    【讨论】:

      【解决方案2】:

      self.assertRaises 将一个可调用对象(以及可选的该可调用对象的一个​​或多个参数)作为其参数;您正在提供通过使用其参数调用可调用对象所产生的值。正确的测试应该是 self.assertRaises(AttributeError, eval, 'myA.myattribute = 9')

      # Thanks to @mgilson for something that actually works while
      # resembling the original attempt.
      self.assertRaises(AttributeError, eval, 'myA.myattribute = 9', locals())
      

      但是,你应该使用assertRaises 作为上下文管理器,这样你可以写得更自然

      with self.assertRaises(AttributeError):
          myA.myattribute = 9
      

      【讨论】:

      • 第一种形式有效吗? eval 将评估当前命名空间中的表达式——这是调用 eval 的命名空间,它不会定义 myA。如果您打算使用函数形式(不建议这样做),您可能应该使用self.assertRaises(AttributeError, setattr, myA, 'myattribute', 9)您必须通过:self.assertRaises(AttributeError, eval, 'myA.myattribute = 9', locals()) 传递当前函数的本地变量
      • 是的,我并没有真正考虑过您将如何正确使用eval。我应该解释一下 assertRaises 接受 it 可以调用的东西,而不是表达式的结果,然后就这样了。
      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2022-11-28
      • 2016-01-24
      • 1970-01-01
      • 2018-06-24
      • 2018-06-18
      相关资源
      最近更新 更多