Failure in __str__() before any output.
authorJeff Quast <contact@jeffquast.com>
Sat, 22 Nov 2014 19:33:55 +0000 (11:33 -0800)
committerJeff Quast <contact@jeffquast.com>
Sat, 22 Nov 2014 19:33:55 +0000 (11:33 -0800)
When calling str() on a spawn class object before
it has any command output, the __str__() override
attempts to truncate long command output while the
value of self.before is still None, raising:

    TypeError: 'NoneType' object has no attribute '__getitem__'

pexpect/__init__.py
tests/test_repr.py [new file with mode: 0644]

index 8e2b21e0e748910b8bf30fc02d676fe524023d72..8f3af26096034a91313fb897790e02b418322901 100644 (file)
@@ -583,8 +583,10 @@ class spawn(object):
         s.append('command: ' + str(self.command))
         s.append('args: %r' % (self.args,))
         s.append('searcher: %r' % (self.searcher,))
-        s.append('buffer (last 100 chars): %r' % (self.buffer)[-100:],)
-        s.append('before (last 100 chars): %r' % (self.before)[-100:],)
+        s.append('buffer (last 100 chars): %r' % (
+            self.buffer and (self.buffer)[-100:] or self.buffer,))
+        s.append('before (last 100 chars): %r' % (
+            self.before and (self.before)[-100:] or self.before,))
         s.append('after: %r' % (self.after,))
         s.append('match: %r' % (self.match,))
         s.append('match_index: ' + str(self.match_index))
diff --git a/tests/test_repr.py b/tests/test_repr.py
new file mode 100644 (file)
index 0000000..9f6c026
--- /dev/null
@@ -0,0 +1,25 @@
+""" Test __str__ methods. """
+import pexpect
+
+from . import PexpectTestCase
+
+class TestCaseMisc(PexpectTestCase.PexpectTestCase):
+
+    def test_str_spawnu(self):
+        """ Exercise spawnu.__str__() """
+        # given,
+        p = pexpect.spawnu('cat')
+        # exercise,
+        value = p.__str__()
+        # verify
+        assert isinstance(value, basestring)
+
+    def test_str_spawn(self):
+        """ Exercise spawn.__str__() """
+        # given,
+        p = pexpect.spawn('cat')
+        # exercise,
+        value = p.__str__()
+        # verify
+        assert isinstance(value, basestring)
+