How to write unittest for variable assignment in python?
<p>This is in <code>Python 2.7</code>.  I have a class called <code>class A</code>, and there are some attributes that I want to throw an exception when being set by the user:</p>

<pre><code>myA = A()
myA.myattribute = 9   # this should throw an error
</code></pre>

<p>I want to write a <code>unittest</code> that ensures that this throws an error.  </p>

<p>After creating a test class and inheriting <code>unittest.TestCase</code>, I tried to write a test like this:</p>

<pre><code>myA = A()
self.assertRaises(AttributeError, eval('myA.myattribute = 9'))
</code></pre>

<p>But, this throws a <code>syntax error</code>.  However, if I try <code>eval('myA.myattribute = 9')</code>, it throws the attribute error, as it should.</p>

<p>How do I write a unittest to test this correctly?  </p>

<p>Thanks.</p>

<p><code>self.assertRaises</code> takes a callable (and optionally one or more arguments for that callable) as its argument; you are providing the value that results from calling the callable with its arguments. The correct test would be <strike><code>self.assertRaises(AttributeError, eval, 'myA.myattribute = 9')</code></strike></p>

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

<p>However, you should use <code>assertRaises</code> as a context manager, which allows you to write the much more natural</p>

<pre><code>with self.assertRaises(AttributeError):
    myA.myattribute = 9
</code></pre>

python python-2.7 unit-testing python-unittest