[Python-checkins] CVS: python/dist/src/Lib/test test_dircache.py,NONE,1.3.2.1 test_repr.py,NONE,1.1.2.1 test_mimetools.py,1.1,1.1.8.1 test_ntpath.py,1.7,1.7.6.1 test_os.py,1.2.2.1,1.2.2.2 test_quopri.py,1.2.2.1,1.2.2.2 test_sax.py,1.16,1.16.6.1 test_unicode.py,1.31.6.1,1.31.6.2

Tim Peters tim_one@users.sourceforge.net
Fri, 20 Jul 2001 23:07:15 -0700


Update of /cvsroot/python/python/dist/src/Lib/test
In directory usw-pr-cvs1:/tmp/cvs-serv27169/descr/dist/src/Lib/test

Modified Files:
      Tag: descr-branch
	test_mimetools.py test_ntpath.py test_os.py test_quopri.py 
	test_sax.py test_unicode.py 
Added Files:
      Tag: descr-branch
	test_dircache.py test_repr.py 
Log Message:
Merge of trunk delta date2001-07-17b to date2001-07-21.  See PLAN.txt.


--- NEW FILE: test_dircache.py ---
"""
  Test cases for the dircache module
  Nick Mathewson
"""

import unittest
from test_support import run_unittest, TESTFN
import dircache, os, time, sys


class DircacheTests(unittest.TestCase):
    def setUp(self):
        self.tempdir = TESTFN+"_dir"
        os.mkdir(self.tempdir)

    def tearDown(self):
        for fname in os.listdir(self.tempdir):
            self.delTemp(fname)
        os.rmdir(self.tempdir)

    def writeTemp(self, fname):
        f = open(os.path.join(self.tempdir, fname), 'w')
        f.close()

    def mkdirTemp(self, fname):
        os.mkdir(os.path.join(self.tempdir, fname))

    def delTemp(self, fname):
        fname = os.path.join(self.tempdir, fname)
        if os.path.isdir(fname):
            os.rmdir(fname)
        else:
            os.unlink(fname)

    def test_listdir(self):
        ## SUCCESSFUL CASES
        entries = dircache.listdir(self.tempdir)
        self.assertEquals(entries, [])

        # Check that cache is actually caching, not just passing through.
        self.assert_(dircache.listdir(self.tempdir) is entries)

        # Directories aren't "files" on Windows, and directory mtime has
        # nothing to do with when files under a directory get created.
        # That is, this test can't possibly work under Windows -- dircache
        # is only good for capturing a one-shot snapshot there.

        if sys.platform[:3] not in ('win', 'os2'):
            # Sadly, dircache has the same granularity as stat.mtime, and so
            # can't notice any changes that occured within 1 sec of the last
            # time it examined a directory.
            time.sleep(1)
            self.writeTemp("test1")
            entries = dircache.listdir(self.tempdir)
            self.assertEquals(entries, ['test1'])
            self.assert_(dircache.listdir(self.tempdir) is entries)

        ## UNSUCCESSFUL CASES
        self.assertEquals(dircache.listdir(self.tempdir+"_nonexistent"), [])

    def test_annotate(self):
        self.writeTemp("test2")
        self.mkdirTemp("A")
        lst = ['A', 'test2', 'test_nonexistent']
        dircache.annotate(self.tempdir, lst)
        self.assertEquals(lst, ['A/', 'test2', 'test_nonexistent'])

run_unittest(DircacheTests)

--- NEW FILE: test_repr.py ---
"""
  Test cases for the repr module
  Nick Mathewson
"""

import unittest
from test_support import run_unittest
from repr import repr as r # Don't shadow builtin repr 


def nestedTuple(nesting):
    t = ()
    for i in range(nesting):
        t = (t,)
    return t

class ReprTests(unittest.TestCase):

    def test_string(self):
        eq = self.assertEquals
        eq(r("abc"), "'abc'")
        eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")

        s = "a"*30+"b"*30
        expected = `s`[:13] + "..." + `s`[-14:]
        eq(r(s), expected)
        
        eq(r("\"'"), repr("\"'"))
        s = "\""*30+"'"*100
        expected = `s`[:13] + "..." + `s`[-14:]
        eq(r(s), expected)

    def test_container(self):
        eq = self.assertEquals
        # Tuples give up after 6 elements
        eq(r(()), "()")
        eq(r((1,)), "(1,)")
        eq(r((1, 2, 3)), "(1, 2, 3)")
        eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
        eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")

        # Lists give up after 6 as well
        eq(r([]), "[]")
        eq(r([1]), "[1]")
        eq(r([1, 2, 3]), "[1, 2, 3]")
        eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
        eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")

        # Dictionaries give up after 4.
        eq(r({}), "{}")
        d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
        eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
        d['arthur'] = 1
        eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")

    def test_numbers(self):
        eq = self.assertEquals
        eq(r(123), repr(123))
        eq(r(123L), repr(123L))
        eq(r(1.0/3), repr(1.0/3))

        n = 10L**100
        expected = `n`[:18] + "..." + `n`[-19:]
        eq(r(n), expected)

    def test_instance(self):
        eq = self.assertEquals
        i1 = ClassWithRepr("a")
        eq(r(i1), repr(i1))
        
        i2 = ClassWithRepr("x"*1000)
        expected = `i2`[:13] + "..." + `i2`[-14:]
        eq(r(i2), expected)

        i3 = ClassWithFailingRepr()
        eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))

    def test_nesting(self):
        eq = self.assertEquals
        # everything is meant to give up after 6 levels.
        eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
        eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")

        eq(r(nestedTuple(6)), "(((((((),),),),),),)")
        eq(r(nestedTuple(7)), "(((((((...),),),),),),)")

        eq(r({ nestedTuple(5) : nestedTuple(5) }),
           "{((((((),),),),),): ((((((),),),),),)}")
        eq(r({ nestedTuple(6) : nestedTuple(6) }),
           "{((((((...),),),),),): ((((((...),),),),),)}")

        eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
        eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")


class ClassWithRepr:
    def __init__(self, s):
        self.s = s
    def __repr__(self):
        return "ClassWithLongRepr(%r)" % self.s


class ClassWithFailingRepr:
    def __repr__(self):
        raise Exception("This should be caught by Repr.repr_instance")


run_unittest(ReprTests)

Index: test_mimetools.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_mimetools.py,v
retrieving revision 1.1
retrieving revision 1.1.8.1
diff -C2 -r1.1 -r1.1.8.1
*** test_mimetools.py	2000/09/30 17:03:18	1.1
--- test_mimetools.py	2001/07/21 06:07:13	1.1.8.1
***************
*** 3,7 ****
  
  import string,StringIO
! start = string.letters + "=" + string.digits + "\n"
  for enc in ['7bit','8bit','base64','quoted-printable']:
      print enc,
--- 3,7 ----
  
  import string,StringIO
! start = string.ascii_letters + "=" + string.digits + "\n"
  for enc in ['7bit','8bit','base64','quoted-printable']:
      print enc,

Index: test_ntpath.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_ntpath.py,v
retrieving revision 1.7
retrieving revision 1.7.6.1
diff -C2 -r1.7 -r1.7.6.1
*** test_ntpath.py	2001/02/09 11:50:16	1.7
--- test_ntpath.py	2001/07/21 06:07:13	1.7.6.1
***************
*** 1,3 ****
--- 1,4 ----
  import ntpath
+ from test_support import verbose, TestFailed
  import os
  
***************
*** 5,8 ****
--- 6,10 ----
  
  def tester(fn, wantResult):
+     global errors
      fn = fn.replace("\\", "\\\\")
      gotResult = eval(fn)
***************
*** 13,29 ****
          print " returned: " + str(gotResult)
          print ""
-         global errors
          errors = errors + 1
  
! tester('ntpath.splitdrive("c:\\foo\\bar")', ('c:', '\\foo\\bar'))
! tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint', '\\foo\\bar'))
! tester('ntpath.splitdrive("c:/foo/bar")', ('c:', '/foo/bar'))
! tester('ntpath.splitunc("//conky/mountpoint/foo/bar")', ('//conky/mountpoint', '/foo/bar'))
  
  tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
! tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint\\foo', 'bar'))
  
  tester('ntpath.split("c:\\")', ('c:\\', ''))
! tester('ntpath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint', ''))
  
  tester('ntpath.split("c:/")', ('c:/', ''))
--- 15,36 ----
          print " returned: " + str(gotResult)
          print ""
          errors = errors + 1
  
! tester('ntpath.splitdrive("c:\\foo\\bar")',
!        ('c:', '\\foo\\bar'))
! tester('ntpath.splitunc("\\\\conky\\mountpoint\\foo\\bar")',
!        ('\\\\conky\\mountpoint', '\\foo\\bar'))
! tester('ntpath.splitdrive("c:/foo/bar")',
!        ('c:', '/foo/bar'))
! tester('ntpath.splitunc("//conky/mountpoint/foo/bar")',
!        ('//conky/mountpoint', '/foo/bar'))
  
  tester('ntpath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
! tester('ntpath.split("\\\\conky\\mountpoint\\foo\\bar")',
!        ('\\\\conky\\mountpoint\\foo', 'bar'))
  
  tester('ntpath.split("c:\\")', ('c:\\', ''))
! tester('ntpath.split("\\\\conky\\mountpoint\\")',
!        ('\\\\conky\\mountpoint', ''))
  
  tester('ntpath.split("c:/")', ('c:/', ''))
***************
*** 44,49 ****
         "/home/swen/spam")
  
  if errors:
!     print str(errors) + " errors."
! else:
      print "No errors.  Thank your lucky stars."
--- 51,72 ----
         "/home/swen/spam")
  
+ tester('ntpath.join("")', '')
+ tester('ntpath.join("", "", "")', '')
+ tester('ntpath.join("a")', 'a')
+ tester('ntpath.join("/a")', '/a')
+ tester('ntpath.join("\\a")', '\\a')
+ tester('ntpath.join("a:")', 'a:')
+ tester('ntpath.join("a:", "b")', 'a:b')
+ tester('ntpath.join("a:", "/b")', 'a:/b')
+ tester('ntpath.join("a:", "\\b")', 'a:\\b')
+ tester('ntpath.join("a", "/b")', '/b')
+ tester('ntpath.join("a", "\\b")', '\\b')
+ tester('ntpath.join("a", "b", "c")', 'a\\b\\c')
+ tester('ntpath.join("a\\", "b", "c")', 'a\\b\\c')
+ tester('ntpath.join("a", "b\\", "c")', 'a\\b\\c')
+ tester('ntpath.join("a", "b", "\\c")', '\\c')
+ 
  if errors:
!     raise TestFailed(str(errors) + " errors.")
! elif verbose:
      print "No errors.  Thank your lucky stars."

Index: test_os.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_os.py,v
retrieving revision 1.2.2.1
retrieving revision 1.2.2.2
diff -C2 -r1.2.2.1 -r1.2.2.2
*** test_os.py	2001/07/18 04:13:56	1.2.2.1
--- test_os.py	2001/07/21 06:07:13	1.2.2.2
***************
*** 53,57 ****
              return
          self.check_tempfile(os.tmpnam())
!         
  
  
--- 53,57 ----
              return
          self.check_tempfile(os.tmpnam())
! 
  
  

Index: test_quopri.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_quopri.py,v
retrieving revision 1.2.2.1
retrieving revision 1.2.2.2
diff -C2 -r1.2.2.1 -r1.2.2.2
*** test_quopri.py	2001/07/07 22:55:29	1.2.2.1
--- test_quopri.py	2001/07/21 06:07:13	1.2.2.2
***************
*** 6,10 ****
  
  
! 
  ENCSAMPLE = """\
  Here's a bunch of special=20
--- 6,10 ----
  
  
! 
  ENCSAMPLE = """\
  Here's a bunch of special=20
***************
*** 26,31 ****
  
  # First line ends with a space
! DECSAMPLE = """\
! Here's a bunch of special 
  
  ¡¢£¤¥¦§¨©
--- 26,31 ----
  
  # First line ends with a space
! DECSAMPLE = "Here's a bunch of special \n" + \
! """\
  
  ¡¢£¤¥¦§¨©
***************
*** 44,49 ****
  """
  
  
- 
  class QuopriTestCase(unittest.TestCase):
      # Each entry is a tuple of (plaintext, encoded string).  These strings are
--- 44,49 ----
  """
  
+ 
  
  class QuopriTestCase(unittest.TestCase):
      # Each entry is a tuple of (plaintext, encoded string).  These strings are
***************
*** 104,116 ****
          ('hello\tworld', 'hello=09world'),
          )
!         
      def test_encodestring(self):
          for p, e in self.STRINGS:
              self.assert_(encodestring(p) == e)
!         
      def test_decodestring(self):
          for p, e in self.STRINGS:
              self.assert_(decodestring(e) == p)
!         
      def test_idempotent_string(self):
          for p, e in self.STRINGS:
--- 104,116 ----
          ('hello\tworld', 'hello=09world'),
          )
! 
      def test_encodestring(self):
          for p, e in self.STRINGS:
              self.assert_(encodestring(p) == e)
! 
      def test_decodestring(self):
          for p, e in self.STRINGS:
              self.assert_(decodestring(e) == p)
! 
      def test_idempotent_string(self):
          for p, e in self.STRINGS:
***************
*** 135,139 ****
              self.assert_(encodestring(p, quotetabs=1) == e)
              self.assert_(decodestring(e) == p)
  
- 
  test_support.run_unittest(QuopriTestCase)
--- 135,139 ----
              self.assert_(encodestring(p, quotetabs=1) == e)
              self.assert_(decodestring(e) == p)
+ 
  
  test_support.run_unittest(QuopriTestCase)

Index: test_sax.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sax.py,v
retrieving revision 1.16
retrieving revision 1.16.6.1
diff -C2 -r1.16 -r1.16.6.1
*** test_sax.py	2001/01/18 02:22:22	1.16
--- test_sax.py	2001/07/21 06:07:13	1.16.6.1
***************
*** 9,13 ****
      # don't try to test this module if we cannot create a parser
      raise ImportError("no XML parsers available")
! from xml.sax.saxutils import XMLGenerator, escape, XMLFilterBase
  from xml.sax.expatreader import create_parser
  from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
--- 9,13 ----
      # don't try to test this module if we cannot create a parser
      raise ImportError("no XML parsers available")
! from xml.sax.saxutils import XMLGenerator, escape, quoteattr, XMLFilterBase
  from xml.sax.expatreader import create_parser
  from xml.sax.xmlreader import InputSource, AttributesImpl, AttributesNSImpl
***************
*** 69,72 ****
--- 69,91 ----
  def test_escape_extra():
      return escape("Hei på deg", {"å" : "&aring;"}) == "Hei p&aring; deg"
+ 
+ # ===== quoteattr
+ 
+ def test_quoteattr_basic():
+     return quoteattr("Donald Duck & Co") == '"Donald Duck &amp; Co"'
+ 
+ def test_single_quoteattr():
+     return (quoteattr('Includes "double" quotes')
+             == '\'Includes "double" quotes\'')
+ 
+ def test_double_quoteattr():
+     return (quoteattr("Includes 'single' quotes")
+             == "\"Includes 'single' quotes\"")
+ 
+ def test_single_double_quoteattr():
+     return (quoteattr("Includes 'single' and \"double\" quotes")
+             == "\"Includes 'single' and &quot;double&quot; quotes\"")
+ 
+ # ===== make_parser
  
  def test_make_parser():

Index: test_unicode.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_unicode.py,v
retrieving revision 1.31.6.1
retrieving revision 1.31.6.2
diff -C2 -r1.31.6.1 -r1.31.6.2
*** test_unicode.py	2001/07/06 07:01:30	1.31.6.1
--- test_unicode.py	2001/07/21 06:07:13	1.31.6.2
***************
*** 446,451 ****
--- 446,459 ----
  verify(u'hello'.encode('latin-1') == 'hello')
  
+ # Roundtrip safety for BMP (just the first 1024 chars)
  u = u''.join(map(unichr, range(1024)))
  for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
+                  'raw_unicode_escape', 'unicode_escape', 'unicode_internal'):
+     verify(unicode(u.encode(encoding),encoding) == u)
+ 
+ # Roundtrip safety for non-BMP (just a few chars)
+ u = u'\U00010001\U00020002\U00030003\U00040004\U00050005'
+ for encoding in ('utf-8',
+                  'utf-16', 'utf-16-le', 'utf-16-be',
                   'raw_unicode_escape', 'unicode_escape', 'unicode_internal'):
      verify(unicode(u.encode(encoding),encoding) == u)