Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Updated</strong> - <code>__file__</code> is the path name from which the <em>current module</em> was loaded, so naturally using <code>__file__</code> inside DynamicTestCase.py will result in the path DynamicTestCase.py. However, you can just pass the path into <code>setDocstring()</code> from subclasses like this:</p> <p><strong>DynamicTestCase.py</strong>:</p> <pre><code>class DynamicTestCase(unittest.TestCase): def setDocstring(self, docstring=None): if docstring is None: docstring = __file__ if os.path.exists(docstring): name = os.path.split(docstring)[1] docstring = os.path.splitext(name)[0] setattr(self, '__doc__', docstring) </code></pre> <p><strong>MyTestCase.py</strong>:</p> <pre><code>class MyTestCase(DynamicTestCase): def __init__(self, *args, **kwargs): DynamicTestCase.__init__(self, *args, **kwargs) self.setDocstring(__file__) def test_print_docstring(self): print 'MyTestCase Docstring = ', self.__doc__ def test_new_docstring(self): self.setDocstring('hello') print 'MyTestCase Docstring = ', self.__doc__ </code></pre> <p>Output:</p> <pre><code>MyTestCase Docstring = MyTestCase MyTestCase Docstring = hello </code></pre> <hr> <p><strong>Rest of answer</strong></p> <p>In your original code above <code>__name__</code> is a string, not a class. Jython rightly rejects altering the <code>__doc__</code> attribute on the <code>str</code> type.</p> <p>Could you explain a bit about <em>why</em> you want to change TestCase's docstring? For example, you could subclass TestCase and give your own docstring:</p> <pre><code>class MyTestCase(unittest.TestCase): "Docstring of MyTestCase" </code></pre> <p>Not sure if you've tried it yet, but the <a href="http://pypi.python.org/pypi/unittest2" rel="nofollow">unittest2 package's</a> TestCase has <code>setUpClass, tearDownClass</code> class methods. It's a backport of Python 2.7's improvements to work with Python 2.6 and prior.</p> <p>Jython allows you to set the <code>__doc__</code> of new-style classes, but CPython does not. For that reason you might want to find another way to accomplish your goal if you want your code to be portable:</p> <pre><code>Jython 2.2.1 on java1.6.0_24 &gt;&gt;&gt; unittest.TestCase.__doc__ = 'foo bar' &gt;&gt;&gt; unittest.TestCase.__doc__ 'foo bar' Python 2.6.6 (r266:84292, Feb 12 2011, 01:07:21) &gt;&gt;&gt; unittest.TestCase.__doc__ = 'foo bar' AttributeError: attribute '__doc__' of 'type' objects is not writable </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload