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>You can also use <code>assertRaises</code> as a context manager:</p>

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

<p>The <a href="https://docs.python.org/3/library/unittest.html#basic-example" rel="nofollow">documentation shows more examples for this if you are interested</a>. The documentation for <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> has a lot more detail on this subject as well.</p>

<p>From that documentation:</p>

<blockquote>
  <p>If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written
  inline rather than as a function:</p>

<pre><code>with self.assertRaises(SomeException):
     do_something()
</code></pre>
</blockquote>

<p>which is exactly what you are trying to do.</p>

python python-2.7 unit-testing python-unittest