[Python-checkins] CVS: python/dist/src/Lib/test double_const.py,NONE,1.1.4.1 test_call.py,NONE,1.1.4.1 test_codecs.py,NONE,1.1.2.1 test_generators.py,NONE,1.17.2.1 test_htmlparser.py,NONE,1.1.4.1 test_mutants.py,NONE,1.6.4.1 test_pprint.py,NONE,1.4.4.1 test_quopri.py,NONE,1.2.2.1 test_unicode_file.py,NONE,1.1.4.1 test_urllib2.py,NONE,1.2.4.1 re_tests.py,1.28,1.28.4.1 string_tests.py,1.7,1.7.6.1 test_b1.py,1.34,1.34.6.1 test_b2.py,1.24,1.24.6.1 test_binhex.py,1.10,1.10.6.1 test_complex.py,1.1,1.1.4.1 test_contains.py,1.6,1.6.6.1 test_cookie.py,1.9,1.9.4.1 test_copy_reg.py,1.1,1.1.8.1 test_difflib.py,1.1,1.1.6.1 test_doctest.py,1.1,1.1.6.1 test_dospath.py,1.3,1.3.6.1 test_extcall.py,1.14,1.14.4.1 test_fcntl.py,1.17,1.17.4.1 test_fnmatch.py,1.1,1.1.4.1 test_grp.py,1.7,1.7.6.1 test_hash.py,1.2,1.2.6.1 test_import.py,1.3,1.3.4.1 test_iter.py,1.2.2.1,1.2.2.2 test_locale.py,1.2,1.2.4.1 test_mailbox.py,1.3,1.3.4.1 test_minidom.py,1.26,1.26.6.1 test_mmap.py,1.15,1.15.6.1 test_operations.py,1.3,1.3.6.1 test_parser.py,1.6,1.6.6.1 test_pyexpat.py,1.7,1.7.6.1 test_regex.py,1.9,1.9.6.1 test_rfc822.py,1.9,1.9.6.1 test_richcmp.py,1.5,1.5.6.1 test_scope.py,1.14,1.14.4.1 test_sha.py,1.1,1.1.12.1 test_sre.py,1.24,1.24.4.1 test_strop.py,1.10,1.10.6.1 test_struct.py,1.7,1.7.6.1 test_time.py,1.6,1.6.6.1 test_types.py,1.20,1.20.2.1 test_weakref.py,1.7,1.7.4.1 test_xmllib.py,1.4,1.4.6.1

Tim Peters tim_one@users.sourceforge.net
Sat, 07 Jul 2001 15:56:01 -0700


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

Modified Files:
      Tag: descr-branch
	re_tests.py string_tests.py test_b1.py test_b2.py 
	test_binhex.py test_complex.py test_contains.py test_cookie.py 
	test_copy_reg.py test_difflib.py test_doctest.py 
	test_dospath.py test_extcall.py test_fcntl.py test_fnmatch.py 
	test_grp.py test_hash.py test_import.py test_iter.py 
	test_locale.py test_mailbox.py test_minidom.py test_mmap.py 
	test_operations.py test_parser.py test_pyexpat.py 
	test_regex.py test_rfc822.py test_richcmp.py test_scope.py 
	test_sha.py test_sre.py test_strop.py test_struct.py 
	test_time.py test_types.py test_weakref.py test_xmllib.py 
Added Files:
      Tag: descr-branch
	double_const.py test_call.py test_codecs.py test_generators.py 
	test_htmlparser.py test_mutants.py test_pprint.py 
	test_quopri.py test_unicode_file.py test_urllib2.py 
Log Message:
Merge of trunk tag date2001-07-06 into descr-branch.


--- NEW FILE: double_const.py ---
from test_support import TestFailed

# A test for SF bug 422177:  manifest float constants varied way too much in
# precision depending on whether Python was loading a module for the first
# time, or reloading it from a precompiled .pyc.  The "expected" failure
# mode is that when test_import imports this after all .pyc files have been
# erased, it passes, but when test_import imports this from
# double_const.pyc, it fails.  This indicates a woeful loss of precision in
# the marshal format for doubles.  It's also possible that repr() doesn't
# produce enough digits to get reasonable precision for this box.

PI    = 3.14159265358979324
TWOPI = 6.28318530717958648

PI_str    = "3.14159265358979324"
TWOPI_str = "6.28318530717958648"

# Verify that the double x is within a few bits of eval(x_str).
def check_ok(x, x_str):
    assert x > 0.0
    x2 = eval(x_str)
    assert x2 > 0.0
    diff = abs(x - x2)
    # If diff is no larger than 3 ULP (wrt x2), then diff/8 is no larger
    # than 0.375 ULP, so adding diff/8 to x2 should have no effect.
    if x2 + (diff / 8.) != x2:
        raise TestFailed("Manifest const %s lost too much precision " % x_str)

check_ok(PI, PI_str)
check_ok(TWOPI, TWOPI_str)

--- NEW FILE: test_call.py ---
import unittest
from test_support import run_unittest

# The test cases here cover several paths through the function calling
# code.  They depend on the METH_XXX flag that is used to define a C
# function, which can't be verified from Python.  If the METH_XXX decl
# for a C function changes, these tests may not cover the right paths.

class CFunctionCalls(unittest.TestCase):

    def test_varargs0(self):
        self.assertRaises(TypeError, {}.has_key)

    def test_varargs1(self):
        {}.has_key(0)

    def test_varargs2(self):
        self.assertRaises(TypeError, {}.has_key, 0, 1)

    def test_varargs0_ext(self):
        try:
            {}.has_key(*())
        except TypeError:
            pass

    def test_varargs1_ext(self):
        {}.has_key(*(0,))

    def test_varargs2_ext(self):
        try:
            {}.has_key(*(1, 2))
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_varargs0_kw(self):
        self.assertRaises(TypeError, {}.has_key, x=2)

    def test_varargs1_kw(self):
        self.assertRaises(TypeError, {}.has_key, x=2)

    def test_varargs2_kw(self):
        self.assertRaises(TypeError, {}.has_key, x=2, y=2)

    def test_oldargs0_0(self):
        {}.keys()

    def test_oldargs0_1(self):
        self.assertRaises(TypeError, {}.keys, 0)

    def test_oldargs0_2(self):
        self.assertRaises(TypeError, {}.keys, 0, 1)

    def test_oldargs0_0_ext(self):
        {}.keys(*())

    def test_oldargs0_1_ext(self):
        try:
            {}.keys(*(0,))
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_oldargs0_2_ext(self):
        try:
            {}.keys(*(1, 2))
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_oldargs0_0_kw(self):
        try:
            {}.keys(x=2)
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_oldargs0_1_kw(self):
        self.assertRaises(TypeError, {}.keys, x=2)

    def test_oldargs0_2_kw(self):
        self.assertRaises(TypeError, {}.keys, x=2, y=2)

    def test_oldargs1_0(self):
        self.assertRaises(TypeError, {}.update)

    def test_oldargs1_1(self):
        {}.update({})

    def test_oldargs1_2(self):
        self.assertRaises(TypeError, {}.update, {}, 1)

    def test_oldargs1_0_ext(self):
        try:
            {}.update(*())
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_oldargs1_1_ext(self):
        {}.update(*({},))

    def test_oldargs1_2_ext(self):
        try:
            {}.update(*({}, 2))
        except TypeError:
            pass
        else:
            raise RuntimeError

    def test_oldargs1_0_kw(self):
        self.assertRaises(TypeError, {}.update, x=2)

    def test_oldargs1_1_kw(self):
        self.assertRaises(TypeError, {}.update, {}, x=2)

    def test_oldargs1_2_kw(self):
        self.assertRaises(TypeError, {}.update, x=2, y=2)

run_unittest(CFunctionCalls)

--- NEW FILE: test_codecs.py ---
import test_support,unittest
import codecs
import StringIO

class UTF16Test(unittest.TestCase):

    spamle = '\xff\xfes\x00p\x00a\x00m\x00s\x00p\x00a\x00m\x00'
    spambe = '\xfe\xff\x00s\x00p\x00a\x00m\x00s\x00p\x00a\x00m'

    def test_only_one_bom(self):
        _,_,reader,writer = codecs.lookup("utf-16")
        # encode some stream
        s = StringIO.StringIO()
        f = writer(s)
        f.write(u"spam")
        f.write(u"spam")
        d = s.getvalue()
        # check whether there is exactly one BOM in it
        self.assert_(d == self.spamle or d == self.spambe)
        # try to read it back
        s = StringIO.StringIO(d)
        f = reader(s)
        self.assertEquals(f.read(), u"spamspam")

test_support.run_unittest(UTF16Test)

--- NEW FILE: test_generators.py ---
from __future__ import nested_scopes

tutorial_tests = """
Let's try a simple generator:

    >>> def f():
    ...    yield 1
    ...    yield 2

    >>> for i in f():
    ...     print i
    1
    2
    >>> g = f()
    >>> g.next()
    1
    >>> g.next()
    2

[...1329 lines suppressed...]
# Magic test name that regrtest.py invokes *after* importing this module.
# This worms around a bootstrap problem.
# Note that doctest and regrtest both look in sys.argv for a "-v" argument,
# so this works as expected in both ways of running regrtest.
def test_main():
    import doctest, test_generators
    if 0:
        # Temporary block to help track down leaks.  So far, the blame
        # fell mostly on doctest.  Later:  the only leaks remaining are
        # in fun_tests, and only if you comment out the two LazyList.clear()
        # calls.
        for i in range(10000):
            doctest.master = None
            doctest.testmod(test_generators)
    else:
        doctest.testmod(test_generators)

# This part isn't needed for regrtest, but for running the test directly.
if __name__ == "__main__":
    test_main()

--- NEW FILE: test_htmlparser.py ---
"""Tests for HTMLParser.py."""

import HTMLParser
import sys
import test_support
import unittest


class EventCollector(HTMLParser.HTMLParser):

    def __init__(self):
        self.events = []
        self.append = self.events.append
        HTMLParser.HTMLParser.__init__(self)

    def get_events(self):
        # Normalize the list of events so that buffer artefacts don't
        # separate runs of contiguous characters.
        L = []
        prevtype = None
        for event in self.events:
            type = event[0]
            if type == prevtype == "data":
                L[-1] = ("data", L[-1][1] + event[1])
            else:
                L.append(event)
            prevtype = type
        self.events = L
        return L

    # structure markup

    def handle_starttag(self, tag, attrs):
        self.append(("starttag", tag, attrs))

    def handle_startendtag(self, tag, attrs):
        self.append(("startendtag", tag, attrs))

    def handle_endtag(self, tag):
        self.append(("endtag", tag))

    # all other markup

    def handle_comment(self, data):
        self.append(("comment", data))

    def handle_charref(self, data):
        self.append(("charref", data))

    def handle_data(self, data):
        self.append(("data", data))

    def handle_decl(self, data):
        self.append(("decl", data))

    def handle_entityref(self, data):
        self.append(("entityref", data))

    def handle_pi(self, data):
        self.append(("pi", data))


class EventCollectorExtra(EventCollector):

    def handle_starttag(self, tag, attrs):
        EventCollector.handle_starttag(self, tag, attrs)
        self.append(("starttag_text", self.get_starttag_text()))


class TestCaseBase(unittest.TestCase):

    # Constant pieces of source and events
    prologue = ""
    epilogue = ""
    initial_events = []
    final_events = []

    def _run_check(self, source, events, collector=EventCollector):
        parser = collector()
        parser.feed(self.prologue)
        for s in source:
            parser.feed(s)
        for c in self.epilogue:
            parser.feed(c)
        parser.close()
        self.assert_(parser.get_events() ==
                     self.initial_events + events + self.final_events,
                     parser.get_events())

    def _run_check_extra(self, source, events):
        self._run_check(source, events, EventCollectorExtra)

    def _parse_error(self, source):
        def parse(source=source):
            parser = HTMLParser.HTMLParser()
            parser.feed(source)
            parser.close()
        self.assertRaises(HTMLParser.HTMLParseError, parse)


class HTMLParserTestCase(TestCaseBase):

    def check_processing_instruction_only(self):
        self._run_check("<?processing instruction>", [
            ("pi", "processing instruction"),
            ])

    def check_simple_html(self):
        self._run_check("""
<!DOCTYPE html PUBLIC 'foo'>
<HTML>&entity;&#32;
<!--comment1a
-></foo><bar>&lt;<?pi?></foo<bar
comment1b-->
<Img sRc='Bar' isMAP>sample
text
<!--comment2a-- --comment2b-->
</Html>
""", [
    ("data", "\n"),
    ("decl", "DOCTYPE html PUBLIC 'foo'"),
    ("data", "\n"),
    ("starttag", "html", []),
    ("entityref", "entity"),
    ("charref", "32"),
    ("data", "\n"),
    ("comment", "comment1a\n-></foo><bar>&lt;<?pi?></foo<bar\ncomment1b"),
    ("data", "\n"),
    ("starttag", "img", [("src", "Bar"), ("ismap", None)]),
    ("data", "sample\ntext\n"),
    ("comment", "comment2a-- --comment2b"),
    ("data", "\n"),
    ("endtag", "html"),
    ("data", "\n"),
    ])

    def check_bad_nesting(self):
        self._run_check("<a><b></a></b>", [
            ("starttag", "a", []),
            ("starttag", "b", []),
            ("endtag", "a"),
            ("endtag", "b"),
            ])

    def check_attr_syntax(self):
        output = [
          ("starttag", "a", [("b", "v"), ("c", "v"), ("d", "v"), ("e", None)])
          ]
        self._run_check("""<a b='v' c="v" d=v e>""", output)
        self._run_check("""<a  b = 'v' c = "v" d = v e>""", output)
        self._run_check("""<a\nb\n=\n'v'\nc\n=\n"v"\nd\n=\nv\ne>""", output)
        self._run_check("""<a\tb\t=\t'v'\tc\t=\t"v"\td\t=\tv\te>""", output)

    def check_attr_values(self):
        self._run_check("""<a b='xxx\n\txxx' c="yyy\t\nyyy" d='\txyz\n'>""",
                        [("starttag", "a", [("b", "xxx\n\txxx"),
                                            ("c", "yyy\t\nyyy"),
                                            ("d", "\txyz\n")])
                         ])
        self._run_check("""<a b='' c="">""", [
            ("starttag", "a", [("b", ""), ("c", "")]),
            ])

    def check_attr_entity_replacement(self):
        self._run_check("""<a b='&amp;&gt;&lt;&quot;&apos;'>""", [
            ("starttag", "a", [("b", "&><\"'")]),
            ])

    def check_attr_funky_names(self):
        self._run_check("""<a a.b='v' c:d=v e-f=v>""", [
            ("starttag", "a", [("a.b", "v"), ("c:d", "v"), ("e-f", "v")]),
            ])

    def check_starttag_end_boundary(self):
        self._run_check("""<a b='<'>""", [("starttag", "a", [("b", "<")])])
        self._run_check("""<a b='>'>""", [("starttag", "a", [("b", ">")])])

    def check_buffer_artefacts(self):
        output = [("starttag", "a", [("b", "<")])]
        self._run_check(["<a b='<'>"], output)
        self._run_check(["<a ", "b='<'>"], output)
        self._run_check(["<a b", "='<'>"], output)
        self._run_check(["<a b=", "'<'>"], output)
        self._run_check(["<a b='<", "'>"], output)
        self._run_check(["<a b='<'", ">"], output)

        output = [("starttag", "a", [("b", ">")])]
        self._run_check(["<a b='>'>"], output)
        self._run_check(["<a ", "b='>'>"], output)
        self._run_check(["<a b", "='>'>"], output)
        self._run_check(["<a b=", "'>'>"], output)
        self._run_check(["<a b='>", "'>"], output)
        self._run_check(["<a b='>'", ">"], output)

    def check_starttag_junk_chars(self):
        self._parse_error("<")
        self._parse_error("<>")
        self._parse_error("</>")
        self._parse_error("</$>")
        self._parse_error("</")
        self._parse_error("</a")
        self._parse_error("</a")
        self._parse_error("<a<a>")
        self._parse_error("</a<a>")
        self._parse_error("<$")
        self._parse_error("<$>")
        self._parse_error("<!")
        self._parse_error("<a $>")
        self._parse_error("<a")
        self._parse_error("<a foo='bar'")
        self._parse_error("<a foo='bar")
        self._parse_error("<a foo='>'")
        self._parse_error("<a foo='>")
        self._parse_error("<a foo=>")

    def check_declaration_junk_chars(self):
        self._parse_error("<!DOCTYPE foo $ >")

    def check_startendtag(self):
        self._run_check("<p/>", [
            ("startendtag", "p", []),
            ])
        self._run_check("<p></p>", [
            ("starttag", "p", []),
            ("endtag", "p"),
            ])
        self._run_check("<p><img src='foo' /></p>", [
            ("starttag", "p", []),
            ("startendtag", "img", [("src", "foo")]),
            ("endtag", "p"),
            ])

    def check_get_starttag_text(self):
        s = """<foo:bar   \n   one="1"\ttwo=2   >"""
        self._run_check_extra(s, [
            ("starttag", "foo:bar", [("one", "1"), ("two", "2")]),
            ("starttag_text", s)])

    def check_cdata_content(self):
        s = """<script> <!-- not a comment --> &not-an-entity-ref; </script>"""
        self._run_check(s, [
            ("starttag", "script", []),
            ("data", " <!-- not a comment --> &not-an-entity-ref; "),
            ("endtag", "script"),
            ])
        s = """<script> <not a='start tag'> </script>"""
        self._run_check(s, [
            ("starttag", "script", []),
            ("data", " <not a='start tag'> "),
            ("endtag", "script"),
            ])


test_support.run_unittest(HTMLParserTestCase)

--- NEW FILE: test_mutants.py ---
from test_support import verbose, TESTFN
import random
import os

# From SF bug #422121:  Insecurities in dict comparison.

# Safety of code doing comparisons has been an historical Python weak spot.
# The problem is that comparison of structures written in C *naturally*
# wants to hold on to things like the size of the container, or "the
# biggest" containee so far, across a traversal of the container; but
# code to do containee comparisons can call back into Python and mutate
# the container in arbitrary ways while the C loop is in midstream.  If the
# C code isn't extremely paranoid about digging things out of memory on
# each trip, and artificially boosting refcounts for the duration, anything
# from infinite loops to OS crashes can result (yes, I use Windows <wink>).
#
# The other problem is that code designed to provoke a weakness is usually
# white-box code, and so catches only the particular vulnerabilities the
# author knew to protect against.  For example, Python's list.sort() code
# went thru many iterations as one "new" vulnerability after another was
# discovered.
#
# So the dict comparison test here uses a black-box approach instead,
# generating dicts of various sizes at random, and performing random
# mutations on them at random times.  This proved very effective,
# triggering at least six distinct failure modes the first 20 times I
# ran it.  Indeed, at the start, the driver never got beyond 6 iterations
# before the test died.

# The dicts are global to make it easy to mutate tham from within functions.
dict1 = {}
dict2 = {}

# The current set of keys in dict1 and dict2.  These are materialized as
# lists to make it easy to pick a dict key at random.
dict1keys = []
dict2keys = []

# Global flag telling maybe_mutate() wether to *consider* mutating.
mutate = 0

# If global mutate is true, consider mutating a dict.  May or may not
# mutate a dict even if mutate is true.  If it does decide to mutate a
# dict, it picks one of {dict1, dict2} at random, and deletes a random
# entry from it; or, more rarely, adds a random element.

def maybe_mutate():
    global mutate
    if not mutate:
        return
    if random.random() < 0.5:
        return

    if random.random() < 0.5:
        target, keys = dict1, dict1keys
    else:
        target, keys = dict2, dict2keys

    if random.random() < 0.2:
        # Insert a new key.
        mutate = 0   # disable mutation until key inserted
        while 1:
            newkey = Horrid(random.randrange(100))
            if newkey not in target:
                break
        target[newkey] = Horrid(random.randrange(100))
        keys.append(newkey)
        mutate = 1

    elif keys:
        # Delete a key at random.
        i = random.randrange(len(keys))
        key = keys[i]
        del target[key]
        # CAUTION:  don't use keys.remove(key) here.  Or do <wink>.  The
        # point is that .remove() would trigger more comparisons, and so
        # also more calls to this routine.  We're mutating often enough
        # without that.
        del keys[i]

# A horrid class that triggers random mutations of dict1 and dict2 when
# instances are compared.

class Horrid:
    def __init__(self, i):
        # Comparison outcomes are determined by the value of i.
        self.i = i

        # An artificial hashcode is selected at random so that we don't
        # have any systematic relationship between comparison outcomes
        # (based on self.i and other.i) and relative position within the
        # hash vector (based on hashcode).
        self.hashcode = random.randrange(1000000000)

    def __hash__(self):
        return self.hashcode

    def __cmp__(self, other):
        maybe_mutate()   # The point of the test.
        return cmp(self.i, other.i)

    def __repr__(self):
        return "Horrid(%d)" % self.i

# Fill dict d with numentries (Horrid(i), Horrid(j)) key-value pairs,
# where i and j are selected at random from the candidates list.
# Return d.keys() after filling.

def fill_dict(d, candidates, numentries):
    d.clear()
    for i in xrange(numentries):
        d[Horrid(random.choice(candidates))] = \
            Horrid(random.choice(candidates))
    return d.keys()

# Test one pair of randomly generated dicts, each with n entries.
# Note that dict comparison is trivial if they don't have the same number
# of entires (then the "shorter" dict is instantly considered to be the
# smaller one, without even looking at the entries).

def test_one(n):
    global mutate, dict1, dict2, dict1keys, dict2keys

    # Fill the dicts without mutating them.
    mutate = 0
    dict1keys = fill_dict(dict1, range(n), n)
    dict2keys = fill_dict(dict2, range(n), n)

    # Enable mutation, then compare the dicts so long as they have the
    # same size.
    mutate = 1
    if verbose:
        print "trying w/ lengths", len(dict1), len(dict2),
    while dict1 and len(dict1) == len(dict2):
        if verbose:
            print ".",
        c = cmp(dict1, dict2)
    if verbose:
        print

# Run test_one n times.  At the start (before the bugs were fixed), 20
# consecutive runs of this test each blew up on or before the sixth time
# test_one was run.  So n doesn't have to be large to get an interesting
# test.
# OTOH, calling with large n is also interesting, to ensure that the fixed
# code doesn't hold on to refcounts *too* long (in which case memory would
# leak).

def test(n):
    for i in xrange(n):
        test_one(random.randrange(1, 100))

# See last comment block for clues about good values for n.
test(100)

##########################################################################
# Another segfault bug, distilled by Michael Hudson from a c.l.py post.

class Child:
    def __init__(self, parent):
        self.__dict__['parent'] = parent
    def __getattr__(self, attr):
        self.parent.a = 1
        self.parent.b = 1
        self.parent.c = 1
        self.parent.d = 1
        self.parent.e = 1
        self.parent.f = 1
        self.parent.g = 1
        self.parent.h = 1
        self.parent.i = 1
        return getattr(self.parent, attr)

class Parent:
    def __init__(self):
        self.a = Child(self)

# Hard to say what this will print!  May vary from time to time.  But
# we're specifically trying to test the tp_print slot here, and this is
# the clearest way to do it.  We print the result to a temp file so that
# the expected-output file doesn't need to change.

f = open(TESTFN, "w")
print >> f, Parent().__dict__
f.close()
os.unlink(TESTFN)

##########################################################################
# And another core-dumper from Michael Hudson.

dict = {}

# Force dict to malloc its table.
for i in range(1, 10):
    dict[i] = i

f = open(TESTFN, "w")

class Machiavelli:
    def __repr__(self):
        dict.clear()

        # Michael sez:  "doesn't crash without this.  don't know why."
        # Tim sez:  "luck of the draw; crashes with or without for me."
        print >> f

        return `"machiavelli"`

    def __hash__(self):
        return 0

dict[Machiavelli()] = Machiavelli()

print >> f, str(dict)
f.close()
os.unlink(TESTFN)
del f, dict


##########################################################################
# And another core-dumper from Michael Hudson.

dict = {}

# let's force dict to malloc its table
for i in range(1, 10):
    dict[i] = i

class Machiavelli2:
    def __eq__(self, other):
        dict.clear()
        return 1

    def __hash__(self):
        return 0

dict[Machiavelli2()] = Machiavelli2()

try:
    dict[Machiavelli2()]
except KeyError:
    pass

del dict

##########################################################################
# And another core-dumper from Michael Hudson.

dict = {}

# let's force dict to malloc its table
for i in range(1, 10):
    dict[i] = i

class Machiavelli3:
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        if self.id == other.id:
            dict.clear()
            return 1
        else:
            return 0

    def __repr__(self):
        return "%s(%s)"%(self.__class__.__name__, self.id)

    def __hash__(self):
        return 0

dict[Machiavelli3(1)] = Machiavelli3(0)
dict[Machiavelli3(2)] = Machiavelli3(0)

f = open(TESTFN, "w")
try:
    try:
        print >> f, dict[Machiavelli3(2)]
    except KeyError:
        pass
finally:
    f.close()
    os.unlink(TESTFN)

del dict

--- NEW FILE: test_pprint.py ---
import pprint
import unittest

import test_support


class QueryTestCase(unittest.TestCase):

    def setUp(self):
        self.a = range(100)
        self.b = range(200)
        self.a[-12] = self.b

    def test_basic(self):
        """Verify .isrecursive() and .isreadable() w/o recursion."""
        verify = self.assert_
        for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, u"yaddayadda",
                     self.a, self.b):
            verify(not pprint.isrecursive(safe),
                   "expected not isrecursive for " + `safe`)
            verify(pprint.isreadable(safe),
                   "expected isreadable for " + `safe`)

    def test_knotted(self):
        """Verify .isrecursive() and .isreadable() w/ recursion."""
        # Tie a knot.
        self.b[67] = self.a
        # Messy dict.
        self.d = {}
        self.d[0] = self.d[1] = self.d[2] = self.d

        verify = self.assert_

        for icky in self.a, self.b, self.d, (self.d, self.d):
            verify(pprint.isrecursive(icky), "expected isrecursive")
            verify(not pprint.isreadable(icky),  "expected not isreadable")

        # Break the cycles.
        self.d.clear()
        del self.a[:]
        del self.b[:]

        for safe in self.a, self.b, self.d, (self.d, self.d):
            verify(not pprint.isrecursive(safe),
                   "expected not isrecursive for " + `safe`)
            verify(pprint.isreadable(safe),
                   "expected isreadable for " + `safe`)

    def test_unreadable(self):
        """Not recursive but not readable anyway."""
        verify = self.assert_
        for unreadable in type(3), pprint, pprint.isrecursive:
            verify(not pprint.isrecursive(unreadable),
                   "expected not isrecursive for " + `unreadable`)
            verify(not pprint.isreadable(unreadable),
                   "expected not isreadable for " + `unreadable`)

    def test_same_as_repr(self):
        "Simple objects and small containers that should be same as repr()."
        verify = self.assert_
        for simple in (0, 0L, 0+0j, 0.0, "", u"", (), [], {}, verify, pprint,
                       -6, -6L, -6-6j, -1.5, "x", u"x", (3,), [3], {3: 6},
                       (1,2), [3,4], {5: 6, 7: 8},
                       {"xy\tab\n": (3,), 5: [[]], (): {}},
                       range(10, -11, -1)
                      ):
            native = repr(simple)
            for function in "pformat", "saferepr":
                f = getattr(pprint, function)
                got = f(simple)
                verify(native == got, "expected %s got %s from pprint.%s" %
                                      (native, got, function))

test_support.run_unittest(QueryTestCase)

--- NEW FILE: test_quopri.py ---
import test_support
import unittest

from cStringIO import StringIO
from quopri import *



ENCSAMPLE = """\
Here's a bunch of special=20

=A1=A2=A3=A4=A5=A6=A7=A8=A9
=AA=AB=AC=AD=AE=AF=B0=B1=B2=B3
=B4=B5=B6=B7=B8=B9=BA=BB=BC=BD=BE
=BF=C0=C1=C2=C3=C4=C5=C6
=C7=C8=C9=CA=CB=CC=CD=CE=CF
=D0=D1=D2=D3=D4=D5=D6=D7
=D8=D9=DA=DB=DC=DD=DE=DF
=E0=E1=E2=E3=E4=E5=E6=E7
=E8=E9=EA=EB=EC=ED=EE=EF
=F0=F1=F2=F3=F4=F5=F6=F7
=F8=F9=FA=FB=FC=FD=FE=FF

characters... have fun!
"""

# First line ends with a space
DECSAMPLE = """\
Here's a bunch of special 

¡¢£¤¥¦§¨©
ª«¬­®¯°±²³
´µ¶·¸¹º»¼½¾
¿ÀÁÂÃÄÅÆ
ÇÈÉÊËÌÍÎÏ
ÐÑÒÓÔÕÖ×
ØÙÚÛÜÝÞß
àáâãäåæç
èéêëìíîï
ðñòóôõö÷
øùúûüýþÿ

characters... have fun!
"""



class QuopriTestCase(unittest.TestCase):
    # Each entry is a tuple of (plaintext, encoded string).  These strings are
    # used in the "quotetabs=0" tests.
    STRINGS = (
        # Some normal strings
        ('hello', 'hello'),
        ('''hello
        there
        world''', '''hello
        there
        world'''),
        ('''hello
        there
        world
''', '''hello
        there
        world
'''),
        ('\201\202\203', '=81=82=83'),
        # Add some trailing MUST QUOTE strings
        ('hello ', 'hello=20'),
        ('hello\t', 'hello=09'),
        # Some long lines.  First, a single line of 108 characters
        ('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxØÙÚÛÜÝÞßxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
         '''xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=D8=D9=DA=DB=DC=DD=DE=DFx=
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'''),
        # A line of exactly 76 characters, no soft line break should be needed
        ('yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy',
        'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'),
        # A line of 77 characters, forcing a soft line break at position 75,
        # and a second line of exactly 2 characters (because the soft line
        # break `=' sign counts against the line length limit).
        ('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',
         '''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=
zz'''),
        # A line of 151 characters, forcing a soft line break at position 75,
        # with a second line of exactly 76 characters and no trailing =
        ('zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz',
         '''zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''),
        # A string containing a hard line break, but which the first line is
        # 151 characters and the second line is exactly 76 characters.  This
        # should leave us with three lines, the first which has a soft line
        # break, and which the second and third do not.
        ('''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz''',
         '''yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy=
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz'''),
        # Now some really complex stuff ;)
        (DECSAMPLE, ENCSAMPLE),
        )

    # These are used in the "quotetabs=1" tests.
    ESTRINGS = (
        ('hello world', 'hello=20world'),
        ('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:
            self.assert_(decodestring(encodestring(e)) == e)

    def test_encode(self):
        for p, e in self.STRINGS:
            infp = StringIO(p)
            outfp = StringIO()
            encode(infp, outfp, quotetabs=0)
            self.assert_(outfp.getvalue() == e)

    def test_decode(self):
        for p, e in self.STRINGS:
            infp = StringIO(e)
            outfp = StringIO()
            decode(infp, outfp)
            self.assert_(outfp.getvalue() == p)

    def test_embedded_ws(self):
        for p, e in self.ESTRINGS:
            self.assert_(encodestring(p, quotetabs=1) == e)
            self.assert_(decodestring(e) == p)


test_support.run_unittest(QuopriTestCase)

--- NEW FILE: test_unicode_file.py ---
# Test some Unicode file name semantics
# We dont test many operations on files other than
# that their names can be used with Unicode characters.
import os

from test_support import verify, TestSkipped, TESTFN_UNICODE
try:
    from test_support import TESTFN_ENCODING
except ImportError:
    raise TestSkipped("No Unicode filesystem semantics on this platform.")

TESTFN_ENCODED = TESTFN_UNICODE.encode(TESTFN_ENCODING)

# Check with creation as Unicode string.
f = open(TESTFN_UNICODE, 'wb')
if not os.path.isfile(TESTFN_UNICODE):
    print "File doesn't exist after creating it"

if not os.path.isfile(TESTFN_ENCODED):
    print "File doesn't exist (encoded string) after creating it"

f.close()

# Test stat and chmod
if os.stat(TESTFN_ENCODED) != os.stat(TESTFN_UNICODE):
    print "os.stat() did not agree on the 2 filenames"
os.chmod(TESTFN_ENCODED, 0777)
os.chmod(TESTFN_UNICODE, 0777)

# Test rename
os.rename(TESTFN_ENCODED, TESTFN_ENCODED + ".new")
os.rename(TESTFN_UNICODE+".new", TESTFN_ENCODED)

os.unlink(TESTFN_ENCODED)
if os.path.isfile(TESTFN_ENCODED) or \
   os.path.isfile(TESTFN_UNICODE):
    print "File exists after deleting it"

# Check with creation as encoded string.
f = open(TESTFN_ENCODED, 'wb')
if not os.path.isfile(TESTFN_UNICODE) or \
   not os.path.isfile(TESTFN_ENCODED):
    print "File doesn't exist after creating it"

path, base = os.path.split(os.path.abspath(TESTFN_ENCODED))
if base not in os.listdir(path):
    print "Filename did not appear in os.listdir()"

f.close()
os.unlink(TESTFN_UNICODE)
if os.path.isfile(TESTFN_ENCODED) or \
   os.path.isfile(TESTFN_UNICODE):
    print "File exists after deleting it"

# test os.open
f = os.open(TESTFN_ENCODED, os.O_CREAT)
if not os.path.isfile(TESTFN_UNICODE) or \
   not os.path.isfile(TESTFN_ENCODED):
    print "File doesn't exist after creating it"
os.close(f)
os.unlink(TESTFN_UNICODE)

# Test directories etc
cwd = os.getcwd()
abs_encoded = os.path.abspath(TESTFN_ENCODED) + ".dir"
abs_unicode = os.path.abspath(TESTFN_UNICODE) + ".dir"
os.mkdir(abs_encoded)
try:
    os.chdir(abs_encoded)
    os.chdir(abs_unicode)
finally:
    os.chdir(cwd)
    os.rmdir(abs_unicode)
os.mkdir(abs_unicode)
try:
    os.chdir(abs_encoded)
    os.chdir(abs_unicode)
finally:
    os.chdir(cwd)
    os.rmdir(abs_encoded)
print "All the Unicode tests appeared to work"

--- NEW FILE: test_urllib2.py ---
from test_support import verify
import urllib2

# A couple trivial tests

try:
    urllib2.urlopen('bogus url')
except ValueError:
    pass
else:
    verify(0)

file_url = "file://%s" % urllib2.__file__
f = urllib2.urlopen(file_url)
buf = f.read()
f.close()

Index: re_tests.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/re_tests.py,v
retrieving revision 1.28
retrieving revision 1.28.4.1
diff -C2 -r1.28 -r1.28.4.1
*** re_tests.py	2001/03/22 15:50:10	1.28
--- re_tests.py	2001/07/07 22:55:28	1.28.4.1
***************
*** 639,642 ****
--- 639,644 ----
      # bug 130748: ^* should be an error (nothing to repeat)
      (r'^*', '', SYNTAX_ERROR),
+     # bug 133283: minimizing repeat bug
+     (r'"(?:\\"|[^"])*?"', r'"\""', SUCCEED, 'found', r'"\"'),
  ]
  

Index: string_tests.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/string_tests.py,v
retrieving revision 1.7
retrieving revision 1.7.6.1
diff -C2 -r1.7 -r1.7.6.1
*** string_tests.py	2001/02/09 11:43:35	1.7
--- string_tests.py	2001/07/07 22:55:28	1.7.6.1
***************
*** 2,5 ****
--- 2,6 ----
  
  import string
+ from test_support import verify, verbose, TestFailed
  
  transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
***************
*** 178,181 ****
--- 179,188 ----
      test('replace', 'one!two!three!', 'one!two!three!', 'x', '@')
      test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2)
+     # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with
+     # MemoryError due to empty result (platform malloc issue when requesting
+     # 0 bytes).
+     test('replace', '123', '', '123', '')
+     test('replace', '123123', '', '123', '')
+     test('replace', '123x123', 'x', '123', '')
  
      test('startswith', 'hello', 1, 'he')
***************
*** 207,208 ****
--- 214,233 ----
      test('endswith', 'ab', 0, 'ab', 0, 1)
      test('endswith', 'ab', 0, 'ab', 0, 0)
+ 
+     # Encoding/decoding
+     codecs = [('rot13', 'uryyb jbeyq'),
+               ('base64', 'aGVsbG8gd29ybGQ=\n'),
+               ('hex', '68656c6c6f20776f726c64'),
+               ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')]
+     for encoding, data in codecs:
+         test('encode', 'hello world', data, encoding)
+         test('decode', data, 'hello world', encoding)
+     # zlib is optional, so we make the test optional too...
+     try:
+         import zlib
+     except ImportError:
+         pass
+     else:
+         data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'
+         verify('hello world'.encode('zlib') == data)
+         verify(data.decode('zlib') == 'hello world')

Index: test_b1.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_b1.py,v
retrieving revision 1.34
retrieving revision 1.34.6.1
diff -C2 -r1.34 -r1.34.6.1
*** test_b1.py	2001/01/22 19:30:07	1.34
--- test_b1.py	2001/07/07 22:55:28	1.34.6.1
***************
*** 368,371 ****
--- 368,378 ----
      raise TestFailed, "int(%s)" % `s[1:]` + " should raise ValueError"
  
+ # SF bug 434186:  0x80000000/2 != 0x80000000>>1.
+ # Worked by accident in Windows release build, but failed in debug build.
+ # Failed in all Linux builds.
+ x = -1-sys.maxint
+ if x >> 1 != x/2:
+     raise TestFailed("x >> 1 != x/2 when x == -1-sys.maxint")
+ 
  print 'isinstance'
  class C:

Index: test_b2.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_b2.py,v
retrieving revision 1.24
retrieving revision 1.24.6.1
diff -C2 -r1.24 -r1.24.6.1
*** test_b2.py	2001/01/19 21:57:52	1.24
--- test_b2.py	2001/07/07 22:55:28	1.24.6.1
***************
*** 255,272 ****
  if tuple(xrange(0,10,2)) != tuple(range(0,10,2)):
      raise TestFailed, 'xrange(0,10,2)'
- # regression tests for SourceForge bug #121695
- def _range_test(r):
-     verify(r.start != r.stop, 'Test not valid for passed-in xrange object.')
-     if r.stop in r:
-         raise TestFailed, 'r.stop in ' + `r`
-     if r.stop-r.step not in r:
-         raise TestFailed, 'r.stop-r.step not in ' + `r`
-     if r.start not in r:
-         raise TestFailed, 'r.start not in ' + `r`
-     if r.stop+r.step in r:
-         raise TestFailed, 'r.stop+r.step in ' + `r`
- _range_test(xrange(10))
- _range_test(xrange(9, -1, -1))
- _range_test(xrange(0, 10, 2))
  
  print 'zip'
--- 255,258 ----
***************
*** 310,314 ****
  try:
      zip(a, G())
! except AttributeError:
      exc = 1
  except:
--- 296,300 ----
  try:
      zip(a, G())
! except TypeError:
      exc = 1
  except:
***************
*** 316,320 ****
      raise TestFailed, 'zip(a, b) - b instance w/o __getitem__'
  if not exc:
!     raise TestFailed, 'zip(a, b) - missing expected AttributeError'
  
  
--- 302,306 ----
      raise TestFailed, 'zip(a, b) - b instance w/o __getitem__'
  if not exc:
!     raise TestFailed, 'zip(a, b) - missing expected TypeError'
  
  

Index: test_binhex.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_binhex.py,v
retrieving revision 1.10
retrieving revision 1.10.6.1
diff -C2 -r1.10 -r1.10.6.1
*** test_binhex.py	2001/01/17 21:51:36	1.10
--- test_binhex.py	2001/07/07 22:55:28	1.10.6.1
***************
*** 3,47 ****
  
     Uses the mechanism of the python binhex module
!    Roger E. Masse
  """
  import binhex
  import tempfile
! from test_support import verbose, TestSkipped
  
- def test():
  
!     try:
!         fname1 = tempfile.mktemp()
!         fname2 = tempfile.mktemp()
!         f = open(fname1, 'w')
!     except:
!         raise TestSkipped, "Cannot test binhex without a temp file"
! 
!     start = 'Jack is my hero'
!     f.write(start)
!     f.close()
! 
!     binhex.binhex(fname1, fname2)
!     if verbose:
!         print 'binhex'
! 
!     binhex.hexbin(fname2, fname1)
!     if verbose:
!         print 'hexbin'
! 
!     f = open(fname1, 'r')
!     finish = f.readline()
!     f.close()   # on Windows an open file cannot be unlinked
! 
!     if start != finish:
!         print 'Error: binhex != hexbin'
!     elif verbose:
!         print 'binhex == hexbin'
! 
!     try:
!         import os
!         os.unlink(fname1)
!         os.unlink(fname2)
!     except:
!         pass
! test()
--- 3,45 ----
  
     Uses the mechanism of the python binhex module
!    Based on an original test by Roger E. Masse.
  """
  import binhex
+ import os
  import tempfile
! import test_support
! import unittest
  
  
! class BinHexTestCase(unittest.TestCase):
! 
!     def setUp(self):
!         self.fname1 = tempfile.mktemp()
!         self.fname2 = tempfile.mktemp()
! 
!     def tearDown(self):
!         try: os.unlink(self.fname1)
!         except OSError: pass
! 
!         try: os.unlink(self.fname2)
!         except OSError: pass
! 
!     DATA = 'Jack is my hero'
! 
!     def test_binhex(self):
!         f = open(self.fname1, 'w')
!         f.write(self.DATA)
!         f.close()
! 
!         binhex.binhex(self.fname1, self.fname2)
! 
!         binhex.hexbin(self.fname2, self.fname1)
! 
!         f = open(self.fname1, 'r')
!         finish = f.readline()
!         f.close()
! 
!         self.assertEqual(self.DATA, finish)
! 
! 
! test_support.run_unittest(BinHexTestCase)

Index: test_complex.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_complex.py,v
retrieving revision 1.1
retrieving revision 1.1.4.1
diff -C2 -r1.1 -r1.1.4.1
*** test_complex.py	2001/03/18 08:21:56	1.1
--- test_complex.py	2001/07/07 22:55:28	1.1.4.1
***************
*** 6,10 ****
  nerrors = 0
  
! def check_close_real(x, y, eps=1e-12):
      """Return true iff floats x and y "are close\""""
      # put the one with larger magnitude second
--- 6,10 ----
  nerrors = 0
  
! def check_close_real(x, y, eps=1e-9):
      """Return true iff floats x and y "are close\""""
      # put the one with larger magnitude second
***************
*** 18,22 ****
      return abs((x-y)/y) < eps
  
! def check_close(x, y, eps=1e-12):
      """Return true iff complexes x and y "are close\""""
      return check_close_real(x.real, y.real, eps) and \
--- 18,22 ----
      return abs((x-y)/y) < eps
  
! def check_close(x, y, eps=1e-9):
      """Return true iff complexes x and y "are close\""""
      return check_close_real(x.real, y.real, eps) and \
***************
*** 31,40 ****
          if not check_close(q, y):
              nerrors += 1
!             print `z`, "/", `x`, "==", `q`, "but expected", `y`
      if y != 0:
          q = z / y
          if not check_close(q, x):
              nerrors += 1
!             print `z`, "/", `y`, "==", `q`, "but expected", `x`
  
  simple_real = [float(i) for i in range(-5, 6)]
--- 31,40 ----
          if not check_close(q, y):
              nerrors += 1
!             print "%r / %r == %r but expected %r" % (z, x, q, y)
      if y != 0:
          q = z / y
          if not check_close(q, x):
              nerrors += 1
!             print "%r / %r == %r but expected %r" % (z, y, q, x)
  
  simple_real = [float(i) for i in range(-5, 6)]

Index: test_contains.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_contains.py,v
retrieving revision 1.6
retrieving revision 1.6.6.1
diff -C2 -r1.6 -r1.6.6.1
*** test_contains.py	2000/10/23 17:22:07	1.6
--- test_contains.py	2001/07/07 22:55:28	1.6.6.1
***************
*** 32,36 ****
      1 in a
      check(0, "in base_set did not raise error")
! except AttributeError:
      pass
  
--- 32,36 ----
      1 in a
      check(0, "in base_set did not raise error")
! except TypeError:
      pass
  
***************
*** 38,42 ****
      1 not in a
      check(0, "not in base_set did not raise error")
! except AttributeError:
      pass
  
--- 38,42 ----
      1 not in a
      check(0, "not in base_set did not raise error")
! except TypeError:
      pass
  

Index: test_cookie.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_cookie.py,v
retrieving revision 1.9
retrieving revision 1.9.4.1
diff -C2 -r1.9 -r1.9.4.1
*** test_cookie.py	2001/04/06 21:20:58	1.9
--- test_cookie.py	2001/07/07 22:55:28	1.9.4.1
***************
*** 21,25 ****
      print repr(C)
      print str(C)
!     for k, v in dict.items():
          print ' ', k, repr( C[k].value ), repr(v)
          verify(C[k].value == v)
--- 21,27 ----
      print repr(C)
      print str(C)
!     items = dict.items()
!     items.sort()
!     for k, v in items:
          print ' ', k, repr( C[k].value ), repr(v)
          verify(C[k].value == v)

Index: test_copy_reg.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_copy_reg.py,v
retrieving revision 1.1
retrieving revision 1.1.8.1
diff -C2 -r1.1 -r1.1.8.1
*** test_copy_reg.py	2000/10/11 22:17:35	1.1
--- test_copy_reg.py	2001/07/07 22:55:28	1.1.8.1
***************
*** 1,35 ****
  import copy_reg
  
  class C:
      pass
  
  
! try:
!     copy_reg.pickle(C, None, None)
! except TypeError, e:
!     print "Caught expected TypeError:"
!     print e
! else:
!     print "Failed to catch expected TypeError when registering a class type."
! 
! 
! print
! try:
!     copy_reg.pickle(type(1), "not a callable")
! except TypeError, e:
!     print "Caught expected TypeError:"
!     print e
! else:
!     print "Failed to catch TypeError " \
!           "when registering a non-callable reduction function."
! 
! 
! print
! try:
!     copy_reg.pickle(type(1), int, "not a callable")
! except TypeError, e:
!     print "Caught expected TypeError:"
!     print e
! else:
!     print "Failed to catch TypeError " \
!           "when registering a non-callable constructor."
--- 1,25 ----
  import copy_reg
+ import test_support
+ import unittest
  
+ 
  class C:
      pass
  
+ 
+ class CopyRegTestCase(unittest.TestCase):
+ 
+     def test_class(self):
+         self.assertRaises(TypeError, copy_reg.pickle,
+                           C, None, None)
+ 
+     def test_noncallable_reduce(self):
+         self.assertRaises(TypeError, copy_reg.pickle,
+                           type(1), "not a callable")
+ 
+     def test_noncallable_constructor(self):
+         self.assertRaises(TypeError, copy_reg.pickle,
+                           type(1), int, "not a callable")
+ 
  
! test_support.run_unittest(CopyRegTestCase)

Index: test_difflib.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_difflib.py,v
retrieving revision 1.1
retrieving revision 1.1.6.1
diff -C2 -r1.1 -r1.1.6.1
*** test_difflib.py	2001/02/10 08:00:53	1.1
--- test_difflib.py	2001/07/07 22:55:28	1.1.6.1
***************
*** 1,2 ****
  import doctest, difflib
! doctest.testmod(difflib, verbose=1)
--- 1,3 ----
+ from test_support import verbose
  import doctest, difflib
! doctest.testmod(difflib, verbose=verbose)

Index: test_doctest.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_doctest.py,v
retrieving revision 1.1
retrieving revision 1.1.6.1
diff -C2 -r1.1 -r1.1.6.1
*** test_doctest.py	2001/02/10 01:36:47	1.1
--- test_doctest.py	2001/07/07 22:55:28	1.1.6.1
***************
*** 1,2 ****
  import doctest
! doctest.testmod(doctest, verbose=1)
--- 1,3 ----
+ from test_support import verbose
  import doctest
! doctest.testmod(doctest, verbose=verbose)

Index: test_dospath.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_dospath.py,v
retrieving revision 1.3
retrieving revision 1.3.6.1
diff -C2 -r1.3 -r1.3.6.1
*** test_dospath.py	2001/02/09 11:44:24	1.3
--- test_dospath.py	2001/07/07 22:55:28	1.3.6.1
***************
*** 1,47 ****
  import dospath
! import os
  
- errors = 0
  
! def tester(fn, wantResult):
!     fn = fn.replace("\\", "\\\\")
!     gotResult = eval(fn)
!     if wantResult != gotResult:
!         print "error!"
!         print "evaluated: " + str(fn)
!         print "should be: " + str(wantResult)
!         print " returned: " + str(gotResult)
!         print ""
!         global errors
!         errors = errors + 1
! 
! tester('dospath.splitdrive("c:\\foo\\bar")', ('c:', '\\foo\\bar'))
! tester('dospath.splitdrive("c:/foo/bar")', ('c:', '/foo/bar'))
! 
! tester('dospath.split("c:\\foo\\bar")', ('c:\\foo', 'bar'))
! tester('dospath.split("\\\\conky\\mountpoint\\foo\\bar")', ('\\\\conky\\mountpoint\\foo', 'bar'))
! 
! tester('dospath.split("c:\\")', ('c:\\', ''))
! tester('dospath.split("\\\\conky\\mountpoint\\")', ('\\\\conky\\mountpoint', ''))
! 
! tester('dospath.split("c:/")', ('c:/', ''))
! tester('dospath.split("//conky/mountpoint/")', ('//conky/mountpoint', ''))
! 
! tester('dospath.isabs("c:\\")', 1)
! tester('dospath.isabs("\\\\conky\\mountpoint\\")', 1)
! tester('dospath.isabs("\\foo")', 1)
! tester('dospath.isabs("\\foo\\bar")', 1)
! 
! tester('dospath.abspath("C:\\")', "C:\\")
! 
! tester('dospath.commonprefix(["/home/swenson/spam", "/home/swen/spam"])',
!        "/home/swen")
! tester('dospath.commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])',
!        "\\home\\swen\\")
! tester('dospath.commonprefix(["/home/swen/spam", "/home/swen/spam"])',
!        "/home/swen/spam")
! 
! if errors:
!     print str(errors) + " errors."
! else:
!     print "No errors.  Thank your lucky stars."
--- 1,56 ----
  import dospath
! import test_support
! import unittest
  
  
! class DOSPathTestCase(unittest.TestCase):
! 
!     def test_abspath(self):
!         self.assert_(dospath.abspath("C:\\") == "C:\\")
! 
!     def test_isabs(self):
!         isabs = dospath.isabs
!         self.assert_(isabs("c:\\"))
!         self.assert_(isabs("\\\\conky\\mountpoint\\"))
!         self.assert_(isabs("\\foo"))
!         self.assert_(isabs("\\foo\\bar"))
!         self.failIf(isabs("foo"))
!         self.failIf(isabs("foo\\"))
!         self.failIf(isabs("foo\\bar"))
!         self.failIf(isabs("c:foo"))
!         self.failIf(isabs("c:foo\\"))
!         self.failIf(isabs("c:foo\\bar"))
! 
!     def test_commonprefix(self):
!         commonprefix = dospath.commonprefix
!         self.assert_(commonprefix(["/home/swenson/spam", "/home/swen/spam"])
!                      == "/home/swen")
!         self.assert_(commonprefix(["\\home\\swen\\spam", "\\home\\swen\\eggs"])
!                      == "\\home\\swen\\")
!         self.assert_(commonprefix(["/home/swen/spam", "/home/swen/spam"])
!                      == "/home/swen/spam")
! 
!     def test_split(self):
!         split = dospath.split
!         self.assertEquals(split("c:\\foo\\bar"),
!                           ('c:\\foo', 'bar'))
!         self.assertEquals(split("\\\\conky\\mountpoint\\foo\\bar"),
!                           ('\\\\conky\\mountpoint\\foo', 'bar'))
! 
!         self.assertEquals(split("c:\\"), ('c:\\', ''))
!         self.assertEquals(split("\\\\conky\\mountpoint\\"),
!                           ('\\\\conky\\mountpoint', ''))
! 
!         self.assertEquals(split("c:/"), ('c:/', ''))
!         self.assertEquals(split("//conky/mountpoint/"),
!                           ('//conky/mountpoint', ''))
! 
!     def test_splitdrive(self):
!         splitdrive = dospath.splitdrive
!         self.assertEquals(splitdrive("c:\\foo\\bar"), ('c:', '\\foo\\bar'))
!         self.assertEquals(splitdrive("c:/foo/bar"), ('c:', '/foo/bar'))
!         self.assertEquals(splitdrive("foo\\bar"), ('', 'foo\\bar'))
!         self.assertEquals(splitdrive("c:"), ('c:', ''))
! 
! 
! test_support.run_unittest(DOSPathTestCase)

Index: test_extcall.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_extcall.py,v
retrieving revision 1.14
retrieving revision 1.14.4.1
diff -C2 -r1.14 -r1.14.4.1
*** test_extcall.py	2001/04/11 13:53:35	1.14
--- test_extcall.py	2001/07/07 22:55:28	1.14.4.1
***************
*** 1,13 ****
! from test_support import verify, verbose, TestFailed
  from UserList import UserList
  
- def sortdict(d):
-     keys = d.keys()
-     keys.sort()
-     lst = []
-     for k in keys:
-         lst.append("%r: %r" % (k, d[k]))
-     return "{%s}" % ", ".join(lst)
- 
  def f(*a, **k):
      print a, sortdict(k)
--- 1,5 ----
! from test_support import verify, verbose, TestFailed, sortdict
  from UserList import UserList
  
  def f(*a, **k):
      print a, sortdict(k)
***************
*** 59,66 ****
  try:
      g(*Nothing())
! except AttributeError, attr:
      pass
  else:
!     print "should raise AttributeError: __len__"
  
  class Nothing:
--- 51,58 ----
  try:
      g(*Nothing())
! except TypeError, attr:
      pass
  else:
!     print "should raise TypeError"
  
  class Nothing:
***************
*** 69,76 ****
  try:
      g(*Nothing())
! except AttributeError, attr:
      pass
  else:
!     print "should raise AttributeError: __getitem__"
  
  class Nothing:
--- 61,68 ----
  try:
      g(*Nothing())
! except TypeError, attr:
      pass
  else:
!     print "should raise TypeError"
  
  class Nothing:
***************
*** 229,234 ****
                  if vararg: arglist.append('*' + vararg)
                  if kwarg: arglist.append('**' + kwarg)
!                 decl = 'def %s(%s): print "ok %s", a, b, d, e, v, k' % (
!                     name, ', '.join(arglist), name)
                  exec(decl)
                  func = eval(name)
--- 221,227 ----
                  if vararg: arglist.append('*' + vararg)
                  if kwarg: arglist.append('**' + kwarg)
!                 decl = (('def %s(%s): print "ok %s", a, b, d, e, v, ' +
!                          'type(k) is type ("") and k or sortdict(k)')
!                          % (name, ', '.join(arglist), name))
                  exec(decl)
                  func = eval(name)

Index: test_fcntl.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_fcntl.py,v
retrieving revision 1.17
retrieving revision 1.17.4.1
diff -C2 -r1.17 -r1.17.4.1
*** test_fcntl.py	2001/04/11 20:58:20	1.17
--- test_fcntl.py	2001/07/07 22:55:28	1.17.4.1
***************
*** 5,9 ****
  import struct
  import fcntl
- import FCNTL
  import os, sys
  from test_support import verbose, TESTFN
--- 5,8 ----
***************
*** 11,35 ****
  filename = TESTFN
  
- # the example from the library docs
- f = open(filename, 'w')
- rv = fcntl.fcntl(f.fileno(), FCNTL.F_SETFL, os.O_NONBLOCK)
- if verbose:
-     print 'Status from fnctl with O_NONBLOCK: ', rv
- 
  if sys.platform in ('netbsd1', 'Darwin1.2', 'darwin1',
                      'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
                      'bsdos2', 'bsdos3', 'bsdos4',
                      'openbsd', 'openbsd2'):
!     lockdata = struct.pack('lxxxxlxxxxlhh', 0, 0, 0, FCNTL.F_WRLCK, 0)
  elif sys.platform in ['aix3', 'aix4', 'hp-uxB', 'unixware7']:
!     lockdata = struct.pack('hhlllii', FCNTL.F_WRLCK, 0, 0, 0, 0, 0, 0)
  else:
!     lockdata = struct.pack('hhllhh', FCNTL.F_WRLCK, 0, 0, 0, 0, 0)
  if verbose:
      print 'struct.pack: ', `lockdata`
  
! rv = fcntl.fcntl(f.fileno(), FCNTL.F_SETLKW, lockdata)
  if verbose:
      print 'String from fcntl with F_SETLKW: ', `rv`
  
  f.close()
--- 10,45 ----
  filename = TESTFN
  
  if sys.platform in ('netbsd1', 'Darwin1.2', 'darwin1',
                      'freebsd2', 'freebsd3', 'freebsd4', 'freebsd5',
                      'bsdos2', 'bsdos3', 'bsdos4',
                      'openbsd', 'openbsd2'):
!     lockdata = struct.pack('lxxxxlxxxxlhh', 0, 0, 0, fcntl.F_WRLCK, 0)
  elif sys.platform in ['aix3', 'aix4', 'hp-uxB', 'unixware7']:
!     lockdata = struct.pack('hhlllii', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
  else:
!     lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
  if verbose:
      print 'struct.pack: ', `lockdata`
+ 
+ 
+ # the example from the library docs
+ f = open(filename, 'w')
+ rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
+ if verbose:
+     print 'Status from fnctl with O_NONBLOCK: ', rv
  
! rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata)
  if verbose:
      print 'String from fcntl with F_SETLKW: ', `rv`
+ 
+ f.close()
+ os.unlink(filename)
+ 
+ 
+ # Again, but pass the file rather than numeric descriptor:
+ f = open(filename, 'w')
+ rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NONBLOCK)
+ 
+ rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)
  
  f.close()

Index: test_fnmatch.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_fnmatch.py,v
retrieving revision 1.1
retrieving revision 1.1.4.1
diff -C2 -r1.1 -r1.1.4.1
*** test_fnmatch.py	2001/03/21 18:29:24	1.1
--- test_fnmatch.py	2001/07/07 22:55:28	1.1.4.1
***************
*** 1,5 ****
  """Test cases for the fnmatch module."""
  
- import re
  import test_support
  import unittest
--- 1,4 ----

Index: test_grp.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_grp.py,v
retrieving revision 1.7
retrieving revision 1.7.6.1
diff -C2 -r1.7 -r1.7.6.1
*** test_grp.py	2001/01/17 21:51:35	1.7
--- test_grp.py	2001/07/07 22:55:28	1.7.6.1
***************
*** 1,25 ****
! #! /usr/bin/env python
! """Test script for the grp module
!    Roger E. Masse
! """
  
  import grp
! from test_support import verbose
  
! groups = grp.getgrall()
! if verbose:
!     print 'Groups:'
!     for group in groups:
!         print group
! 
! if not groups:
!     if verbose:
!         print "Empty Group Database -- no further tests of grp module possible"
! else:
!     group = grp.getgrgid(groups[0][2])
!     if verbose:
!         print 'Group Entry for GID %d: %s' % (groups[0][2], group)
! 
!     group = grp.getgrnam(groups[0][0])
!     if verbose:
!         print 'Group Entry for group %s: %s' % (groups[0][0], group)
--- 1,22 ----
! """Test script for the grp module."""
  
+ # XXX This really needs some work, but what are the expected invariants?
+ 
  import grp
! import test_support
! import unittest
! 
! 
! class GroupDatabaseTestCase(unittest.TestCase):
! 
!     def setUp(self):
!         self.groups = grp.getgrall()
! 
!     def test_getgrgid(self):
!         entry = grp.getgrgid(self.groups[0][2])
! 
!     def test_getgrnam(self):
!         entry = grp.getgrnam(self.groups[0][0])
! 
  
! test_support.run_unittest(GroupDatabaseTestCase)

Index: test_hash.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_hash.py,v
retrieving revision 1.2
retrieving revision 1.2.6.1
diff -C2 -r1.2 -r1.2.6.1
*** test_hash.py	2000/10/23 17:22:07	1.2
--- test_hash.py	2001/07/07 22:55:28	1.2.6.1
***************
*** 4,23 ****
  
  import test_support
  
  
! def same_hash(*objlist):
!     # hash each object given an raise TestFailed if
!     # the hash values are not all the same
!     hashed = map(hash, objlist)
!     for h in hashed[1:]:
!         if h != hashed[0]:
!             raise TestFailed, "hashed values differ: %s" % `objlist`
  
  
  
! same_hash(1, 1L, 1.0, 1.0+0.0j)
! same_hash(int(1), long(1), float(1), complex(1))
  
! same_hash(long(1.23e300), float(1.23e300))
  
! same_hash(float(0.5), complex(0.5, 0.0))
--- 4,31 ----
  
  import test_support
+ import unittest
  
  
! class HashEqualityTestCase(unittest.TestCase):
  
+     def same_hash(self, *objlist):
+         # Hash each object given and fail if
+         # the hash values are not all the same.
+         hashed = map(hash, objlist)
+         for h in hashed[1:]:
+             if h != hashed[0]:
+                 self.fail("hashed values differ: %s" % `objlist`)
  
+     def test_numeric_literals(self):
+         self.same_hash(1, 1L, 1.0, 1.0+0.0j)
  
!     def test_coerced_integers(self):
!         self.same_hash(int(1), long(1), float(1), complex(1),
!                        int('1'), float('1.0'))
  
!     def test_coerced_floats(self):
!         self.same_hash(long(1.23e300), float(1.23e300))
!         self.same_hash(float(0.5), complex(0.5, 0.0))
  
! 
! test_support.run_unittest(HashEqualityTestCase)

Index: test_import.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_import.py,v
retrieving revision 1.3
retrieving revision 1.3.4.1
diff -C2 -r1.3 -r1.3.4.1
*** test_import.py	2001/03/21 03:58:16	1.3
--- test_import.py	2001/07/07 22:55:28	1.3.4.1
***************
*** 14,17 ****
--- 14,20 ----
      raise TestFailed("import of RAnDoM should have failed (case mismatch)")
  
+ # Another brief digression to test the accuracy of manifest float constants.
+ import double_const  # don't blink -- that *was* the test
+ 
  sys.path.insert(0, os.curdir)
  

Index: test_iter.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_iter.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_iter.py	2001/06/11 19:05:28	1.2.2.1
--- test_iter.py	2001/07/07 22:55:28	1.2.2.2
***************
*** 276,278 ****
--- 276,650 ----
                  pass
  
+     # Test tuples()'s use of iterators.
+     def test_builtin_tuple(self):
+         self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4))
+         self.assertEqual(tuple(SequenceClass(0)), ())
+         self.assertEqual(tuple([]), ())
+         self.assertEqual(tuple(()), ())
+         self.assertEqual(tuple("abc"), ("a", "b", "c"))
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(tuple(d), tuple(d.keys()))
+ 
+         self.assertRaises(TypeError, tuple, list)
+         self.assertRaises(TypeError, tuple, 42)
+ 
+         f = open(TESTFN, "w")
+         try:
+             for i in range(5):
+                 f.write("%d\n" % i)
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n"))
+             f.seek(0, 0)
+             self.assertEqual(tuple(f.xreadlines()),
+                              ("0\n", "1\n", "2\n", "3\n", "4\n"))
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test filter()'s use of iterators.
+     def test_builtin_filter(self):
+         self.assertEqual(filter(None, SequenceClass(5)), range(1, 5))
+         self.assertEqual(filter(None, SequenceClass(0)), [])
+         self.assertEqual(filter(None, ()), ())
+         self.assertEqual(filter(None, "abc"), "abc")
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(filter(None, d), d.keys())
+ 
+         self.assertRaises(TypeError, filter, None, list)
+         self.assertRaises(TypeError, filter, None, 42)
+ 
+         class Boolean:
+             def __init__(self, truth):
+                 self.truth = truth
+             def __nonzero__(self):
+                 return self.truth
+         True = Boolean(1)
+         False = Boolean(0)
+ 
+         class Seq:
+             def __init__(self, *args):
+                 self.vals = args
+             def __iter__(self):
+                 class SeqIter:
+                     def __init__(self, vals):
+                         self.vals = vals
+                         self.i = 0
+                     def __iter__(self):
+                         return self
+                     def next(self):
+                         i = self.i
+                         self.i = i + 1
+                         if i < len(self.vals):
+                             return self.vals[i]
+                         else:
+                             raise StopIteration
+                 return SeqIter(self.vals)
+ 
+         seq = Seq(*([True, False] * 25))
+         self.assertEqual(filter(lambda x: not x, seq), [False]*25)
+         self.assertEqual(filter(lambda x: not x, iter(seq)), [False]*25)
+ 
+     # Test max() and min()'s use of iterators.
+     def test_builtin_max_min(self):
+         self.assertEqual(max(SequenceClass(5)), 4)
+         self.assertEqual(min(SequenceClass(5)), 0)
+         self.assertEqual(max(8, -1), 8)
+         self.assertEqual(min(8, -1), -1)
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(max(d), "two")
+         self.assertEqual(min(d), "one")
+         self.assertEqual(max(d.itervalues()), 3)
+         self.assertEqual(min(iter(d.itervalues())), 1)
+ 
+         f = open(TESTFN, "w")
+         try:
+             f.write("medium line\n")
+             f.write("xtra large line\n")
+             f.write("itty-bitty line\n")
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             self.assertEqual(min(f), "itty-bitty line\n")
+             f.seek(0, 0)
+             self.assertEqual(max(f), "xtra large line\n")
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test map()'s use of iterators.
+     def test_builtin_map(self):
+         self.assertEqual(map(None, SequenceClass(5)), range(5))
+         self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(map(None, d), d.keys())
+         self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items())
+         dkeys = d.keys()
+         expected = [(i < len(d) and dkeys[i] or None,
+                      i,
+                      i < len(d) and dkeys[i] or None)
+                     for i in range(5)]
+         self.assertEqual(map(None, d,
+                                    SequenceClass(5),
+                                    iter(d.iterkeys())),
+                          expected)
+ 
+         f = open(TESTFN, "w")
+         try:
+             for i in range(10):
+                 f.write("xy" * i + "\n") # line i has len 2*i+1
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             self.assertEqual(map(len, f), range(1, 21, 2))
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test zip()'s use of iterators.
+     def test_builtin_zip(self):
+         self.assertRaises(TypeError, zip)
+         self.assertRaises(TypeError, zip, None)
+         self.assertRaises(TypeError, zip, range(10), 42)
+         self.assertRaises(TypeError, zip, range(10), zip)
+ 
+         self.assertEqual(zip(IteratingSequenceClass(3)),
+                          [(0,), (1,), (2,)])
+         self.assertEqual(zip(SequenceClass(3)),
+                          [(0,), (1,), (2,)])
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(d.items(), zip(d, d.itervalues()))
+ 
+         # Generate all ints starting at constructor arg.
+         class IntsFrom:
+             def __init__(self, start):
+                 self.i = start
+ 
+             def __iter__(self):
+                 return self
+ 
+             def next(self):
+                 i = self.i
+                 self.i = i+1
+                 return i
+ 
+         f = open(TESTFN, "w")
+         try:
+             f.write("a\n" "bbb\n" "cc\n")
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             self.assertEqual(zip(IntsFrom(0), f, IntsFrom(-100)),
+                              [(0, "a\n", -100),
+                               (1, "bbb\n", -99),
+                               (2, "cc\n", -98)])
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test reduces()'s use of iterators.
+     def test_builtin_reduce(self):
+         from operator import add
+         self.assertEqual(reduce(add, SequenceClass(5)), 10)
+         self.assertEqual(reduce(add, SequenceClass(5), 42), 52)
+         self.assertRaises(TypeError, reduce, add, SequenceClass(0))
+         self.assertEqual(reduce(add, SequenceClass(0), 42), 42)
+         self.assertEqual(reduce(add, SequenceClass(1)), 0)
+         self.assertEqual(reduce(add, SequenceClass(1), 42), 42)
+ 
+         d = {"one": 1, "two": 2, "three": 3}
+         self.assertEqual(reduce(add, d), "".join(d.keys()))
+ 
+     def test_unicode_join_endcase(self):
+ 
+         # This class inserts a Unicode object into its argument's natural
+         # iteration, in the 3rd position.
+         class OhPhooey:
+             def __init__(self, seq):
+                 self.it = iter(seq)
+                 self.i = 0
+ 
+             def __iter__(self):
+                 return self
+ 
+             def next(self):
+                 i = self.i
+                 self.i = i+1
+                 if i == 2:
+                     return u"fooled you!"
+                 return self.it.next()
+ 
+         f = open(TESTFN, "w")
+         try:
+             f.write("a\n" + "b\n" + "c\n")
+         finally:
+             f.close()
+ 
+         f = open(TESTFN, "r")
+         # Nasty:  string.join(s) can't know whether unicode.join() is needed
+         # until it's seen all of s's elements.  But in this case, f's
+         # iterator cannot be restarted.  So what we're testing here is
+         # whether string.join() can manage to remember everything it's seen
+         # and pass that on to unicode.join().
+         try:
+             got = " - ".join(OhPhooey(f))
+             self.assertEqual(got, u"a\n - b\n - fooled you! - c\n")
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test iterators with 'x in y' and 'x not in y'.
+     def test_in_and_not_in(self):
+         for sc5 in IteratingSequenceClass(5), SequenceClass(5):
+             for i in range(5):
+                 self.assert_(i in sc5)
+             for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5:
+                 self.assert_(i not in sc5)
+ 
+         self.assertRaises(TypeError, lambda: 3 in 12)
+         self.assertRaises(TypeError, lambda: 3 not in map)
+ 
+         d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
+         for k in d:
+             self.assert_(k in d)
+             self.assert_(k not in d.itervalues())
+         for v in d.values():
+             self.assert_(v in d.itervalues())
+             self.assert_(v not in d)
+         for k, v in d.iteritems():
+             self.assert_((k, v) in d.iteritems())
+             self.assert_((v, k) not in d.iteritems())
+ 
+         f = open(TESTFN, "w")
+         try:
+             f.write("a\n" "b\n" "c\n")
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             for chunk in "abc":
+                 f.seek(0, 0)
+                 self.assert_(chunk not in f)
+                 f.seek(0, 0)
+                 self.assert_((chunk + "\n") in f)
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test iterators with operator.countOf (PySequence_Count).
+     def test_countOf(self):
+         from operator import countOf
+         self.assertEqual(countOf([1,2,2,3,2,5], 2), 3)
+         self.assertEqual(countOf((1,2,2,3,2,5), 2), 3)
+         self.assertEqual(countOf("122325", "2"), 3)
+         self.assertEqual(countOf("122325", "6"), 0)
+ 
+         self.assertRaises(TypeError, countOf, 42, 1)
+         self.assertRaises(TypeError, countOf, countOf, countOf)
+ 
+         d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
+         for k in d:
+             self.assertEqual(countOf(d, k), 1)
+         self.assertEqual(countOf(d.itervalues(), 3), 3)
+         self.assertEqual(countOf(d.itervalues(), 2j), 1)
+         self.assertEqual(countOf(d.itervalues(), 1j), 0)
+ 
+         f = open(TESTFN, "w")
+         try:
+             f.write("a\n" "b\n" "c\n" "b\n")
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             for letter, count in ("a", 1), ("b", 2), ("c", 1), ("d", 0):
+                 f.seek(0, 0)
+                 self.assertEqual(countOf(f, letter + "\n"), count)
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+     # Test iterators on RHS of unpacking assignments.
+     def test_unpack_iter(self):
+         a, b = 1, 2
+         self.assertEqual((a, b), (1, 2))
+ 
+         a, b, c = IteratingSequenceClass(3)
+         self.assertEqual((a, b, c), (0, 1, 2))
+ 
+         try:    # too many values
+             a, b = IteratingSequenceClass(3)
+         except ValueError:
+             pass
+         else:
+             self.fail("should have raised ValueError")
+ 
+         try:    # not enough values
+             a, b, c = IteratingSequenceClass(2)
+         except ValueError:
+             pass
+         else:
+             self.fail("should have raised ValueError")
+ 
+         try:    # not iterable
+             a, b, c = len
+         except TypeError:
+             pass
+         else:
+             self.fail("should have raised TypeError")
+ 
+         a, b, c = {1: 42, 2: 42, 3: 42}.itervalues()
+         self.assertEqual((a, b, c), (42, 42, 42))
+ 
+         f = open(TESTFN, "w")
+         lines = ("a\n", "bb\n", "ccc\n")
+         try:
+             for line in lines:
+                 f.write(line)
+         finally:
+             f.close()
+         f = open(TESTFN, "r")
+         try:
+             a, b, c = f
+             self.assertEqual((a, b, c), lines)
+         finally:
+             f.close()
+             try:
+                 unlink(TESTFN)
+             except OSError:
+                 pass
+ 
+         (a, b), (c,) = IteratingSequenceClass(2), {42: 24}
+         self.assertEqual((a, b, c), (0, 1, 42))
+ 
  run_unittest(TestCase)

Index: test_locale.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_locale.py,v
retrieving revision 1.2
retrieving revision 1.2.4.1
diff -C2 -r1.2 -r1.2.4.1
*** test_locale.py	2001/04/15 13:15:56	1.2
--- test_locale.py	2001/07/07 22:55:29	1.2.4.1
***************
*** 37,42 ****
      testformat("%+f", -42, grouping=1, output='-42.000000')
      testformat("%20.f", -42, grouping=1, output='                 -42')
!     testformat("%+10.f", -4200, grouping=1, output='    -4,200')    
!     testformat("%-10.f", 4200, grouping=1, output='4,200     ')    
  finally:
      locale.setlocale(locale.LC_NUMERIC, oldlocale)
--- 37,42 ----
      testformat("%+f", -42, grouping=1, output='-42.000000')
      testformat("%20.f", -42, grouping=1, output='                 -42')
!     testformat("%+10.f", -4200, grouping=1, output='    -4,200')
!     testformat("%-10.f", 4200, grouping=1, output='4,200     ')
  finally:
      locale.setlocale(locale.LC_NUMERIC, oldlocale)

Index: test_mailbox.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_mailbox.py,v
retrieving revision 1.3
retrieving revision 1.3.4.1
diff -C2 -r1.3 -r1.3.4.1
*** test_mailbox.py	2001/04/10 15:01:20	1.3
--- test_mailbox.py	2001/07/07 22:55:29	1.3.4.1
***************
*** 2,7 ****
  import os
  import test_support
  
! # cleanup
  try:
      os.unlink(test_support.TESTFN)
--- 2,9 ----
  import os
  import test_support
+ import time
+ import unittest
  
! # cleanup earlier tests
  try:
      os.unlink(test_support.TESTFN)
***************
*** 9,34 ****
      pass
  
- # create a new maildir mailbox to work with:
- curdir = os.path.join(test_support.TESTFN, "cur")
- newdir = os.path.join(test_support.TESTFN, "new")
- try:
-     os.mkdir(test_support.TESTFN)
-     os.mkdir(curdir)
-     os.mkdir(newdir)
- 
-     # Test for regression on bug #117490:
-     # http://sourceforge.net/bugs/?func=detailbug&bug_id=117490&group_id=5470
-     # Make sure the boxes attribute actually gets set.
-     mbox = mailbox.Maildir(test_support.TESTFN)
-     mbox.boxes
-     print "newly created maildir contains", len(mbox.boxes), "messages"
  
      # XXX We still need more tests!
  
! finally:
!     try: os.rmdir(newdir)
!     except os.error: pass
!     try: os.rmdir(curdir)
!     except os.error: pass
!     try: os.rmdir(test_support.TESTFN)
!     except os.error: pass
--- 11,99 ----
      pass
  
  
+ DUMMY_MESSAGE = """\
+ From: some.body@dummy.domain
+ To: me@my.domain
+ 
+ This is a dummy message.
+ """
+ 
+ 
+ class MaildirTestCase(unittest.TestCase):
+ 
+     def setUp(self):
+         # create a new maildir mailbox to work with:
+         self._dir = test_support.TESTFN
+         os.mkdir(self._dir)
+         os.mkdir(os.path.join(self._dir, "cur"))
+         os.mkdir(os.path.join(self._dir, "tmp"))
+         os.mkdir(os.path.join(self._dir, "new"))
+         self._counter = 1
+         self._msgfiles = []
+ 
+     def tearDown(self):
+         map(os.unlink, self._msgfiles)
+         os.rmdir(os.path.join(self._dir, "cur"))
+         os.rmdir(os.path.join(self._dir, "tmp"))
+         os.rmdir(os.path.join(self._dir, "new"))
+         os.rmdir(self._dir)
+ 
+     def createMessage(self, dir):
+         t = int(time.time() % 1000000)
+         pid = self._counter
+         self._counter += 1
+         filename = "%s.%s.myhostname.mydomain" % (t, pid)
+         tmpname = os.path.join(self._dir, "tmp", filename)
+         newname = os.path.join(self._dir, dir, filename)
+         fp = open(tmpname, "w")
+         self._msgfiles.append(tmpname)
+         fp.write(DUMMY_MESSAGE)
+         fp.close()
+         if hasattr(os, "link"):
+             os.link(tmpname, newname)
+         else:
+             fp = open(newname, "w")
+             fp.write(DUMMY_MESSAGE)
+             fp.close()
+         self._msgfiles.append(newname)
+ 
+     def test_empty_maildir(self):
+         """Test an empty maildir mailbox"""
+         # Test for regression on bug #117490:
+         # Make sure the boxes attribute actually gets set.
+         self.mbox = mailbox.Maildir(test_support.TESTFN)
+         self.assert_(hasattr(self.mbox, "boxes"))
+         self.assert_(len(self.mbox.boxes) == 0)
+         self.assert_(self.mbox.next() is None)
+         self.assert_(self.mbox.next() is None)
+ 
+     def test_nonempty_maildir_cur(self):
+         self.createMessage("cur")
+         self.mbox = mailbox.Maildir(test_support.TESTFN)
+         self.assert_(len(self.mbox.boxes) == 1)
+         self.assert_(self.mbox.next() is not None)
+         self.assert_(self.mbox.next() is None)
+         self.assert_(self.mbox.next() is None)
+ 
+     def test_nonempty_maildir_new(self):
+         self.createMessage("new")
+         self.mbox = mailbox.Maildir(test_support.TESTFN)
+         self.assert_(len(self.mbox.boxes) == 1)
+         self.assert_(self.mbox.next() is not None)
+         self.assert_(self.mbox.next() is None)
+         self.assert_(self.mbox.next() is None)
+ 
+     def test_nonempty_maildir_both(self):
+         self.createMessage("cur")
+         self.createMessage("new")
+         self.mbox = mailbox.Maildir(test_support.TESTFN)
+         self.assert_(len(self.mbox.boxes) == 2)
+         self.assert_(self.mbox.next() is not None)
+         self.assert_(self.mbox.next() is not None)
+         self.assert_(self.mbox.next() is None)
+         self.assert_(self.mbox.next() is None)
+ 
      # XXX We still need more tests!
+ 
  
! test_support.run_unittest(MaildirTestCase)

Index: test_minidom.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_minidom.py,v
retrieving revision 1.26
retrieving revision 1.26.6.1
diff -C2 -r1.26 -r1.26.6.1
*** test_minidom.py	2001/02/21 07:29:48	1.26
--- test_minidom.py	2001/07/07 22:55:29	1.26.6.1
***************
*** 240,244 ****
  def testGetAttributeNode(): pass
  
! def testGetElementsByTagNameNS(): pass
  
  def testGetEmptyNodeListFromElementsByTagNameNS(): pass
--- 240,251 ----
  def testGetAttributeNode(): pass
  
! def testGetElementsByTagNameNS():
!     d="""<foo xmlns:minidom="http://pyxml.sf.net/minidom">
!     <minidom:myelem/>
!     </foo>"""
!     dom = parseString(d)
!     elem = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom","myelem")
!     confirm(len(elem) == 1)
!     dom.unlink()
  
  def testGetEmptyNodeListFromElementsByTagNameNS(): pass

Index: test_mmap.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_mmap.py,v
retrieving revision 1.15
retrieving revision 1.15.6.1
diff -C2 -r1.15 -r1.15.6.1
*** test_mmap.py	2001/02/09 11:49:24	1.15
--- test_mmap.py	2001/07/07 22:55:29	1.15.6.1
***************
*** 1,5 ****
! from test_support import verify
  import mmap
! import os, re, sys
  
  PAGESIZE = mmap.PAGESIZE
--- 1,5 ----
! from test_support import verify, TESTFN
  import mmap
! import os, re
  
  PAGESIZE = mmap.PAGESIZE
***************
*** 8,123 ****
      "Test mmap module on Unix systems and Windows"
  
!     # Create an mmap'ed file
!     f = open('foo', 'w+')
  
!     # Write 2 pages worth of data to the file
!     f.write('\0'* PAGESIZE)
!     f.write('foo')
!     f.write('\0'* (PAGESIZE-3) )
! 
!     m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
!     f.close()
! 
!     # Simple sanity checks
! 
!     print type(m)  # SF bug 128713:  segfaulted on Linux
!     print '  Position of foo:', m.find('foo') / float(PAGESIZE), 'pages'
!     verify(m.find('foo') == PAGESIZE)
! 
!     print '  Length of file:', len(m) / float(PAGESIZE), 'pages'
!     verify(len(m) == 2*PAGESIZE)
! 
!     print '  Contents of byte 0:', repr(m[0])
!     verify(m[0] == '\0')
!     print '  Contents of first 3 bytes:', repr(m[0:3])
!     verify(m[0:3] == '\0\0\0')
! 
!     # Modify the file's content
!     print "\n  Modifying file's content..."
!     m[0] = '3'
!     m[PAGESIZE +3: PAGESIZE +3+3]='bar'
! 
!     # Check that the modification worked
!     print '  Contents of byte 0:', repr(m[0])
!     verify(m[0] == '3')
!     print '  Contents of first 3 bytes:', repr(m[0:3])
!     verify(m[0:3] == '3\0\0')
!     print '  Contents of second page:',  repr(m[PAGESIZE-1 : PAGESIZE + 7])
!     verify(m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0')
! 
!     m.flush()
! 
!     # Test doing a regular expression match in an mmap'ed file
!     match=re.search('[A-Za-z]+', m)
!     if match is None:
!         print '  ERROR: regex match on mmap failed!'
!     else:
!         start, end = match.span(0)
!         length = end - start
! 
!         print '  Regex match on mmap (page start, length of match):',
!         print start / float(PAGESIZE), length
! 
!         verify(start == PAGESIZE)
!         verify(end == PAGESIZE + 6)
! 
!     # test seeking around (try to overflow the seek implementation)
!     m.seek(0,0)
!     print '  Seek to zeroth byte'
!     verify(m.tell() == 0)
!     m.seek(42,1)
!     print '  Seek to 42nd byte'
!     verify(m.tell() == 42)
!     m.seek(0,2)
!     print '  Seek to last byte'
!     verify(m.tell() == len(m))
! 
!     print '  Try to seek to negative position...'
!     try:
!         m.seek(-1)
!     except ValueError:
!         pass
!     else:
!         verify(0, 'expected a ValueError but did not get it')
! 
!     print '  Try to seek beyond end of mmap...'
!     try:
!         m.seek(1,2)
!     except ValueError:
!         pass
!     else:
!         verify(0, 'expected a ValueError but did not get it')
! 
!     print '  Try to seek to negative position...'
!     try:
!         m.seek(-len(m)-1,2)
!     except ValueError:
!         pass
!     else:
!         verify(0, 'expected a ValueError but did not get it')
! 
!     # Try resizing map
!     print '  Attempting resize()'
!     try:
!         m.resize( 512 )
!     except SystemError:
!         # resize() not supported
!         # No messages are printed, since the output of this test suite
!         # would then be different across platforms.
!         pass
!     else:
!         # resize() is supported
!         verify(len(m) == 512,
!                 "len(m) is %d, but expecting 512" % (len(m),) )
!         # Check that we can no longer seek beyond the new size.
          try:
!             m.seek(513,0)
          except ValueError:
              pass
          else:
!             verify(0, 'Could seek beyond the new size')
  
-     m.close()
-     os.unlink("foo")
      print ' Test passed'
  
--- 8,136 ----
      "Test mmap module on Unix systems and Windows"
  
!     # Create a file to be mmap'ed.
!     if os.path.exists(TESTFN):
!         os.unlink(TESTFN)
!     f = open(TESTFN, 'w+')
! 
!     try:    # unlink TESTFN no matter what
!         # Write 2 pages worth of data to the file
!         f.write('\0'* PAGESIZE)
!         f.write('foo')
!         f.write('\0'* (PAGESIZE-3) )
! 
!         m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
!         f.close()
! 
!         # Simple sanity checks
! 
!         print type(m)  # SF bug 128713:  segfaulted on Linux
!         print '  Position of foo:', m.find('foo') / float(PAGESIZE), 'pages'
!         verify(m.find('foo') == PAGESIZE)
! 
!         print '  Length of file:', len(m) / float(PAGESIZE), 'pages'
!         verify(len(m) == 2*PAGESIZE)
! 
!         print '  Contents of byte 0:', repr(m[0])
!         verify(m[0] == '\0')
!         print '  Contents of first 3 bytes:', repr(m[0:3])
!         verify(m[0:3] == '\0\0\0')
! 
!         # Modify the file's content
!         print "\n  Modifying file's content..."
!         m[0] = '3'
!         m[PAGESIZE +3: PAGESIZE +3+3] = 'bar'
! 
!         # Check that the modification worked
!         print '  Contents of byte 0:', repr(m[0])
!         verify(m[0] == '3')
!         print '  Contents of first 3 bytes:', repr(m[0:3])
!         verify(m[0:3] == '3\0\0')
!         print '  Contents of second page:',  repr(m[PAGESIZE-1 : PAGESIZE + 7])
!         verify(m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0')
! 
!         m.flush()
! 
!         # Test doing a regular expression match in an mmap'ed file
!         match = re.search('[A-Za-z]+', m)
!         if match is None:
!             print '  ERROR: regex match on mmap failed!'
!         else:
!             start, end = match.span(0)
!             length = end - start
! 
!             print '  Regex match on mmap (page start, length of match):',
!             print start / float(PAGESIZE), length
! 
!             verify(start == PAGESIZE)
!             verify(end == PAGESIZE + 6)
! 
!         # test seeking around (try to overflow the seek implementation)
!         m.seek(0,0)
!         print '  Seek to zeroth byte'
!         verify(m.tell() == 0)
!         m.seek(42,1)
!         print '  Seek to 42nd byte'
!         verify(m.tell() == 42)
!         m.seek(0,2)
!         print '  Seek to last byte'
!         verify(m.tell() == len(m))
! 
!         print '  Try to seek to negative position...'
!         try:
!             m.seek(-1)
!         except ValueError:
!             pass
!         else:
!             verify(0, 'expected a ValueError but did not get it')
! 
!         print '  Try to seek beyond end of mmap...'
!         try:
!             m.seek(1,2)
!         except ValueError:
!             pass
!         else:
!             verify(0, 'expected a ValueError but did not get it')
  
!         print '  Try to seek to negative position...'
          try:
!             m.seek(-len(m)-1,2)
          except ValueError:
              pass
+         else:
+             verify(0, 'expected a ValueError but did not get it')
+ 
+         # Try resizing map
+         print '  Attempting resize()'
+         try:
+             m.resize( 512 )
+         except SystemError:
+             # resize() not supported
+             # No messages are printed, since the output of this test suite
+             # would then be different across platforms.
+             pass
          else:
!             # resize() is supported
!             verify(len(m) == 512,
!                     "len(m) is %d, but expecting 512" % (len(m),) )
!             # Check that we can no longer seek beyond the new size.
!             try:
!                 m.seek(513,0)
!             except ValueError:
!                 pass
!             else:
!                 verify(0, 'Could seek beyond the new size')
! 
!         m.close()
! 
!     finally:
!         try:
!             f.close()
!         except OSError:
!             pass
!         try:
!             os.unlink(TESTFN)
!         except OSError:
!             pass
  
      print ' Test passed'
  

Index: test_operations.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_operations.py,v
retrieving revision 1.3
retrieving revision 1.3.6.1
diff -C2 -r1.3 -r1.3.6.1
*** test_operations.py	2000/10/23 17:22:07	1.3
--- test_operations.py	2001/07/07 22:55:29	1.3.6.1
***************
*** 12,15 ****
--- 12,17 ----
  
  class BadDictKey:
+     already_printed_raising_error = 0
+ 
      def __hash__(self):
          return hash(self.__class__)
***************
*** 17,21 ****
      def __cmp__(self, other):
          if isinstance(other, self.__class__):
!             print "raising error"
              raise RuntimeError, "gotcha"
          return other
--- 19,30 ----
      def __cmp__(self, other):
          if isinstance(other, self.__class__):
!             if not BadDictKey.already_printed_raising_error:
!                 # How many times __cmp__ gets called depends on the hash
!                 # code and the internals of the dict implementation; we
!                 # know it will be called at least once, but that's it.
!                 # already_printed_raising_error makes sure the expected-
!                 # output file prints the msg at most once.
!                 BadDictKey.already_printed_raising_error = 1
!                 print "raising error"
              raise RuntimeError, "gotcha"
          return other
***************
*** 27,28 ****
--- 36,52 ----
  d[x2] = 2
  print "No exception passed through."
+ 
+ # Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
+ # This version got an assert failure in debug build, infinite loop in
+ # release build.  Unfortunately, provoking this kind of stuff requires
+ # a mix of inserts and deletes hitting exactly the right hash codes in
+ # exactly the right order, and I can't think of a randomized approach
+ # that would be *likely* to hit a failing case in reasonable time.
+ 
+ d = {}
+ for i in range(5):
+     d[i] = i
+ for i in range(5):
+     del d[i]
+ for i in range(5, 9):  # i==8 was the problem
+     d[i] = i

Index: test_parser.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_parser.py,v
retrieving revision 1.6
retrieving revision 1.6.6.1
diff -C2 -r1.6 -r1.6.6.1
*** test_parser.py	2001/01/17 21:51:36	1.6
--- test_parser.py	2001/07/07 22:55:29	1.6.6.1
***************
*** 1,9 ****
- import os.path
  import parser
! import pprint
! import sys
  
- from test_support import TestFailed
- 
  #
  #  First, we test that we can generate trees from valid source fragments,
--- 1,6 ----
  import parser
! import test_support
! import unittest
  
  #
  #  First, we test that we can generate trees from valid source fragments,
***************
*** 12,124 ****
  #
  
! def roundtrip(f, s):
!     st1 = f(s)
!     t = st1.totuple()
!     try:
!         st2 = parser.sequence2ast(t)
!     except parser.ParserError:
!         raise TestFailed, s
! 
! def roundtrip_fromfile(filename):
!     roundtrip(parser.suite, open(filename).read())
! 
! def test_expr(s):
!     print "expr:", s
!     roundtrip(parser.expr, s)
! 
! def test_suite(s):
!     print "suite:", s
!     roundtrip(parser.suite, s)
! 
! 
! print "Expressions:"
! 
! test_expr("foo(1)")
! test_expr("[1, 2, 3]")
! test_expr("[x**3 for x in range(20)]")
! test_expr("[x**3 for x in range(20) if x % 3]")
! test_expr("foo(*args)")
! test_expr("foo(*args, **kw)")
! test_expr("foo(**kw)")
! test_expr("foo(key=value)")
! test_expr("foo(key=value, *args)")
! test_expr("foo(key=value, *args, **kw)")
! test_expr("foo(key=value, **kw)")
! test_expr("foo(a, b, c, *args)")
! test_expr("foo(a, b, c, *args, **kw)")
! test_expr("foo(a, b, c, **kw)")
! test_expr("foo + bar")
! test_expr("lambda: 0")
! test_expr("lambda x: 0")
! test_expr("lambda *y: 0")
! test_expr("lambda *y, **z: 0")
! test_expr("lambda **z: 0")
! test_expr("lambda x, y: 0")
! test_expr("lambda foo=bar: 0")
! test_expr("lambda foo=bar, spaz=nifty+spit: 0")
! test_expr("lambda foo=bar, **z: 0")
! test_expr("lambda foo=bar, blaz=blat+2, **z: 0")
! test_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
! test_expr("lambda x, *y, **z: 0")
! 
! print
! print "Statements:"
! test_suite("print")
! test_suite("print 1")
! test_suite("print 1,")
! test_suite("print >>fp")
! test_suite("print >>fp, 1")
! test_suite("print >>fp, 1,")
! 
! # expr_stmt
! test_suite("a")
! test_suite("a = b")
! test_suite("a = b = c = d = e")
! test_suite("a += b")
! test_suite("a -= b")
! test_suite("a *= b")
! test_suite("a /= b")
! test_suite("a %= b")
! test_suite("a &= b")
! test_suite("a |= b")
! test_suite("a ^= b")
! test_suite("a <<= b")
! test_suite("a >>= b")
! test_suite("a **= b")
! 
! test_suite("def f(): pass")
! test_suite("def f(*args): pass")
! test_suite("def f(*args, **kw): pass")
! test_suite("def f(**kw): pass")
! test_suite("def f(foo=bar): pass")
! test_suite("def f(foo=bar, *args): pass")
! test_suite("def f(foo=bar, *args, **kw): pass")
! test_suite("def f(foo=bar, **kw): pass")
! 
! test_suite("def f(a, b): pass")
! test_suite("def f(a, b, *args): pass")
! test_suite("def f(a, b, *args, **kw): pass")
! test_suite("def f(a, b, **kw): pass")
! test_suite("def f(a, b, foo=bar): pass")
! test_suite("def f(a, b, foo=bar, *args): pass")
! test_suite("def f(a, b, foo=bar, *args, **kw): pass")
! test_suite("def f(a, b, foo=bar, **kw): pass")
! 
! test_suite("from sys.path import *")
! test_suite("from sys.path import dirname")
! test_suite("from sys.path import dirname as my_dirname")
! test_suite("from sys.path import dirname, basename")
! test_suite("from sys.path import dirname as my_dirname, basename")
! test_suite("from sys.path import dirname, basename as my_basename")
! 
! test_suite("import sys")
! test_suite("import sys as system")
! test_suite("import sys, math")
! test_suite("import sys as system, math")
! test_suite("import sys, math as my_math")
! 
! #d = os.path.dirname(os.__file__)
! #roundtrip_fromfile(os.path.join(d, "os.py"))
! #roundtrip_fromfile(os.path.join(d, "test", "test_parser.py"))
  
  #
--- 9,123 ----
  #
  
! class RoundtripLegalSyntaxTestCase(unittest.TestCase):
!     def roundtrip(self, f, s):
!         st1 = f(s)
!         t = st1.totuple()
!         try:
!             st2 = parser.sequence2ast(t)
!         except parser.ParserError:
!             self.fail("could not roundtrip %r" % s)
! 
!         self.assertEquals(t, st2.totuple(),
!                           "could not re-generate syntax tree")
! 
!     def check_expr(self, s):
!         self.roundtrip(parser.expr, s)
! 
!     def check_suite(self, s):
!         self.roundtrip(parser.suite, s)
! 
!     def test_expressions(self):
!         self.check_expr("foo(1)")
!         self.check_expr("[1, 2, 3]")
!         self.check_expr("[x**3 for x in range(20)]")
!         self.check_expr("[x**3 for x in range(20) if x % 3]")
!         self.check_expr("foo(*args)")
!         self.check_expr("foo(*args, **kw)")
!         self.check_expr("foo(**kw)")
!         self.check_expr("foo(key=value)")
!         self.check_expr("foo(key=value, *args)")
!         self.check_expr("foo(key=value, *args, **kw)")
!         self.check_expr("foo(key=value, **kw)")
!         self.check_expr("foo(a, b, c, *args)")
!         self.check_expr("foo(a, b, c, *args, **kw)")
!         self.check_expr("foo(a, b, c, **kw)")
!         self.check_expr("foo + bar")
!         self.check_expr("lambda: 0")
!         self.check_expr("lambda x: 0")
!         self.check_expr("lambda *y: 0")
!         self.check_expr("lambda *y, **z: 0")
!         self.check_expr("lambda **z: 0")
!         self.check_expr("lambda x, y: 0")
!         self.check_expr("lambda foo=bar: 0")
!         self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
!         self.check_expr("lambda foo=bar, **z: 0")
!         self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
!         self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
!         self.check_expr("lambda x, *y, **z: 0")
! 
!     def test_print(self):
!         self.check_suite("print")
!         self.check_suite("print 1")
!         self.check_suite("print 1,")
!         self.check_suite("print >>fp")
!         self.check_suite("print >>fp, 1")
!         self.check_suite("print >>fp, 1,")
! 
!     def test_simple_expression(self):
!         # expr_stmt
!         self.check_suite("a")
! 
!     def test_simple_assignments(self):
!         self.check_suite("a = b")
!         self.check_suite("a = b = c = d = e")
! 
!     def test_simple_augmented_assignments(self):
!         self.check_suite("a += b")
!         self.check_suite("a -= b")
!         self.check_suite("a *= b")
!         self.check_suite("a /= b")
!         self.check_suite("a %= b")
!         self.check_suite("a &= b")
!         self.check_suite("a |= b")
!         self.check_suite("a ^= b")
!         self.check_suite("a <<= b")
!         self.check_suite("a >>= b")
!         self.check_suite("a **= b")
! 
!     def test_function_defs(self):
!         self.check_suite("def f(): pass")
!         self.check_suite("def f(*args): pass")
!         self.check_suite("def f(*args, **kw): pass")
!         self.check_suite("def f(**kw): pass")
!         self.check_suite("def f(foo=bar): pass")
!         self.check_suite("def f(foo=bar, *args): pass")
!         self.check_suite("def f(foo=bar, *args, **kw): pass")
!         self.check_suite("def f(foo=bar, **kw): pass")
! 
!         self.check_suite("def f(a, b): pass")
!         self.check_suite("def f(a, b, *args): pass")
!         self.check_suite("def f(a, b, *args, **kw): pass")
!         self.check_suite("def f(a, b, **kw): pass")
!         self.check_suite("def f(a, b, foo=bar): pass")
!         self.check_suite("def f(a, b, foo=bar, *args): pass")
!         self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
!         self.check_suite("def f(a, b, foo=bar, **kw): pass")
! 
!     def test_import_from_statement(self):
!         self.check_suite("from sys.path import *")
!         self.check_suite("from sys.path import dirname")
!         self.check_suite("from sys.path import dirname as my_dirname")
!         self.check_suite("from sys.path import dirname, basename")
!         self.check_suite(
!             "from sys.path import dirname as my_dirname, basename")
!         self.check_suite(
!             "from sys.path import dirname, basename as my_basename")
! 
!     def test_basic_import_statement(self):
!         self.check_suite("import sys")
!         self.check_suite("import sys as system")
!         self.check_suite("import sys, math")
!         self.check_suite("import sys as system, math")
!         self.check_suite("import sys, math as my_math")
  
  #
***************
*** 127,222 ****
  #
  
! print
! print "Invalid parse trees:"
  
- def check_bad_tree(tree, label):
-     print
-     print label
-     try:
-         parser.sequence2ast(tree)
-     except parser.ParserError:
-         print "caught expected exception for invalid tree"
-     else:
-         print "test failed: did not properly detect invalid tree:"
-         pprint.pprint(tree)
- 
- 
- # not even remotely valid:
- check_bad_tree((1, 2, 3), "<junk>")
- 
- # print >>fp,
- tree = \
- (257,
-  (264,
-   (265,
-    (266,
-     (268,
-      (1, 'print'),
-      (35, '>>'),
-      (290,
-       (291,
-        (292,
-         (293,
-          (295,
-           (296,
-            (297,
-             (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
-      (12, ','))),
-    (4, ''))),
-  (0, ''))
- 
- check_bad_tree(tree, "print >>fp,")
- 
- # a,,c
- tree = \
- (258,
-  (311,
-   (290,
-    (291,
-     (292,
-      (293,
-       (295,
-        (296, (297, (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
-   (12, ','),
-   (12, ','),
-   (290,
-    (291,
-     (292,
-      (293,
-       (295,
-        (296, (297, (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
-  (4, ''),
-  (0, ''))
- 
- check_bad_tree(tree, "a,,c")
- 
- # a $= b
- tree = \
- (257,
-  (264,
-   (265,
-    (266,
-     (267,
-      (312,
-       (291,
-        (292,
-         (293,
-          (294,
-           (296,
-            (297,
-             (298,
-              (299, (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
-      (268, (37, '$=')),
-      (312,
-       (291,
-        (292,
-         (293,
-          (294,
-           (296,
-            (297,
-             (298,
-              (299, (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
-    (4, ''))),
-  (0, ''))
  
! check_bad_tree(tree, "a $= b")
--- 126,226 ----
  #
  
! class IllegalSyntaxTestCase(unittest.TestCase):
!     def check_bad_tree(self, tree, label):
!         try:
!             parser.sequence2ast(tree)
!         except parser.ParserError:
!             pass
!         else:
!             self.fail("did not detect invalid tree for %r" % label)
! 
!     def test_junk(self):
!         # not even remotely valid:
!         self.check_bad_tree((1, 2, 3), "<junk>")
! 
!     def test_print_chevron_comma(self):
!         "Illegal input: print >>fp,"""
!         tree = \
!         (257,
!          (264,
!           (265,
!            (266,
!             (268,
!              (1, 'print'),
!              (35, '>>'),
!              (290,
!               (291,
!                (292,
!                 (293,
!                  (295,
!                   (296,
!                    (297,
!                     (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
!              (12, ','))),
!            (4, ''))),
!          (0, ''))
!         self.check_bad_tree(tree, "print >>fp,")
! 
!     def test_a_comma_comma_c(self):
!         """Illegal input: a,,c"""
!         tree = \
!         (258,
!          (311,
!           (290,
!            (291,
!             (292,
!              (293,
!               (295,
!                (296,
!                 (297,
!                  (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
!           (12, ','),
!           (12, ','),
!           (290,
!            (291,
!             (292,
!              (293,
!               (295,
!                (296,
!                 (297,
!                  (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
!          (4, ''),
!          (0, ''))
!         self.check_bad_tree(tree, "a,,c")
! 
!     def test_illegal_operator(self):
!         """Illegal input: a $= b"""
!         tree = \
!         (257,
!          (264,
!           (265,
!            (266,
!             (267,
!              (312,
!               (291,
!                (292,
!                 (293,
!                  (294,
!                   (296,
!                    (297,
!                     (298,
!                      (299,
!                       (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
!              (268, (37, '$=')),
!              (312,
!               (291,
!                (292,
!                 (293,
!                  (294,
!                   (296,
!                    (297,
!                     (298,
!                      (299,
!                       (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
!            (4, ''))),
!          (0, ''))
!         self.check_bad_tree(tree, "a $= b")
  
  
! test_support.run_unittest(RoundtripLegalSyntaxTestCase)
! test_support.run_unittest(IllegalSyntaxTestCase)

Index: test_pyexpat.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pyexpat.py,v
retrieving revision 1.7
retrieving revision 1.7.6.1
diff -C2 -r1.7 -r1.7.6.1
*** test_pyexpat.py	2000/12/23 22:12:07	1.7
--- test_pyexpat.py	2001/07/07 22:55:29	1.7.6.1
***************
*** 6,12 ****
  from xml.parsers import expat
  
  class Outputter:
      def StartElementHandler(self, name, attrs):
!         print 'Start element:\n\t', repr(name), attrs
  
      def EndElementHandler(self, name):
--- 6,14 ----
  from xml.parsers import expat
  
+ from test_support import sortdict
+ 
  class Outputter:
      def StartElementHandler(self, name, attrs):
!         print 'Start element:\n\t', repr(name), sortdict(attrs)
  
      def EndElementHandler(self, name):
***************
*** 76,79 ****
--- 78,93 ----
  parser.returns_unicode = 0; confirm(parser.returns_unicode == 0)
  
+ # Test getting/setting ordered_attributes
+ parser.ordered_attributes = 0; confirm(parser.ordered_attributes == 0)
+ parser.ordered_attributes = 1; confirm(parser.ordered_attributes == 1)
+ parser.ordered_attributes = 2; confirm(parser.ordered_attributes == 1)
+ parser.ordered_attributes = 0; confirm(parser.ordered_attributes == 0)
+ 
+ # Test getting/setting specified_attributes
+ parser.specified_attributes = 0; confirm(parser.specified_attributes == 0)
+ parser.specified_attributes = 1; confirm(parser.specified_attributes == 1)
+ parser.specified_attributes = 2; confirm(parser.specified_attributes == 1)
+ parser.specified_attributes = 0; confirm(parser.specified_attributes == 0)
+ 
  HANDLER_NAMES = [
      'StartElementHandler', 'EndElementHandler',
***************
*** 168,171 ****
--- 182,186 ----
  else:
      print "Failed to catch expected TypeError."
+ 
  try:
      expat.ParserCreate(namespace_separator='too long')
***************
*** 174,183 ****
      print e
  else:
-     print "Failed to catch expected ValueError."
- try:
-     expat.ParserCreate(namespace_separator='') # too short
- except ValueError, e:
-     print "Caught expected ValueError:"
-     print e
- else:
      print "Failed to catch expected ValueError."
--- 189,201 ----
      print e
  else:
      print "Failed to catch expected ValueError."
+ 
+ # ParserCreate() needs to accept a namespace_separator of zero length
+ # to satisfy the requirements of RDF applications that are required
+ # to simply glue together the namespace URI and the localname.  Though
+ # considered a wart of the RDF specifications, it needs to be supported.
+ #
+ # See XML-SIG mailing list thread starting with
+ # http://mail.python.org/pipermail/xml-sig/2001-April/005202.html
+ #
+ expat.ParserCreate(namespace_separator='') # too short

Index: test_regex.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_regex.py,v
retrieving revision 1.9
retrieving revision 1.9.6.1
diff -C2 -r1.9 -r1.9.6.1
*** test_regex.py	2001/01/17 21:51:36	1.9
--- test_regex.py	2001/07/07 22:55:29	1.9.6.1
***************
*** 1,3 ****
! from test_support import verbose
  import warnings
  warnings.filterwarnings("ignore", "the regex module is deprecated",
--- 1,3 ----
! from test_support import verbose, sortdict
  import warnings
  warnings.filterwarnings("ignore", "the regex module is deprecated",
***************
*** 41,45 ****
  print cre.group('one', 'two')
  print 'realpat:', cre.realpat
! print 'groupindex:', cre.groupindex
  
  re = 'world'
--- 41,45 ----
  print cre.group('one', 'two')
  print 'realpat:', cre.realpat
! print 'groupindex:', sortdict(cre.groupindex)
  
  re = 'world'

Index: test_rfc822.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_rfc822.py,v
retrieving revision 1.9
retrieving revision 1.9.6.1
diff -C2 -r1.9 -r1.9.6.1
*** test_rfc822.py	2001/01/17 21:51:36	1.9
--- test_rfc822.py	2001/07/07 22:55:29	1.9.6.1
***************
*** 1,4 ****
! from test_support import verbose
! import rfc822, sys
  try:
      from cStringIO import StringIO
--- 1,7 ----
! import rfc822
! import sys
! import test_support
! import unittest
! 
  try:
      from cStringIO import StringIO
***************
*** 6,126 ****
      from StringIO import StringIO
  
- def test(msg, results):
-     fp = StringIO()
-     fp.write(msg)
-     fp.seek(0)
-     m = rfc822.Message(fp)
-     i = 0
- 
-     for n, a in m.getaddrlist('to') + m.getaddrlist('cc'):
-         if verbose:
-             print 'name:', repr(n), 'addr:', repr(a)
-         try:
-             mn, ma = results[i][0], results[i][1]
-         except IndexError:
-             print 'extra parsed address:', repr(n), repr(a)
-             continue
-         i = i + 1
-         if mn == n and ma == a:
-             if verbose:
-                 print '    [matched]'
-         else:
-             if verbose:
-                 print '    [no match]'
-             print 'not found:', repr(n), repr(a)
- 
-     out = m.getdate('date')
-     if out:
-         if verbose:
-             print 'Date:', m.getheader('date')
-         if out == (1999, 1, 13, 23, 57, 35, 0, 0, 0):
-             if verbose:
-                 print '    [matched]'
-         else:
-             if verbose:
-                 print '    [no match]'
-             print 'Date conversion failed:', out
- 
- # Note: all test cases must have the same date (in various formats),
- # or no date!
- 
- test('''Date:    Wed, 13 Jan 1999 23:57:35 -0500
- From:    Guido van Rossum <guido@CNRI.Reston.VA.US>
- To:      "Guido van
- \t : Rossum" <guido@python.org>
- Subject: test2
- 
- test2
- ''', [('Guido van\n\t : Rossum', 'guido@python.org')])
- 
- test('''From: Barry <bwarsaw@python.org
- To: guido@python.org (Guido: the Barbarian)
- Subject: nonsense
- Date: Wednesday, January 13 1999 23:57:35 -0500
- 
- test''', [('Guido: the Barbarian', 'guido@python.org'),
-           ])
- 
- test('''From: Barry <bwarsaw@python.org
- To: guido@python.org (Guido: the Barbarian)
- Cc: "Guido: the Madman" <guido@python.org>
- Date:  13-Jan-1999 23:57:35 EST
- 
- test''', [('Guido: the Barbarian', 'guido@python.org'),
-           ('Guido: the Madman', 'guido@python.org')
-           ])
- 
- test('''To: "The monster with
-      the very long name: Guido" <guido@python.org>
- Date:    Wed, 13 Jan 1999 23:57:35 -0500
- 
- test''', [('The monster with\n     the very long name: Guido',
-            'guido@python.org')])
- 
- test('''To: "Amit J. Patel" <amitp@Theory.Stanford.EDU>
- CC: Mike Fletcher <mfletch@vrtelecom.com>,
-         "'string-sig@python.org'" <string-sig@python.org>
- Cc: fooz@bat.com, bart@toof.com
- Cc: goit@lip.com
- Date:    Wed, 13 Jan 1999 23:57:35 -0500
- 
- test''', [('Amit J. Patel', 'amitp@Theory.Stanford.EDU'),
-           ('Mike Fletcher', 'mfletch@vrtelecom.com'),
-           ("'string-sig@python.org'", 'string-sig@python.org'),
-           ('', 'fooz@bat.com'),
-           ('', 'bart@toof.com'),
-           ('', 'goit@lip.com'),
-           ])
- 
- # This one is just twisted.  I don't know what the proper result should be,
- # but it shouldn't be to infloop, which is what used to happen!
- test('''To: <[smtp:dd47@mail.xxx.edu]_at_hmhq@hdq-mdm1-imgout.companay.com>
- Date:    Wed, 13 Jan 1999 23:57:35 -0500
- 
- test''', [('', ''),
-           ('', 'dd47@mail.xxx.edu'),
-           ('', '_at_hmhq@hdq-mdm1-imgout.companay.com')
-           ])
- 
- # This exercises the old commas-in-a-full-name bug, which should be doing the
- # right thing in recent versions of the module.
- test('''To: "last, first" <userid@foo.net>
- 
- test''', [('last, first', 'userid@foo.net'),
-           ])
- 
- test('''To: (Comment stuff) "Quoted name"@somewhere.com
- 
- test''', [('Comment stuff', '"Quoted name"@somewhere.com'),
-           ])
- 
- test('''To: :
- Cc: goit@lip.com
- Date:    Wed, 13 Jan 1999 23:57:35 -0500
- 
- test''', [('', 'goit@lip.com')])
  
  
- test('''To: guido@[132.151.1.21]
  
! foo''', [('', 'guido@[132.151.1.21]')])
--- 9,168 ----
      from StringIO import StringIO
  
  
+ class MessageTestCase(unittest.TestCase):
+     def create_message(self, msg):
+         return rfc822.Message(StringIO(msg))
+ 
+     def test_get(self):
+         msg = self.create_message(
+             'To: "last, first" <userid@foo.net>\n\ntest\n')
+         self.assert_(msg.get("to") == '"last, first" <userid@foo.net>')
+         self.assert_(msg.get("TO") == '"last, first" <userid@foo.net>')
+         self.assert_(msg.get("No-Such-Header") == "")
+         self.assert_(msg.get("No-Such-Header", "No-Such-Value")
+                      == "No-Such-Value")
+ 
+     def test_setdefault(self):
+         msg = self.create_message(
+             'To: "last, first" <userid@foo.net>\n\ntest\n')
+         self.assert_(not msg.has_key("New-Header"))
+         self.assert_(msg.setdefault("New-Header", "New-Value") == "New-Value")
+         self.assert_(msg.setdefault("New-Header", "Different-Value")
+                      == "New-Value")
+         self.assert_(msg["new-header"] == "New-Value")
+ 
+         self.assert_(msg.setdefault("Another-Header") == "")
+         self.assert_(msg["another-header"] == "")
+ 
+     def check(self, msg, results):
+         """Check addresses and the date."""
+         m = self.create_message(msg)
+         i = 0
+         for n, a in m.getaddrlist('to') + m.getaddrlist('cc'):
+             try:
+                 mn, ma = results[i][0], results[i][1]
+             except IndexError:
+                 print 'extra parsed address:', repr(n), repr(a)
+                 continue
+             i = i + 1
+             if mn == n and ma == a:
+                 pass
+             else:
+                 print 'not found:', repr(n), repr(a)
+ 
+         out = m.getdate('date')
+         if out:
+             self.assertEqual(out,
+                              (1999, 1, 13, 23, 57, 35, 0, 0, 0),
+                              "date conversion failed")
+ 
+ 
+     # Note: all test cases must have the same date (in various formats),
+     # or no date!
+ 
+     def test_basic(self):
+         self.check(
+             'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
+             'From:    Guido van Rossum <guido@CNRI.Reston.VA.US>\n'
+             'To:      "Guido van\n'
+             '\t : Rossum" <guido@python.org>\n'
+             'Subject: test2\n'
+             '\n'
+             'test2\n',
+             [('Guido van\n\t : Rossum', 'guido@python.org')])
+ 
+         self.check(
+             'From: Barry <bwarsaw@python.org\n'
+             'To: guido@python.org (Guido: the Barbarian)\n'
+             'Subject: nonsense\n'
+             'Date: Wednesday, January 13 1999 23:57:35 -0500\n'
+             '\n'
+             'test',
+             [('Guido: the Barbarian', 'guido@python.org')])
+ 
+         self.check(
+             'From: Barry <bwarsaw@python.org\n'
+             'To: guido@python.org (Guido: the Barbarian)\n'
+             'Cc: "Guido: the Madman" <guido@python.org>\n'
+             'Date:  13-Jan-1999 23:57:35 EST\n'
+             '\n'
+             'test',
+             [('Guido: the Barbarian', 'guido@python.org'),
+              ('Guido: the Madman', 'guido@python.org')
+              ])
+ 
+         self.check(
+             'To: "The monster with\n'
+             '     the very long name: Guido" <guido@python.org>\n'
+             'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
+             '\n'
+             'test',
+             [('The monster with\n     the very long name: Guido',
+               'guido@python.org')])
+ 
+         self.check(
+             'To: "Amit J. Patel" <amitp@Theory.Stanford.EDU>\n'
+             'CC: Mike Fletcher <mfletch@vrtelecom.com>,\n'
+             '        "\'string-sig@python.org\'" <string-sig@python.org>\n'
+             'Cc: fooz@bat.com, bart@toof.com\n'
+             'Cc: goit@lip.com\n'
+             'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
+             '\n'
+             'test',
+             [('Amit J. Patel', 'amitp@Theory.Stanford.EDU'),
+              ('Mike Fletcher', 'mfletch@vrtelecom.com'),
+              ("'string-sig@python.org'", 'string-sig@python.org'),
+              ('', 'fooz@bat.com'),
+              ('', 'bart@toof.com'),
+              ('', 'goit@lip.com'),
+              ])
+ 
+     def test_twisted(self):
+         # This one is just twisted.  I don't know what the proper
+         # result should be, but it shouldn't be to infloop, which is
+         # what used to happen!
+         self.check(
+             'To: <[smtp:dd47@mail.xxx.edu]_at_hmhq@hdq-mdm1-imgout.companay.com>\n'
+             'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
+             '\n'
+             'test',
+             [('', ''),
+              ('', 'dd47@mail.xxx.edu'),
+              ('', '_at_hmhq@hdq-mdm1-imgout.companay.com'),
+              ])
+ 
+     def test_commas_in_full_name(self):
+         # This exercises the old commas-in-a-full-name bug, which
+         # should be doing the right thing in recent versions of the
+         # module.
+         self.check(
+             'To: "last, first" <userid@foo.net>\n'
+             '\n'
+             'test',
+             [('last, first', 'userid@foo.net')])
+ 
+     def test_quoted_name(self):
+         self.check(
+             'To: (Comment stuff) "Quoted name"@somewhere.com\n'
+             '\n'
+             'test',
+             [('Comment stuff', '"Quoted name"@somewhere.com')])
+ 
+     def test_bogus_to_header(self):
+         self.check(
+             'To: :\n'
+             'Cc: goit@lip.com\n'
+             'Date:    Wed, 13 Jan 1999 23:57:35 -0500\n'
+             '\n'
+             'test',
+             [('', 'goit@lip.com')])
+ 
+     def test_addr_ipquad(self):
+         self.check(
+             'To: guido@[132.151.1.21]\n'
+             '\n'
+             'foo',
+             [('', 'guido@[132.151.1.21]')])
  
  
! test_support.run_unittest(MessageTestCase)

Index: test_richcmp.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_richcmp.py,v
retrieving revision 1.5
retrieving revision 1.5.6.1
diff -C2 -r1.5 -r1.5.6.1
*** test_richcmp.py	2001/01/19 06:12:17	1.5
--- test_richcmp.py	2001/07/07 22:55:29	1.5.6.1
***************
*** 222,225 ****
--- 222,252 ----
      if verbose: print "recursion tests ok"
  
+ def dicts():
+     # Verify that __eq__ and __ne__ work for dicts even if the keys and
+     # values don't support anything other than __eq__ and __ne__.  Complex
+     # numbers are a fine example of that.
+     import random
+     imag1a = {}
+     for i in range(50):
+         imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
+     items = imag1a.items()
+     random.shuffle(items)
+     imag1b = {}
+     for k, v in items:
+         imag1b[k] = v
+     imag2 = imag1b.copy()
+     imag2[k] = v + 1.0
+     verify(imag1a == imag1a, "imag1a == imag1a should have worked")
+     verify(imag1a == imag1b, "imag1a == imag1b should have worked")
+     verify(imag2 == imag2, "imag2 == imag2 should have worked")
+     verify(imag1a != imag2, "imag1a != imag2 should have worked")
+     for op in "<", "<=", ">", ">=":
+         try:
+             eval("imag1a %s imag2" % op)
+         except TypeError:
+             pass
+         else:
+             raise TestFailed("expected TypeError from imag1a %s imag2" % op)
+ 
  def main():
      basic()
***************
*** 230,233 ****
--- 257,261 ----
      misbehavin()
      recursion()
+     dicts()
  
  main()

Index: test_scope.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_scope.py,v
retrieving revision 1.14
retrieving revision 1.14.4.1
diff -C2 -r1.14 -r1.14.4.1
*** test_scope.py	2001/04/13 16:51:46	1.14
--- test_scope.py	2001/07/07 22:55:29	1.14.4.1
***************
*** 437,438 ****
--- 437,469 ----
  verify(d == {'x': 2, 'y': 7, 'w': 6})
  
+ print "19. var is bound and free in class"
+ 
+ def f(x):
+     class C:
+         def m(self):
+             return x
+         a = x
+     return C
+ 
+ inst = f(3)()
+ verify(inst.a == inst.m())
+ 
+ print "20. interaction with trace function"
+ 
+ import sys
+ def tracer(a,b,c):
+     return tracer
+ 
+ def adaptgetter(name, klass, getter):
+     kind, des = getter
+     if kind == 1:       # AV happens when stepping from this line to next
+         if des == "":
+             des = "_%s__%s" % (klass.__name__, name)
+         return lambda obj: getattr(obj, des)
+ 
+ class TestClass:
+     pass
+ 
+ sys.settrace(tracer)
+ adaptgetter("foo", TestClass, (1, ""))
+ sys.settrace(None)

Index: test_sha.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sha.py,v
retrieving revision 1.1
retrieving revision 1.1.12.1
diff -C2 -r1.1 -r1.1.12.1
*** test_sha.py	1999/03/24 19:04:29	1.1
--- test_sha.py	2001/07/07 22:55:29	1.1.12.1
***************
*** 1,28 ****
  # Testing sha module (NIST's Secure Hash Algorithm)
  
- import sha
- 
  # use the three examples from Federal Information Processing Standards
  # Publication 180-1, Secure Hash Standard,  1995 April 17
  # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
  
! s = [''] * 3
! d = [''] * 3
  
! s[0] = 'abc'
! d[0] = 'a9993e364706816aba3e25717850c26c9cd0d89d'
  
- s[1] = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'
- d[1] = '84983e441c3bd26ebaae4aa1f95129e5e54670f1'
  
! s[2] = 'a' * 1000000
! d[2] = '34aa973cd4c4daa4f61eeb2bdbad27316534016f'
! 
! for i in range(3):
!     test = sha.new(s[i]).hexdigest()
!     if test == d[i]:
!         print "test %d ok" % i
!     else:
!         print "test %d failed" % i
!         print "expected", d[i]
!         print "computed", test
--- 1,30 ----
  # Testing sha module (NIST's Secure Hash Algorithm)
  
  # use the three examples from Federal Information Processing Standards
  # Publication 180-1, Secure Hash Standard,  1995 April 17
  # http://www.itl.nist.gov/div897/pubs/fip180-1.htm
+ 
+ import sha
+ import test_support
+ import unittest
+ 
+ 
+ class SHATestCase(unittest.TestCase):
+     def check(self, data, digest):
+         computed = sha.new(data).hexdigest()
+         self.assert_(computed == digest)
+ 
+     def test_case_1(self):
+         self.check("abc",
+                    "a9993e364706816aba3e25717850c26c9cd0d89d")
  
!     def test_case_2(self):
!         self.check("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
!                    "84983e441c3bd26ebaae4aa1f95129e5e54670f1")
  
!     def test_case_3(self):
!         self.check("a" * 1000000,
!                    "34aa973cd4c4daa4f61eeb2bdbad27316534016f")
  
  
! test_support.run_unittest(SHATestCase)

Index: test_sre.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sre.py,v
retrieving revision 1.24
retrieving revision 1.24.4.1
diff -C2 -r1.24 -r1.24.4.1
*** test_sre.py	2001/03/22 23:48:28	1.24
--- test_sre.py	2001/07/07 22:55:29	1.24.4.1
***************
*** 246,250 ****
  test("sre.match('(x)*', 50000*'x').span()", (0, 50000), RuntimeError)
  test("sre.match(r'(x)*y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
! test("sre.match(r'(x)*?y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
  
  from re_tests import *
--- 246,250 ----
  test("sre.match('(x)*', 50000*'x').span()", (0, 50000), RuntimeError)
  test("sre.match(r'(x)*y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
! test("sre.match(r'(x)*?y', 50000*'x'+'y').span()", (0, 50001))
  
  from re_tests import *

Index: test_strop.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_strop.py,v
retrieving revision 1.10
retrieving revision 1.10.6.1
diff -C2 -r1.10 -r1.10.6.1
*** test_strop.py	2001/01/17 21:51:36	1.10
--- test_strop.py	2001/07/07 22:55:29	1.10.6.1
***************
*** 1,87 ****
! from test_support import verbose
! import strop, sys
  
- def test(name, input, output, *args):
-     if verbose:
-         print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
-     f = getattr(strop, name)
-     try:
-         value = apply(f, (input,) + args)
-     except:
-         value = sys.exc_type
-     if value != output:
-         if verbose:
-             print 'no'
-         print f, `input`, `output`, `value`
-     else:
-         if verbose:
-             print 'yes'
- 
- test('atoi', " 1 ", 1)
- test('atoi', " 1x", ValueError)
- test('atoi', " x1 ", ValueError)
- test('atol', "  1  ", 1L)
- test('atol', "  1x ", ValueError)
- test('atol', "  x1 ", ValueError)
- test('atof', "  1  ", 1.0)
- test('atof', "  1x ", ValueError)
- test('atof', "  x1 ", ValueError)
- 
- test('capitalize', ' hello ', ' hello ')
- test('capitalize', 'hello ', 'Hello ')
- test('find', 'abcdefghiabc', 0, 'abc')
- test('find', 'abcdefghiabc', 9, 'abc', 1)
- test('find', 'abcdefghiabc', -1, 'def', 4)
- test('rfind', 'abcdefghiabc', 9, 'abc')
- test('lower', 'HeLLo', 'hello')
- test('upper', 'HeLLo', 'HELLO')
  
  transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
  
- test('maketrans', 'abc', transtable, 'xyz')
- test('maketrans', 'abc', ValueError, 'xyzq')
  
! test('split', 'this is the split function',
!      ['this', 'is', 'the', 'split', 'function'])
! test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|')
! test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2)
! test('split', 'a b c d', ['a', 'b c d'], None, 1)
! test('split', 'a b c d', ['a', 'b', 'c d'], None, 2)
! test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3)
! test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4)
! test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 0)
! test('split', 'a  b  c  d', ['a', 'b', 'c  d'], None, 2)
! 
! # join now works with any sequence type
  class Sequence:
      def __init__(self): self.seq = 'wxyz'
      def __len__(self): return len(self.seq)
      def __getitem__(self, i): return self.seq[i]
  
! test('join', ['a', 'b', 'c', 'd'], 'a b c d')
! test('join', ('a', 'b', 'c', 'd'), 'abcd', '')
! test('join', Sequence(), 'w x y z')
! 
! # try a few long ones
! print strop.join(['x' * 100] * 100, ':')
! print strop.join(('x' * 100,) * 100, ':')
! 
! test('strip', '   hello   ', 'hello')
! test('lstrip', '   hello   ', 'hello   ')
! test('rstrip', '   hello   ', '   hello')
! 
! test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS')
! test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def')
! 
! test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1)
! test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2)
! test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3)
! test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4)
! test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
! test('replace', 'one!two!three!', 'one@two@three@', '!', '@')
! test('replace', 'one!two!three!', 'one!two!three!', 'x', '@')
! test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2)
! 
! strop.whitespace
! strop.lowercase
! strop.uppercase
--- 1,128 ----
! import warnings
! warnings.filterwarnings("ignore", "", DeprecationWarning, __name__)
! warnings.filterwarnings("ignore", "", DeprecationWarning, "unittest")
! import strop
! import test_support
! import unittest
! 
! 
! class StropFunctionTestCase(unittest.TestCase):
! 
!     def test_atoi(self):
!         self.assert_(strop.atoi(" 1 ") == 1)
!         self.assertRaises(ValueError, strop.atoi, " 1x")
!         self.assertRaises(ValueError, strop.atoi, " x1 ")
! 
!     def test_atol(self):
!         self.assert_(strop.atol(" 1 ") == 1L)
!         self.assertRaises(ValueError, strop.atol, " 1x")
!         self.assertRaises(ValueError, strop.atol, " x1 ")
! 
!     def test_atof(self):
!         self.assert_(strop.atof(" 1 ") == 1.0)
!         self.assertRaises(ValueError, strop.atof, " 1x")
!         self.assertRaises(ValueError, strop.atof, " x1 ")
! 
!     def test_capitalize(self):
!         self.assert_(strop.capitalize(" hello ") == " hello ")
!         self.assert_(strop.capitalize("hello ") == "Hello ")
! 
!     def test_find(self):
!         self.assert_(strop.find("abcdefghiabc", "abc") == 0)
!         self.assert_(strop.find("abcdefghiabc", "abc", 1) == 9)
!         self.assert_(strop.find("abcdefghiabc", "def", 4) == -1)
! 
!     def test_rfind(self):
!         self.assert_(strop.rfind("abcdefghiabc", "abc") == 9)
! 
!     def test_lower(self):
!         self.assert_(strop.lower("HeLLo") == "hello")
! 
!     def test_upper(self):
!         self.assert_(strop.upper("HeLLo") == "HELLO")
! 
!     def test_swapcase(self):
!         self.assert_(strop.swapcase("HeLLo cOmpUteRs") == "hEllO CoMPuTErS")
! 
!     def test_strip(self):
!         self.assert_(strop.strip(" \t\n hello \t\n ") == "hello")
! 
!     def test_lstrip(self):
!         self.assert_(strop.lstrip(" \t\n hello \t\n ") == "hello \t\n ")
! 
!     def test_rstrip(self):
!         self.assert_(strop.rstrip(" \t\n hello \t\n ") == " \t\n hello")
! 
!     def test_replace(self):
!         replace = strop.replace
!         self.assert_(replace("one!two!three!", '!', '@', 1)
!                      == "one@two!three!")
!         self.assert_(replace("one!two!three!", '!', '@', 2)
!                      == "one@two@three!")
!         self.assert_(replace("one!two!three!", '!', '@', 3)
!                      == "one@two@three@")
!         self.assert_(replace("one!two!three!", '!', '@', 4)
!                      == "one@two@three@")
! 
!         # CAUTION: a replace count of 0 means infinity only to strop,
!         # not to the string .replace() method or to the
!         # string.replace() function.
! 
!         self.assert_(replace("one!two!three!", '!', '@', 0)
!                      == "one@two@three@")
!         self.assert_(replace("one!two!three!", '!', '@')
!                      == "one@two@three@")
!         self.assert_(replace("one!two!three!", 'x', '@')
!                      == "one!two!three!")
!         self.assert_(replace("one!two!three!", 'x', '@', 2)
!                      == "one!two!three!")
! 
!     def test_split(self):
!         split = strop.split
!         self.assert_(split("this is the split function")
!                      == ['this', 'is', 'the', 'split', 'function'])
!         self.assert_(split("a|b|c|d", '|') == ['a', 'b', 'c', 'd'])
!         self.assert_(split("a|b|c|d", '|', 2) == ['a', 'b', 'c|d'])
!         self.assert_(split("a b c d", None, 1) == ['a', 'b c d'])
!         self.assert_(split("a b c d", None, 2) == ['a', 'b', 'c d'])
!         self.assert_(split("a b c d", None, 3) == ['a', 'b', 'c', 'd'])
!         self.assert_(split("a b c d", None, 4) == ['a', 'b', 'c', 'd'])
!         self.assert_(split("a b c d", None, 0) == ['a', 'b', 'c', 'd'])
!         self.assert_(split("a  b  c  d", None, 2) ==  ['a', 'b', 'c  d'])
! 
!     def test_join(self):
!         self.assert_(strop.join(['a', 'b', 'c', 'd']) == 'a b c d')
!         self.assert_(strop.join(('a', 'b', 'c', 'd'), '') == 'abcd')
!         self.assert_(strop.join(Sequence()) == 'w x y z')
! 
!         # try a few long ones
!         self.assert_(strop.join(['x' * 100] * 100, ':')
!                      == (('x' * 100) + ":") * 99 + "x" * 100)
!         self.assert_(strop.join(('x' * 100,) * 100, ':')
!                      == (('x' * 100) + ":") * 99 + "x" * 100)
! 
!     def test_maketrans(self):
!         self.assert_(strop.maketrans("abc", "xyz") == transtable)
!         self.assertRaises(ValueError, strop.maketrans, "abc", "xyzq")
! 
!     def test_translate(self):
!         self.assert_(strop.translate("xyzabcdef", transtable, "def")
!                      == "xyzxyz")
! 
!     def test_data_attributes(self):
!         strop.lowercase
!         strop.uppercase
!         strop.whitespace
  
  
  transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
  
  
! # join() now works with any sequence type.
  class Sequence:
      def __init__(self): self.seq = 'wxyz'
      def __len__(self): return len(self.seq)
      def __getitem__(self, i): return self.seq[i]
+ 
  
! test_support.run_unittest(StropFunctionTestCase)

Index: test_struct.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_struct.py,v
retrieving revision 1.7
retrieving revision 1.7.6.1
diff -C2 -r1.7 -r1.7.6.1
*** test_struct.py	2000/12/12 23:11:42	1.7
--- test_struct.py	2001/07/07 22:55:29	1.7.6.1
***************
*** 1,6 ****
! from test_support import TestFailed, verbose
  import struct
  ## import pdb
  
  def simple_err(func, *args):
      try:
--- 1,23 ----
! from test_support import TestFailed, verbose, verify
  import struct
  ## import pdb
  
+ import sys
+ ISBIGENDIAN = sys.byteorder == "big"
+ del sys
+ verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN,
+        "bigendian determination appears wrong")
+ 
+ def string_reverse(s):
+     chars = list(s)
+     chars.reverse()
+     return "".join(chars)
+ 
+ def bigendian_to_native(value):
+     if ISBIGENDIAN:
+         return value
+     else:
+         return string_reverse(value)
+ 
  def simple_err(func, *args):
      try:
***************
*** 12,18 ****
              func.__name__, args)
  ##      pdb.set_trace()
  
- simple_err(struct.calcsize, 'Q')
  
  sz = struct.calcsize('i')
  if sz * 3 != struct.calcsize('iii'):
--- 29,46 ----
              func.__name__, args)
  ##      pdb.set_trace()
+ 
+ def any_err(func, *args):
+     try:
+         apply(func, args)
+     except (struct.error, OverflowError, TypeError):
+         pass
+     else:
+         raise TestFailed, "%s%s did not raise error" % (
+             func.__name__, args)
+ ##      pdb.set_trace()
  
  
+ simple_err(struct.calcsize, 'Z')
+ 
  sz = struct.calcsize('i')
  if sz * 3 != struct.calcsize('iii'):
***************
*** 94,111 ****
  ]
  
- def badpack(fmt, arg, got, exp):
-     return
- 
- def badunpack(fmt, arg, got, exp):
-     return "unpack(%s, %s) -> (%s,) # expected (%s,)" % (
-         `fmt`, `arg`, `got`, `exp`)
- 
- isbigendian = struct.pack('=h', 1) == '\0\1'
- 
  for fmt, arg, big, lil, asy in tests:
      if verbose:
          print `fmt`, `arg`, `big`, `lil`
      for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
!                         ('='+fmt, isbigendian and big or lil)]:
          res = struct.pack(xfmt, arg)
          if res != exp:
--- 122,130 ----
  ]
  
  for fmt, arg, big, lil, asy in tests:
      if verbose:
          print `fmt`, `arg`, `big`, `lil`
      for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
!                         ('='+fmt, ISBIGENDIAN and big or lil)]:
          res = struct.pack(xfmt, arg)
          if res != exp:
***************
*** 120,121 ****
--- 139,370 ----
              raise TestFailed, "unpack(%s, %s) -> (%s,) # expected (%s,)" % (
                  `fmt`, `res`, `rev`, `arg`)
+ 
+ ###########################################################################
+ # Simple native q/Q tests.
+ 
+ has_native_qQ = 1
+ try:
+     struct.pack("q", 5)
+ except struct.error:
+     has_native_qQ = 0
+ 
+ if verbose:
+     print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
+ 
+ any_err(struct.pack, "Q", -1)   # can't pack -1 as unsigned regardless
+ simple_err(struct.pack, "q", "a")  # can't pack string as 'q' regardless
+ simple_err(struct.pack, "Q", "a")  # ditto, but 'Q'
+ 
+ def test_native_qQ():
+     bytes = struct.calcsize('q')
+     # The expected values here are in big-endian format, primarily because
+     # I'm on a little-endian machine and so this is the clearest way (for
+     # me) to force the code to get exercised.
+     for format, input, expected in (
+             ('q', -1, '\xff' * bytes),
+             ('q', 0, '\x00' * bytes),
+             ('Q', 0, '\x00' * bytes),
+             ('q', 1L, '\x00' * (bytes-1) + '\x01'),
+             ('Q', (1L << (8*bytes))-1, '\xff' * bytes),
+             ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
+         got = struct.pack(format, input)
+         native_expected = bigendian_to_native(expected)
+         verify(got == native_expected,
+                "%r-pack of %r gave %r, not %r" %
+                     (format, input, got, native_expected))
+         retrieved = struct.unpack(format, got)[0]
+         verify(retrieved == input,
+                "%r-unpack of %r gave %r, not %r" %
+                     (format, got, retrieved, input))
+ 
+ if has_native_qQ:
+     test_native_qQ()
+ 
+ ###########################################################################
+ # Standard integer tests (bBhHiIlLqQ).
+ 
+ import binascii
+ 
+ class IntTester:
+ 
+     # XXX Most std integer modes fail to test for out-of-range.
+     # The "i" and "l" codes appear to range-check OK on 32-bit boxes, but
+     # fail to check correctly on some 64-bit ones (Tru64 Unix + Compaq C
+     # reported by Mark Favas).
+     BUGGY_RANGE_CHECK = "bBhHiIlL"
+ 
+     def __init__(self, formatpair, bytesize):
+         assert len(formatpair) == 2
+         self.formatpair = formatpair
+         for direction in "<>!=":
+             for code in formatpair:
+                 format = direction + code
+                 verify(struct.calcsize(format) == bytesize)
+         self.bytesize = bytesize
+         self.bitsize = bytesize * 8
+         self.signed_code, self.unsigned_code = formatpair
+         self.unsigned_min = 0
+         self.unsigned_max = 2L**self.bitsize - 1
+         self.signed_min = -(2L**(self.bitsize-1))
+         self.signed_max = 2L**(self.bitsize-1) - 1
+ 
+     def test_one(self, x, pack=struct.pack,
+                           unpack=struct.unpack,
+                           unhexlify=binascii.unhexlify):
+         if verbose:
+             print "trying std", self.formatpair, "on", x, "==", hex(x)
+ 
+         # Try signed.
+         code = self.signed_code
+         if self.signed_min <= x <= self.signed_max:
+             # Try big-endian.
+             expected = long(x)
+             if x < 0:
+                 expected += 1L << self.bitsize
+                 assert expected > 0
+             expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
+             if len(expected) & 1:
+                 expected = "0" + expected
+             expected = unhexlify(expected)
+             expected = "\x00" * (self.bytesize - len(expected)) + expected
+ 
+             # Pack work?
+             format = ">" + code
+             got = pack(format, x)
+             verify(got == expected,
+                    "'%s'-pack of %r gave %r, not %r" %
+                     (format, x, got, expected))
+ 
+             # Unpack work?
+             retrieved = unpack(format, got)[0]
+             verify(x == retrieved,
+                    "'%s'-unpack of %r gave %r, not %r" %
+                     (format, got, retrieved, x))
+ 
+             # Adding any byte should cause a "too big" error.
+             any_err(unpack, format, '\x01' + got)
+ 
+             # Try little-endian.
+             format = "<" + code
+             expected = string_reverse(expected)
+ 
+             # Pack work?
+             got = pack(format, x)
+             verify(got == expected,
+                    "'%s'-pack of %r gave %r, not %r" %
+                     (format, x, got, expected))
+ 
+             # Unpack work?
+             retrieved = unpack(format, got)[0]
+             verify(x == retrieved,
+                    "'%s'-unpack of %r gave %r, not %r" %
+                     (format, got, retrieved, x))
+ 
+             # Adding any byte should cause a "too big" error.
+             any_err(unpack, format, '\x01' + got)
+ 
+         else:
+             # x is out of range -- verify pack realizes that.
+             if code in self.BUGGY_RANGE_CHECK:
+                 if verbose:
+                     print "Skipping buggy range check for code", code
+             else:
+                 any_err(pack, ">" + code, x)
+                 any_err(pack, "<" + code, x)
+ 
+         # Much the same for unsigned.
+         code = self.unsigned_code
+         if self.unsigned_min <= x <= self.unsigned_max:
+             # Try big-endian.
+             format = ">" + code
+             expected = long(x)
+             expected = hex(expected)[2:-1] # chop "0x" and trailing 'L'
+             if len(expected) & 1:
+                 expected = "0" + expected
+             expected = unhexlify(expected)
+             expected = "\x00" * (self.bytesize - len(expected)) + expected
+ 
+             # Pack work?
+             got = pack(format, x)
+             verify(got == expected,
+                    "'%s'-pack of %r gave %r, not %r" %
+                     (format, x, got, expected))
+ 
+             # Unpack work?
+             retrieved = unpack(format, got)[0]
+             verify(x == retrieved,
+                    "'%s'-unpack of %r gave %r, not %r" %
+                     (format, got, retrieved, x))
+ 
+             # Adding any byte should cause a "too big" error.
+             any_err(unpack, format, '\x01' + got)
+ 
+             # Try little-endian.
+             format = "<" + code
+             expected = string_reverse(expected)
+ 
+             # Pack work?
+             got = pack(format, x)
+             verify(got == expected,
+                    "'%s'-pack of %r gave %r, not %r" %
+                     (format, x, got, expected))
+ 
+             # Unpack work?
+             retrieved = unpack(format, got)[0]
+             verify(x == retrieved,
+                    "'%s'-unpack of %r gave %r, not %r" %
+                     (format, got, retrieved, x))
+ 
+             # Adding any byte should cause a "too big" error.
+             any_err(unpack, format, '\x01' + got)
+ 
+         else:
+             # x is out of range -- verify pack realizes that.
+             if code in self.BUGGY_RANGE_CHECK:
+                 if verbose:
+                     print "Skipping buggy range check for code", code
+             else:
+                 any_err(pack, ">" + code, x)
+                 any_err(pack, "<" + code, x)
+ 
+     def run(self):
+         from random import randrange
+ 
+         # Create all interesting powers of 2.
+         values = []
+         for exp in range(self.bitsize + 3):
+             values.append(1L << exp)
+ 
+         # Add some random values.
+         for i in range(self.bitsize):
+             val = 0L
+             for j in range(self.bytesize):
+                 val = (val << 8) | randrange(256)
+             values.append(val)
+ 
+         # Try all those, and their negations, and +-1 from them.  Note
+         # that this tests all power-of-2 boundaries in range, and a few out
+         # of range, plus +-(2**n +- 1).
+         for base in values:
+             for val in -base, base:
+                 for incr in -1, 0, 1:
+                     x = val + incr
+                     try:
+                         x = int(x)
+                     except OverflowError:
+                         pass
+                     self.test_one(x)
+ 
+         # Some error cases.
+         for direction in "<>":
+             for code in self.formatpair:
+                 for badobject in "a string", 3+42j, randrange:
+                     any_err(struct.pack, direction + code, badobject)
+ 
+ for args in [("bB", 1),
+              ("hH", 2),
+              ("iI", 4),
+              ("lL", 4),
+              ("qQ", 8)]:
+     t = IntTester(*args)
+     t.run()

Index: test_time.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_time.py,v
retrieving revision 1.6
retrieving revision 1.6.6.1
diff -C2 -r1.6 -r1.6.6.1
*** test_time.py	2000/12/12 23:11:42	1.6
--- test_time.py	2001/07/07 22:55:29	1.6.6.1
***************
*** 1,39 ****
  import time
  
! time.altzone
! time.clock()
! t = time.time()
! time.asctime(time.gmtime(t))
! if time.ctime(t) != time.asctime(time.localtime(t)):
!     print 'time.ctime(t) != time.asctime(time.localtime(t))'
! 
! time.daylight
! if long(time.mktime(time.localtime(t))) != long(t):
!     print 'time.mktime(time.localtime(t)) != t'
! 
! time.sleep(1.2)
! tt = time.gmtime(t)
! for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
!                   'j', 'm', 'M', 'p', 'S',
!                   'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
!     format = ' %' + directive
!     try:
!         time.strftime(format, tt)
!     except ValueError:
!         print 'conversion specifier:', format, ' failed.'
! 
! time.timezone
! time.tzname
! 
! # expected errors
! try:
!     time.asctime(0)
! except TypeError:
!     pass
! 
! try:
!     time.mktime((999999, 999999, 999999, 999999,
!                  999999, 999999, 999999, 999999,
!                  999999))
! except OverflowError:
!     pass
--- 1,51 ----
+ import test_support
  import time
+ import unittest
  
! 
! class TimeTestCase(unittest.TestCase):
! 
!     def setUp(self):
!         self.t = time.time()
! 
!     def test_data_attributes(self):
!         time.altzone
!         time.daylight
!         time.timezone
!         time.tzname
! 
!     def test_clock(self):
!         time.clock()
! 
!     def test_conversions(self):
!         self.assert_(time.ctime(self.t)
!                      == time.asctime(time.localtime(self.t)))
!         self.assert_(long(time.mktime(time.localtime(self.t)))
!                      == long(self.t))
! 
!     def test_sleep(self):
!         time.sleep(1.2)
! 
!     def test_strftime(self):
!         tt = time.gmtime(self.t)
!         for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
!                           'j', 'm', 'M', 'p', 'S',
!                           'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
!             format = ' %' + directive
!             try:
!                 time.strftime(format, tt)
!             except ValueError:
!                 self.fail('conversion specifier: %r failed.' % format)
! 
!     def test_asctime(self):
!         time.asctime(time.gmtime(self.t))
!         self.assertRaises(TypeError, time.asctime, 0)
! 
!     def test_mktime(self):
!         self.assertRaises(OverflowError,
!                           time.mktime, (999999, 999999, 999999, 999999,
!                                         999999, 999999, 999999, 999999,
!                                         999999))
! 
! 
! test_support.run_unittest(TimeTestCase)

Index: test_types.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v
retrieving revision 1.20
retrieving revision 1.20.2.1
diff -C2 -r1.20 -r1.20.2.1
*** test_types.py	2001/04/20 16:50:40	1.20
--- test_types.py	2001/07/07 22:55:29	1.20.2.1
***************
*** 240,250 ****
--- 240,320 ----
  del d['b']
  if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
+ # dict.clear()
  d = {1:1, 2:2, 3:3}
  d.clear()
  if d != {}: raise TestFailed, 'dict clear'
+ # dict.update()
  d.update({1:100})
  d.update({2:20})
  d.update({1:1, 2:2, 3:3})
  if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
+ d.clear()
+ try: d.update(None)
+ except AttributeError: pass
+ else: raise TestFailed, 'dict.update(None), AttributeError expected'
+ class SimpleUserDict:
+     def __init__(self):
+         self.d = {1:1, 2:2, 3:3}
+     def keys(self):
+         return self.d.keys()
+     def __getitem__(self, i):
+         return self.d[i]
+ d.update(SimpleUserDict())
+ if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
+ d.clear()
+ class FailingUserDict:
+     def keys(self):
+         raise ValueError
+ try: d.update(FailingUserDict())
+ except ValueError: pass
+ else: raise TestFailed, 'dict.keys() expected ValueError'
+ class FailingUserDict:
+     def keys(self):
+         class BogonIter:
+             def __iter__(self):
+                 raise ValueError
+         return BogonIter()
+ try: d.update(FailingUserDict())
+ except ValueError: pass
+ else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
+ class FailingUserDict:
+     def keys(self):
+         class BogonIter:
+             def __init__(self):
+                 self.i = 1
+             def __iter__(self):
+                 return self
+             def next(self):
+                 if self.i:
+                     self.i = 0
+                     return 'a'
+                 raise ValueError
+         return BogonIter()
+     def __getitem__(self, key):
+         return key
+ try: d.update(FailingUserDict())
+ except ValueError: pass
+ else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
+ class FailingUserDict:
+     def keys(self):
+         class BogonIter:
+             def __init__(self):
+                 self.i = ord('a')
+             def __iter__(self):
+                 return self
+             def next(self):
+                 if self.i <= ord('z'):
+                     rtn = chr(self.i)
+                     self.i += 1
+                     return rtn
+                 raise StopIteration
+         return BogonIter()
+     def __getitem__(self, key):
+         raise ValueError
+ try: d.update(FailingUserDict())
+ except ValueError: pass
+ else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
+ # dict.copy()
+ d = {1:1, 2:2, 3:3}
  if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
  if {}.copy() != {}: raise TestFailed, 'empty dict copy'

Index: test_weakref.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_weakref.py,v
retrieving revision 1.7
retrieving revision 1.7.4.1
diff -C2 -r1.7 -r1.7.4.1
*** test_weakref.py	2001/04/16 17:37:27	1.7
--- test_weakref.py	2001/07/07 22:55:29	1.7.4.1
***************
*** 230,238 ****
  
      def test_weak_values(self):
!         dict = weakref.WeakValueDictionary()
!         objects = map(Object, range(self.COUNT))
!         for o in objects:
!             dict[o.arg] = o
! 
          for o in objects:
              self.assert_(weakref.getweakrefcount(o) == 1,
--- 230,237 ----
  
      def test_weak_values(self):
!         #
!         #  This exercises d.copy(), d.items(), d[], del d[], len(d).
!         #
!         dict, objects = self.make_weak_valued_dict()
          for o in objects:
              self.assert_(weakref.getweakrefcount(o) == 1,
***************
*** 256,265 ****
  
      def test_weak_keys(self):
!         dict = weakref.WeakKeyDictionary()
!         objects = map(Object, range(self.COUNT))
          for o in objects:
-             dict[o] = o.arg
- 
-         for o in objects:
              self.assert_(weakref.getweakrefcount(o) == 1,
                           "wrong number of weak references to %r!" % o)
--- 255,264 ----
  
      def test_weak_keys(self):
!         #
!         #  This exercises d.copy(), d.items(), d[] = v, d[], del d[],
!         #  len(d).
!         #
!         dict, objects = self.make_weak_keyed_dict()
          for o in objects:
              self.assert_(weakref.getweakrefcount(o) == 1,
                           "wrong number of weak references to %r!" % o)
***************
*** 281,285 ****
--- 280,386 ----
                       "deleting the keys did not clear the dictionary")
  
+     def test_weak_keyed_iters(self):
+         dict, objects = self.make_weak_keyed_dict()
+         self.check_iters(dict)
+ 
+     def test_weak_valued_iters(self):
+         dict, objects = self.make_weak_valued_dict()
+         self.check_iters(dict)
+ 
+     def check_iters(self, dict):
+         # item iterator:
+         items = dict.items()
+         for item in dict.iteritems():
+             items.remove(item)
+         self.assert_(len(items) == 0, "iteritems() did not touch all items")
+ 
+         # key iterator, via __iter__():
+         keys = dict.keys()
+         for k in dict:
+             keys.remove(k)
+         self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
+ 
+         # key iterator, via iterkeys():
+         keys = dict.keys()
+         for k in dict.iterkeys():
+             keys.remove(k)
+         self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
+ 
+         # value iterator:
+         values = dict.values()
+         for v in dict.itervalues():
+             values.remove(v)
+         self.assert_(len(values) == 0, "itervalues() did not touch all values")
+ 
+     def make_weak_keyed_dict(self):
+         dict = weakref.WeakKeyDictionary()
+         objects = map(Object, range(self.COUNT))
+         for o in objects:
+             dict[o] = o.arg
+         return dict, objects
+ 
+     def make_weak_valued_dict(self):
+         dict = weakref.WeakValueDictionary()
+         objects = map(Object, range(self.COUNT))
+         for o in objects:
+             dict[o.arg] = o
+         return dict, objects
+ 
+     def check_popitem(self, klass, key1, value1, key2, value2):
+         weakdict = klass()
+         weakdict[key1] = value1
+         weakdict[key2] = value2
+         self.assert_(len(weakdict) == 2)
+         k, v = weakdict.popitem()
+         self.assert_(len(weakdict) == 1)
+         if k is key1:
+             self.assert_(v is value1)
+         else:
+             self.assert_(v is value2)
+         k, v = weakdict.popitem()
+         self.assert_(len(weakdict) == 0)
+         if k is key1:
+             self.assert_(v is value1)
+         else:
+             self.assert_(v is value2)
+ 
+     def test_weak_valued_dict_popitem(self):
+         self.check_popitem(weakref.WeakValueDictionary,
+                            "key1", C(), "key2", C())
+ 
+     def test_weak_keyed_dict_popitem(self):
+         self.check_popitem(weakref.WeakKeyDictionary,
+                            C(), "value 1", C(), "value 2")
+ 
+     def check_setdefault(self, klass, key, value1, value2):
+         self.assert_(value1 is not value2,
+                      "invalid test"
+                      " -- value parameters must be distinct objects")
+         weakdict = klass()
+         o = weakdict.setdefault(key, value1)
+         self.assert_(o is value1)
+         self.assert_(weakdict.has_key(key))
+         self.assert_(weakdict.get(key) is value1)
+         self.assert_(weakdict[key] is value1)
+ 
+         o = weakdict.setdefault(key, value2)
+         self.assert_(o is value1)
+         self.assert_(weakdict.has_key(key))
+         self.assert_(weakdict.get(key) is value1)
+         self.assert_(weakdict[key] is value1)
+ 
+     def test_weak_valued_dict_setdefault(self):
+         self.check_setdefault(weakref.WeakValueDictionary,
+                               "key", C(), C())
+ 
+     def test_weak_keyed_dict_setdefault(self):
+         self.check_setdefault(weakref.WeakKeyDictionary,
+                               C(), "value 1", "value 2")
+ 
      def check_update(self, klass, dict):
+         #
+         #  This exercises d.update(), len(d), d.keys(), d.has_key(),
+         #  d.get(), d[].
+         #
          weakdict = klass()
          weakdict.update(dict)

Index: test_xmllib.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_xmllib.py,v
retrieving revision 1.4
retrieving revision 1.4.6.1
diff -C2 -r1.4 -r1.4.6.1
*** test_xmllib.py	2001/01/17 21:51:36	1.4
--- test_xmllib.py	2001/07/07 22:55:29	1.4.6.1
***************
*** 3,12 ****
  '''
  
- from test_support import verbose
- 
  testdoc = """\
  <?xml version="1.0" encoding="UTF-8" standalone='yes' ?>
  <!-- comments aren't allowed before the <?xml?> tag,
       but they are allowed before the <!DOCTYPE> tag -->
  <!DOCTYPE greeting [
    <!ELEMENT greeting (#PCDATA)>
--- 3,11 ----
  '''
  
  testdoc = """\
  <?xml version="1.0" encoding="UTF-8" standalone='yes' ?>
  <!-- comments aren't allowed before the <?xml?> tag,
       but they are allowed before the <!DOCTYPE> tag -->
+ <?processing instructions are allowed in the same places as comments ?>
  <!DOCTYPE greeting [
    <!ELEMENT greeting (#PCDATA)>
***************
*** 15,25 ****
  """
  
  import xmllib
! if verbose:
!     parser = xmllib.TestXMLParser()
! else:
!     parser = xmllib.XMLParser()
! 
! for c in testdoc:
!     parser.feed(c)
! parser.close()
--- 14,30 ----
  """
  
+ import test_support
+ import unittest
  import xmllib
! 
! 
! class XMLParserTestCase(unittest.TestCase):
! 
!     def test_simple(self):
!         parser = xmllib.XMLParser()
!         for c in testdoc:
!             parser.feed(c)
!         parser.close()
! 
! 
! test_support.run_unittest(XMLParserTestCase)