Partially merge trunk into p3yk. The removal of Mac/Tools is confusing svn
merge in bad ways, so I'll have to merge that extra-carefully (probably manually.)

Merged revisions 46495-46605 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk

........
  r46495 | tim.peters | 2006-05-28 03:52:38 +0200 (Sun, 28 May 2006) | 2 lines

  Added missing svn:eol-style property to text files.
........
  r46497 | tim.peters | 2006-05-28 12:41:29 +0200 (Sun, 28 May 2006) | 3 lines

  PyErr_Display(), PyErr_WriteUnraisable():  Coverity found a cut-and-paste
  bug in both:  `className` was referenced before being checked for NULL.
........
  r46499 | fredrik.lundh | 2006-05-28 14:06:46 +0200 (Sun, 28 May 2006) | 5 lines

  needforspeed: added Py_MEMCPY macro (currently tuned for Visual C only),
  and use it for string copy operations.  this gives a 20% speedup on some
  string benchmarks.
........
  r46501 | michael.hudson | 2006-05-28 17:51:40 +0200 (Sun, 28 May 2006) | 26 lines

  Quality control, meet exceptions.c.

  Fix a number of problems with the need for speed code:

  One is doing this sort of thing:

      Py_DECREF(self->field);
      self->field = newval;
      Py_INCREF(self->field);

  without being very sure that self->field doesn't start with a
  value that has a __del__, because that almost certainly can lead
  to segfaults.

  As self->args is constrained to be an exact tuple we may as well
  exploit this fact consistently.  This leads to quite a lot of
  simplification (and, hey, probably better performance).

  Add some error checking in places lacking it.

  Fix some rather strange indentation in the Unicode code.

  Delete some trailing whitespace.

  More to come, I haven't fixed all the reference leaks yet...
........
  r46502 | george.yoshida | 2006-05-28 18:39:09 +0200 (Sun, 28 May 2006) | 3 lines

  Patch #1080727: add "encoding" parameter to doctest.DocFileSuite
  Contributed by Bjorn Tillenius.
........
  r46503 | martin.v.loewis | 2006-05-28 18:57:38 +0200 (Sun, 28 May 2006) | 4 lines

  Rest of patch #1490384: Commit icon source, remove
  claim that Erik von Blokland is the author of the
  installer picture.
........
  r46504 | michael.hudson | 2006-05-28 19:40:29 +0200 (Sun, 28 May 2006) | 16 lines

  Quality control, meet exceptions.c, round two.

  Make some functions that should have been static static.

  Fix a bunch of refleaks by fixing the definition of
  MiddlingExtendsException.

  Remove all the __new__ implementations apart from
  BaseException_new.  Rewrite most code that needs it to cope with
  NULL fields (such code could get excercised anyway, the
  __new__-removal just makes it more likely).  This involved
  editing the code for WindowsError, which I can't test.

  This fixes all the refleaks in at least the start of a regrtest
  -R :: run.
........
  r46505 | marc-andre.lemburg | 2006-05-28 19:46:58 +0200 (Sun, 28 May 2006) | 10 lines

  Initial version of systimes - a module to provide platform dependent
  performance measurements.

  The module is currently just a proof-of-concept implementation, but
  will integrated into pybench once it is stable enough.

  License: pybench license.
  Author: Marc-Andre Lemburg.
........
  r46507 | armin.rigo | 2006-05-28 21:13:17 +0200 (Sun, 28 May 2006) | 15 lines

  ("Forward-port" of r46506)

  Remove various dependencies on dictionary order in the standard library
  tests, and one (clearly an oversight, potentially critical) in the
  standard library itself - base64.py.

  Remaining open issues:
   * test_extcall is an output test, messy to make robust
   * tarfile.py has a potential bug here, but I'm not familiar
     enough with this code.  Filed in as SF bug #1496501.
   * urllib2.HTTPPasswordMgr() returns a random result if there is more
     than one matching root path.  I'm asking python-dev for
     clarification...
........
  r46508 | georg.brandl | 2006-05-28 22:11:45 +0200 (Sun, 28 May 2006) | 4 lines

  The empty string is a valid import path.
   (fixes #1496539)
........
  r46509 | georg.brandl | 2006-05-28 22:23:12 +0200 (Sun, 28 May 2006) | 3 lines

  Patch #1496206: urllib2 PasswordMgr ./. default ports
........
  r46510 | georg.brandl | 2006-05-28 22:57:09 +0200 (Sun, 28 May 2006) | 3 lines

  Fix refleaks in UnicodeError get and set methods.
........
  r46511 | michael.hudson | 2006-05-28 23:19:03 +0200 (Sun, 28 May 2006) | 3 lines

  use the UnicodeError traversal and clearing functions in UnicodeError
  subclasses.
........
  r46512 | thomas.wouters | 2006-05-28 23:32:12 +0200 (Sun, 28 May 2006) | 4 lines


  Make last patch valid C89 so Windows compilers can deal with it.
........
  r46513 | georg.brandl | 2006-05-28 23:42:54 +0200 (Sun, 28 May 2006) | 3 lines

  Fix ref-antileak in _struct.c which eventually lead to deallocating None.
........
  r46514 | georg.brandl | 2006-05-28 23:57:35 +0200 (Sun, 28 May 2006) | 4 lines

  Correct None refcount issue in Mac modules. (Are they
  still used?)
........
  r46515 | armin.rigo | 2006-05-29 00:07:08 +0200 (Mon, 29 May 2006) | 3 lines

  A clearer error message when passing -R to regrtest.py with
  release builds of Python.
........
  r46516 | georg.brandl | 2006-05-29 00:14:04 +0200 (Mon, 29 May 2006) | 3 lines

  Fix C function calling conventions in _sre module.
........
  r46517 | georg.brandl | 2006-05-29 00:34:51 +0200 (Mon, 29 May 2006) | 3 lines

  Convert audioop over to METH_VARARGS.
........
  r46518 | georg.brandl | 2006-05-29 00:38:57 +0200 (Mon, 29 May 2006) | 3 lines

  METH_NOARGS functions do get called with two args.
........
  r46519 | georg.brandl | 2006-05-29 11:46:51 +0200 (Mon, 29 May 2006) | 4 lines

  Fix refleak in socketmodule. Replace bogus Py_BuildValue calls.
  Fix refleak in exceptions.
........
  r46520 | nick.coghlan | 2006-05-29 14:43:05 +0200 (Mon, 29 May 2006) | 7 lines

  Apply modified version of Collin Winter's patch #1478788

  Renames functional extension module to _functools and adds a Python
  functools module so that utility functions like update_wrapper can be
  added easily.
........
  r46522 | georg.brandl | 2006-05-29 15:53:16 +0200 (Mon, 29 May 2006) | 3 lines

  Convert fmmodule to METH_VARARGS.
........
  r46523 | georg.brandl | 2006-05-29 16:13:21 +0200 (Mon, 29 May 2006) | 3 lines

  Fix #1494605.
........
  r46524 | georg.brandl | 2006-05-29 16:28:05 +0200 (Mon, 29 May 2006) | 3 lines

  Handle PyMem_Malloc failure in pystrtod.c. Closes #1494671.
........
  r46525 | georg.brandl | 2006-05-29 16:33:55 +0200 (Mon, 29 May 2006) | 3 lines

  Fix compiler warning.
........
  r46526 | georg.brandl | 2006-05-29 16:39:00 +0200 (Mon, 29 May 2006) | 3 lines

  Fix #1494787 (pyclbr counts whitespace as superclass name)
........
  r46527 | bob.ippolito | 2006-05-29 17:47:29 +0200 (Mon, 29 May 2006) | 1 line

  simplify the struct code a bit (no functional changes)
........
  r46528 | armin.rigo | 2006-05-29 19:59:47 +0200 (Mon, 29 May 2006) | 2 lines

  Silence a warning.
........
  r46529 | georg.brandl | 2006-05-29 21:39:45 +0200 (Mon, 29 May 2006) | 3 lines

  Correct some value converting strangenesses.
........
  r46530 | nick.coghlan | 2006-05-29 22:27:44 +0200 (Mon, 29 May 2006) | 1 line

  When adding a module like functools, it helps to let SVN know about the file.
........
  r46531 | georg.brandl | 2006-05-29 22:52:54 +0200 (Mon, 29 May 2006) | 4 lines

  Patches #1497027 and #972322: try HTTP digest auth first,
  and watch out for handler name collisions.
........
  r46532 | georg.brandl | 2006-05-29 22:57:01 +0200 (Mon, 29 May 2006) | 3 lines

  Add News entry for last commit.
........
  r46533 | georg.brandl | 2006-05-29 23:04:52 +0200 (Mon, 29 May 2006) | 4 lines

  Make use of METH_O and METH_NOARGS where possible.
  Use Py_UnpackTuple instead of PyArg_ParseTuple where possible.
........
  r46534 | georg.brandl | 2006-05-29 23:58:42 +0200 (Mon, 29 May 2006) | 3 lines

  Convert more modules to METH_VARARGS.
........
  r46535 | georg.brandl | 2006-05-30 00:00:30 +0200 (Tue, 30 May 2006) | 3 lines

  Whoops.
........
  r46536 | fredrik.lundh | 2006-05-30 00:42:07 +0200 (Tue, 30 May 2006) | 4 lines

  fixed "abc".count("", 100) == -96 error (hopefully, nobody's relying on
  the current behaviour ;-)
........
  r46537 | bob.ippolito | 2006-05-30 00:55:48 +0200 (Tue, 30 May 2006) | 1 line

  struct: modulo math plus warning on all endian-explicit formats for compatibility with older struct usage (ugly)
........
  r46539 | bob.ippolito | 2006-05-30 02:26:01 +0200 (Tue, 30 May 2006) | 1 line

  Add a length check to aifc to ensure it doesn't write a bogus file
........
  r46540 | tim.peters | 2006-05-30 04:25:25 +0200 (Tue, 30 May 2006) | 10 lines

  deprecated_err():  Stop bizarre warning messages when the tests
  are run in the order:

      test_genexps (or any other doctest-based test)
      test_struct
      test_doctest

  The `warnings` module needs an advertised way to save/restore
  its internal filter list.
........
  r46541 | tim.peters | 2006-05-30 04:26:46 +0200 (Tue, 30 May 2006) | 2 lines

  Whitespace normalization.
........
  r46542 | tim.peters | 2006-05-30 04:30:30 +0200 (Tue, 30 May 2006) | 2 lines

  Set a binary svn:mime-type property on this UTF-8 encoded file.
........
  r46543 | neal.norwitz | 2006-05-30 05:18:50 +0200 (Tue, 30 May 2006) | 1 line

  Simplify further by using AddStringConstant
........
  r46544 | tim.peters | 2006-05-30 06:16:25 +0200 (Tue, 30 May 2006) | 6 lines

  Convert relevant dict internals to Py_ssize_t.

  I don't have a box with nearly enough RAM, or an OS,
  that could get close to tickling this, though (requires
  a dict w/ at least 2**31 entries).
........
  r46545 | neal.norwitz | 2006-05-30 06:19:21 +0200 (Tue, 30 May 2006) | 1 line

  Remove stray | in comment
........
  r46546 | neal.norwitz | 2006-05-30 06:25:05 +0200 (Tue, 30 May 2006) | 1 line

  Use Py_SAFE_DOWNCAST for safety.  Fix format strings.  Remove 2 more stray | in comment
........
  r46547 | neal.norwitz | 2006-05-30 06:43:23 +0200 (Tue, 30 May 2006) | 1 line

  No DOWNCAST is required since sizeof(Py_ssize_t) >= sizeof(int) and Py_ReprEntr returns an int
........
  r46548 | tim.peters | 2006-05-30 07:04:59 +0200 (Tue, 30 May 2006) | 3 lines

  dict_print():  Explicitly narrow the return value
  from a (possibly) wider variable.
........
  r46549 | tim.peters | 2006-05-30 07:23:59 +0200 (Tue, 30 May 2006) | 5 lines

  dict_print():  So that Neal & I don't spend the rest of
  our lives taking turns rewriting code that works ;-),
  get rid of casting illusions by declaring a new variable
  with the obvious type.
........
  r46550 | georg.brandl | 2006-05-30 09:04:55 +0200 (Tue, 30 May 2006) | 3 lines

  Restore exception pickle support. #1497319.
........
  r46551 | georg.brandl | 2006-05-30 09:13:29 +0200 (Tue, 30 May 2006) | 3 lines

  Add a test case for exception pickling. args is never NULL.
........
  r46552 | neal.norwitz | 2006-05-30 09:21:10 +0200 (Tue, 30 May 2006) | 1 line

  Don't fail if the (sub)pkgname already exist.
........
  r46553 | georg.brandl | 2006-05-30 09:34:45 +0200 (Tue, 30 May 2006) | 3 lines

  Disallow keyword args for exceptions.
........
  r46554 | neal.norwitz | 2006-05-30 09:36:54 +0200 (Tue, 30 May 2006) | 5 lines

  I'm impatient.  I think this will fix a few more problems with the buildbots.
  I'm not sure this is the best approach, but I can't think of anything better.
  If this creates problems, feel free to revert, but I think it's safe and
  should make things a little better.
........
  r46555 | georg.brandl | 2006-05-30 10:17:00 +0200 (Tue, 30 May 2006) | 4 lines

  Do the check for no keyword arguments in __init__ so that
  subclasses of Exception can be supplied keyword args
........
  r46556 | georg.brandl | 2006-05-30 10:47:19 +0200 (Tue, 30 May 2006) | 3 lines

  Convert test_exceptions to unittest.
........
  r46557 | andrew.kuchling | 2006-05-30 14:52:01 +0200 (Tue, 30 May 2006) | 1 line

  Add SoC name, and reorganize this section a bit
........
  r46559 | tim.peters | 2006-05-30 17:53:34 +0200 (Tue, 30 May 2006) | 11 lines

  PyLong_FromString():  Continued fraction analysis (explained in
  a new comment) suggests there are almost certainly large input
  integers in all non-binary input bases for which one Python digit
  too few is initally allocated to hold the final result.  Instead
  of assert-failing when that happens, allocate more space.  Alas,
  I estimate it would take a few days to find a specific such case,
  so this isn't backed up by a new test (not to mention that such
  a case may take hours to run, since conversion time is quadratic
  in the number of digits, and preliminary attempts suggested that
  the smallest such inputs contain at least a million digits).
........
  r46560 | fredrik.lundh | 2006-05-30 19:11:48 +0200 (Tue, 30 May 2006) | 3 lines

  changed find/rfind to return -1 for matches outside the source string
........
  r46561 | bob.ippolito | 2006-05-30 19:37:54 +0200 (Tue, 30 May 2006) | 1 line

  Change wrapping terminology to overflow masking
........
  r46562 | fredrik.lundh | 2006-05-30 19:39:58 +0200 (Tue, 30 May 2006) | 3 lines

  changed count to return 0 for slices outside the source string
........
  r46568 | tim.peters | 2006-05-31 01:28:02 +0200 (Wed, 31 May 2006) | 2 lines

  Whitespace normalization.
........
  r46569 | brett.cannon | 2006-05-31 04:19:54 +0200 (Wed, 31 May 2006) | 5 lines

  Clarify wording on default values for strptime(); defaults are used when better
  values cannot be inferred.

  Closes bug #1496315.
........
  r46572 | neal.norwitz | 2006-05-31 09:43:27 +0200 (Wed, 31 May 2006) | 1 line

  Calculate smallest properly (it was off by one) and use proper ssize_t types for Win64
........
  r46573 | neal.norwitz | 2006-05-31 10:01:08 +0200 (Wed, 31 May 2006) | 1 line

  Revert last checkin, it is better to do make distclean
........
  r46574 | neal.norwitz | 2006-05-31 11:02:44 +0200 (Wed, 31 May 2006) | 3 lines

  On 64-bit platforms running test_struct after test_tarfile would fail
  since the deprecation warning wouldn't be raised.
........
  r46575 | thomas.heller | 2006-05-31 13:37:58 +0200 (Wed, 31 May 2006) | 3 lines

  PyTuple_Pack is not available in Python 2.3, but ctypes must stay
  compatible with that.
........
  r46576 | andrew.kuchling | 2006-05-31 15:18:56 +0200 (Wed, 31 May 2006) | 1 line

  'functional' module was renamed to 'functools'
........
  r46577 | kristjan.jonsson | 2006-05-31 15:35:41 +0200 (Wed, 31 May 2006) | 1 line

  Fixup the PCBuild8 project directory.  exceptions.c have moved to Objects, and the functionalmodule.c has been replaced with _functoolsmodule.c.  Other minor changes to .vcproj files and .sln to fix compilation
........
  r46578 | andrew.kuchling | 2006-05-31 16:08:48 +0200 (Wed, 31 May 2006) | 15 lines

  [Bug #1473048]
  SimpleXMLRPCServer and DocXMLRPCServer don't look at
  the path of the HTTP request at all; you can POST or
  GET from / or /RPC2 or /blahblahblah with the same results.
  Security scanners that look for /cgi-bin/phf will therefore report
  lots of vulnerabilities.

  Fix: add a .rpc_paths attribute to the SimpleXMLRPCServer class,
  and report a 404 error if the path isn't on the allowed list.

  Possibly-controversial aspect of this change: the default makes only
  '/' and '/RPC2' legal.  Maybe this will break people's applications
  (though I doubt it).  We could just set the default to an empty tuple,
  which would exactly match the current behaviour.
........
  r46579 | andrew.kuchling | 2006-05-31 16:12:47 +0200 (Wed, 31 May 2006) | 1 line

  Mention SimpleXMLRPCServer change
........
  r46580 | tim.peters | 2006-05-31 16:28:07 +0200 (Wed, 31 May 2006) | 2 lines

  Trimmed trailing whitespace.
........
  r46581 | tim.peters | 2006-05-31 17:33:22 +0200 (Wed, 31 May 2006) | 4 lines

  _range_error():  Speed and simplify (there's no real need for
  loops here).  Assert that size_t is actually big enough, and
  that f->size is at least one.  Wrap a long line.
........
  r46582 | tim.peters | 2006-05-31 17:34:37 +0200 (Wed, 31 May 2006) | 2 lines

  Repaired error in new comment.
........
  r46584 | neal.norwitz | 2006-06-01 07:32:49 +0200 (Thu, 01 Jun 2006) | 4 lines

  Remove ; at end of macro.  There was a compiler recently that warned
  about extra semi-colons.  It may have been the HP C compiler.
  This file will trigger a bunch of those warnings now.
........
  r46585 | georg.brandl | 2006-06-01 08:39:19 +0200 (Thu, 01 Jun 2006) | 3 lines

  Correctly unpickle 2.4 exceptions via __setstate__ (patch #1498571)
........
  r46586 | georg.brandl | 2006-06-01 10:27:32 +0200 (Thu, 01 Jun 2006) | 3 lines

  Correctly allocate complex types with tp_alloc. (bug #1498638)
........
  r46587 | georg.brandl | 2006-06-01 14:30:46 +0200 (Thu, 01 Jun 2006) | 2 lines

  Correctly dispatch Faults in loads (patch #1498627)
........
  r46588 | georg.brandl | 2006-06-01 15:00:49 +0200 (Thu, 01 Jun 2006) | 3 lines

  Some code style tweaks, and remove apply.
........
  r46589 | armin.rigo | 2006-06-01 15:19:12 +0200 (Thu, 01 Jun 2006) | 5 lines

  [ 1497053 ] Let dicts propagate the exceptions in user __eq__().

  [ 1456209 ] dictresize() vulnerability ( <- backport candidate ).
........
  r46590 | tim.peters | 2006-06-01 15:41:46 +0200 (Thu, 01 Jun 2006) | 2 lines

  Whitespace normalization.
........
  r46591 | tim.peters | 2006-06-01 15:49:23 +0200 (Thu, 01 Jun 2006) | 2 lines

  Record bugs 1275608 and 1456209 as being fixed.
........
  r46592 | tim.peters | 2006-06-01 15:56:26 +0200 (Thu, 01 Jun 2006) | 5 lines

  Re-enable a new empty-string test added during the NFS sprint,
  but disabled then because str and unicode strings gave different
  results.  The implementations were repaired later during the
  sprint, but the new test remained disabled.
........
  r46594 | tim.peters | 2006-06-01 17:50:44 +0200 (Thu, 01 Jun 2006) | 7 lines

  Armin committed his patch while I was reviewing it (I'm sure
  he didn't know this), so merged in some changes I made during
  review.  Nothing material apart from changing a new `mask` local
  from int to Py_ssize_t.  Mostly this is repairing comments that
  were made incorrect, and adding new comments.  Also a few
  minor code rewrites for clarity or helpful succinctness.
........
  r46599 | neal.norwitz | 2006-06-02 06:45:53 +0200 (Fri, 02 Jun 2006) | 1 line

  Convert docstrings to comments so regrtest -v prints method names
........
  r46600 | neal.norwitz | 2006-06-02 06:50:49 +0200 (Fri, 02 Jun 2006) | 2 lines

  Fix memory leak found by valgrind.
........
  r46601 | neal.norwitz | 2006-06-02 06:54:52 +0200 (Fri, 02 Jun 2006) | 1 line

  More memory leaks from valgrind
........
  r46602 | neal.norwitz | 2006-06-02 08:23:00 +0200 (Fri, 02 Jun 2006) | 11 lines

  Patch #1357836:

  Prevent an invalid memory read from test_coding in case the done flag is set.
  In that case, the loop isn't entered.  I wonder if rather than setting
  the done flag in the cases before the loop, if they should just exit early.

  This code looks like it should be refactored.

  Backport candidate (also the early break above if decoding_fgets fails)
........
  r46603 | martin.blais | 2006-06-02 15:03:43 +0200 (Fri, 02 Jun 2006) | 1 line

  Fixed struct test to not use unittest.
........
  r46605 | tim.peters | 2006-06-03 01:22:51 +0200 (Sat, 03 Jun 2006) | 10 lines

  pprint functions used to sort a dict (by key) if and only if
  the output required more than one line.  "Small" dicts got
  displayed in seemingly random order (the hash-induced order
  produced by dict.__repr__).  None of this was documented.
  Now pprint functions always sort dicts by key, and the docs
  promise it.

  This was proposed and agreed to during the PyCon 2006 core
  sprint -- I just didn't have time for it before now.
........
diff --git a/Lib/test/crashers/dictresize_attack.py b/Lib/test/crashers/dictresize_attack.py
deleted file mode 100644
index 1895791..0000000
--- a/Lib/test/crashers/dictresize_attack.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# http://www.python.org/sf/1456209
-
-# A dictresize() attack.  If oldtable == mp->ma_smalltable then pure
-# Python code can mangle with mp->ma_smalltable while it is being walked
-# over.
-
-class X(object):
-
-    def __hash__(self):
-        return 5
-
-    def __eq__(self, other):
-        if resizing:
-            d.clear()
-        return False
-
-
-d = {}
-
-resizing = False
-
-d[X()] = 1
-d[X()] = 2
-d[X()] = 3
-d[X()] = 4
-d[X()] = 5
-
-# now trigger a resize
-resizing = True
-d[9] = 6
-
-# ^^^ I get Segmentation fault or Illegal instruction here.
diff --git a/Lib/test/output/test_exceptions b/Lib/test/output/test_exceptions
deleted file mode 100644
index 28a7aa8..0000000
--- a/Lib/test/output/test_exceptions
+++ /dev/null
@@ -1,52 +0,0 @@
-test_exceptions
-5. Built-in exceptions
-spam
-AttributeError
-spam
-EOFError
-spam
-IOError
-spam
-ImportError
-spam
-IndexError
-'spam'
-KeyError
-spam
-KeyboardInterrupt
-(not testable in a script)
-spam
-MemoryError
-(not safe to test)
-spam
-NameError
-spam
-OverflowError
-spam
-RuntimeError
-(not used any more?)
-spam
-SyntaxError
-'continue' not supported inside 'finally' clause
-ok
-'continue' not properly in loop
-ok
-'continue' not properly in loop
-ok
-spam
-IndentationError
-spam
-TabError
-spam
-SystemError
-(hard to reproduce)
-spam
-SystemExit
-spam
-TypeError
-spam
-ValueError
-spam
-ZeroDivisionError
-spam
-Exception
diff --git a/Lib/test/output/test_operations b/Lib/test/output/test_operations
index 32eff3f..8a1bc2a 100644
--- a/Lib/test/output/test_operations
+++ b/Lib/test/output/test_operations
@@ -1,6 +1,21 @@
 test_operations
 3. Operations
 XXX Mostly not yet implemented
-3.1 Dictionary lookups succeed even if __cmp__() raises an exception
+3.1 Dictionary lookups fail if __cmp__() raises an exception
 raising error
-No exception passed through.
+d[x2] = 2: caught the RuntimeError outside
+raising error
+z = d[x2]: caught the RuntimeError outside
+raising error
+x2 in d: caught the RuntimeError outside
+raising error
+d.has_key(x2): caught the RuntimeError outside
+raising error
+d.get(x2): caught the RuntimeError outside
+raising error
+d.setdefault(x2, 42): caught the RuntimeError outside
+raising error
+d.pop(x2): caught the RuntimeError outside
+raising error
+d.update({x2: 2}): caught the RuntimeError outside
+resize bugs not triggered.
diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py
index 86961b0..314e7e1 100755
--- a/Lib/test/regrtest.py
+++ b/Lib/test/regrtest.py
@@ -513,6 +513,9 @@
     else:
         cfp = cStringIO.StringIO()
     if huntrleaks:
+        if not hasattr(sys, 'gettotalrefcount'):
+            raise Exception("Tracking reference leaks requires a debug build "
+                            "of Python")
         refrep = open(huntrleaks[2], "a")
     try:
         save_stdout = sys.stdout
diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py
index 489af20..aaa2dc2 100644
--- a/Lib/test/string_tests.py
+++ b/Lib/test/string_tests.py
@@ -106,10 +106,19 @@
         self.checkequal(3, 'aaa', 'count', 'a')
         self.checkequal(0, 'aaa', 'count', 'b')
         self.checkequal(0, 'aaa', 'count', 'b')
+        self.checkequal(2, 'aaa', 'count', 'a', 1)
+        self.checkequal(0, 'aaa', 'count', 'a', 10)
         self.checkequal(1, 'aaa', 'count', 'a', -1)
         self.checkequal(3, 'aaa', 'count', 'a', -10)
+        self.checkequal(1, 'aaa', 'count', 'a', 0, 1)
+        self.checkequal(3, 'aaa', 'count', 'a', 0, 10)
         self.checkequal(2, 'aaa', 'count', 'a', 0, -1)
         self.checkequal(0, 'aaa', 'count', 'a', 0, -10)
+        self.checkequal(3, 'aaa', 'count', '', 1)
+        self.checkequal(1, 'aaa', 'count', '', 3)
+        self.checkequal(0, 'aaa', 'count', '', 10)
+        self.checkequal(2, 'aaa', 'count', '', -1)
+        self.checkequal(4, 'aaa', 'count', '', -10)
 
         self.checkraises(TypeError, 'hello', 'count')
         self.checkraises(TypeError, 'hello', 'count', 42)
@@ -146,6 +155,10 @@
         self.checkequal(9, 'abcdefghiabc', 'find', 'abc', 1)
         self.checkequal(-1, 'abcdefghiabc', 'find', 'def', 4)
 
+        self.checkequal(0, 'abc', 'find', '', 0)
+        self.checkequal(3, 'abc', 'find', '', 3)
+        self.checkequal(-1, 'abc', 'find', '', 4)
+
         self.checkraises(TypeError, 'hello', 'find')
         self.checkraises(TypeError, 'hello', 'find', 42)
 
@@ -180,6 +193,10 @@
         self.checkequal(0, 'abcdefghiabc', 'rfind', 'abcd')
         self.checkequal(-1, 'abcdefghiabc', 'rfind', 'abcz')
 
+        self.checkequal(3, 'abc', 'rfind', '', 0)
+        self.checkequal(3, 'abc', 'rfind', '', 3)
+        self.checkequal(-1, 'abc', 'rfind', '', 4)
+
         self.checkraises(TypeError, 'hello', 'rfind')
         self.checkraises(TypeError, 'hello', 'rfind', 42)
 
@@ -477,12 +494,7 @@
 
         # Operations on the empty string
         EQ("", "", "replace", "", "")
-
-        #EQ("A", "", "replace", "", "A")
-        # That was the correct result; this is the result we actually get
-        # now (for str, but not for unicode):
-        #EQ("", "", "replace", "", "A")
-
+        EQ("A", "", "replace", "", "A")
         EQ("", "", "replace", "A", "")
         EQ("", "", "replace", "A", "A")
         EQ("", "", "replace", "", "", 100)
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index 8511a5a..feb6ddf 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -875,7 +875,10 @@
     def test_delimiters(self):
         sniffer = csv.Sniffer()
         dialect = sniffer.sniff(self.sample3)
-        self.assertEqual(dialect.delimiter, "0")
+        # given that all three lines in sample3 are equal,
+        # I think that any character could have been 'guessed' as the
+        # delimiter, depending on dictionary order
+        self.assert_(dialect.delimiter in self.sample3)
         dialect = sniffer.sniff(self.sample3, delimiters="?,")
         self.assertEqual(dialect.delimiter, "?")
         dialect = sniffer.sniff(self.sample3, delimiters="/,")
diff --git a/Lib/test/test_doctest.py b/Lib/test/test_doctest.py
index 443c962..92d2d74 100644
--- a/Lib/test/test_doctest.py
+++ b/Lib/test/test_doctest.py
@@ -1937,9 +1937,10 @@
 
          >>> import unittest
          >>> suite = doctest.DocFileSuite('test_doctest.txt',
-         ...                              'test_doctest2.txt')
+         ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt')
          >>> suite.run(unittest.TestResult())
-         <unittest.TestResult run=2 errors=0 failures=2>
+         <unittest.TestResult run=3 errors=0 failures=3>
 
        The test files are looked for in the directory containing the
        calling module.  A package keyword argument can be provided to
@@ -1948,9 +1949,10 @@
          >>> import unittest
          >>> suite = doctest.DocFileSuite('test_doctest.txt',
          ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt',
          ...                              package='test')
          >>> suite.run(unittest.TestResult())
-         <unittest.TestResult run=2 errors=0 failures=2>
+         <unittest.TestResult run=3 errors=0 failures=3>
 
        '/' should be used as a path separator.  It will be converted
        to a native separator at run time:
@@ -1995,19 +1997,21 @@
 
          >>> suite = doctest.DocFileSuite('test_doctest.txt',
          ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt',
          ...                              globs={'favorite_color': 'blue'})
          >>> suite.run(unittest.TestResult())
-         <unittest.TestResult run=2 errors=0 failures=1>
+         <unittest.TestResult run=3 errors=0 failures=2>
 
        In this case, we supplied a missing favorite color. You can
        provide doctest options:
 
          >>> suite = doctest.DocFileSuite('test_doctest.txt',
          ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt',
          ...                         optionflags=doctest.DONT_ACCEPT_BLANKLINE,
          ...                              globs={'favorite_color': 'blue'})
          >>> suite.run(unittest.TestResult())
-         <unittest.TestResult run=2 errors=0 failures=2>
+         <unittest.TestResult run=3 errors=0 failures=3>
 
        And, you can provide setUp and tearDown functions:
 
@@ -2025,9 +2029,10 @@
 
          >>> suite = doctest.DocFileSuite('test_doctest.txt',
          ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt',
          ...                              setUp=setUp, tearDown=tearDown)
          >>> suite.run(unittest.TestResult())
-         <unittest.TestResult run=2 errors=0 failures=1>
+         <unittest.TestResult run=3 errors=0 failures=2>
 
        But the tearDown restores sanity:
 
@@ -2060,6 +2065,17 @@
          >>> suite.run(unittest.TestResult())
          <unittest.TestResult run=1 errors=0 failures=0>
 
+       If the tests contain non-ASCII characters, we have to specify which
+       encoding the file is encoded with. We do so by using the `encoding`
+       parameter:
+
+         >>> suite = doctest.DocFileSuite('test_doctest.txt',
+         ...                              'test_doctest2.txt',
+         ...                              'test_doctest4.txt',
+         ...                              encoding='utf-8')
+         >>> suite.run(unittest.TestResult())
+         <unittest.TestResult run=3 errors=0 failures=2>
+
        """
 
 def test_trailing_space_in_test():
@@ -2266,6 +2282,32 @@
     Traceback (most recent call last):
     UnexpectedException: ...
     >>> doctest.master = None  # Reset master.
+
+If the tests contain non-ASCII characters, the tests might fail, since
+it's unknown which encoding is used. The encoding can be specified
+using the optional keyword argument `encoding`:
+
+    >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
+    **********************************************************************
+    File "...", line 7, in test_doctest4.txt
+    Failed example:
+        u'...'
+    Expected:
+        u'f\xf6\xf6'
+    Got:
+        u'f\xc3\xb6\xc3\xb6'
+    **********************************************************************
+    ...
+    **********************************************************************
+    1 items had failures:
+       2 of   4 in test_doctest4.txt
+    ***Test Failed*** 2 failures.
+    (2, 4)
+    >>> doctest.master = None  # Reset master.
+
+    >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
+    (0, 4)
+    >>> doctest.master = None  # Reset master.
 """
 
 # old_test1, ... used to live in doctest.py, but cluttered it.  Note
diff --git a/Lib/test/test_doctest4.txt b/Lib/test/test_doctest4.txt
new file mode 100644
index 0000000..a219d16
--- /dev/null
+++ b/Lib/test/test_doctest4.txt
@@ -0,0 +1,17 @@
+This is a sample doctest in a text file that contains non-ASCII characters.
+This file is encoded using UTF-8.
+
+In order to get this test to pass, we have to manually specify the
+encoding.
+
+  >>> u'föö'
+  u'f\xf6\xf6'
+
+  >>> u'bąr'
+  u'b\u0105r'
+
+  >>> 'föö'
+  'f\xc3\xb6\xc3\xb6'
+
+  >>> 'bąr'
+  'b\xc4\x85r'
diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py
index 8f995f7..ebab913 100644
--- a/Lib/test/test_exceptions.py
+++ b/Lib/test/test_exceptions.py
@@ -1,303 +1,310 @@
 # Python test set -- part 5, built-in exceptions
 
-from test.test_support import TestFailed, TESTFN, unlink
-from types import ClassType
+from test.test_support import TESTFN, unlink, run_unittest
 import warnings
 import sys, traceback, os
+import unittest
 
-print '5. Built-in exceptions'
 # XXX This is not really enough, each *operation* should be tested!
 
-# Reloading the built-in exceptions module failed prior to Py2.2, while it
-# should act the same as reloading built-in sys.
-try:
-    import exceptions
-    reload(exceptions)
-except ImportError, e:
-    raise TestFailed, e
+class ExceptionTests(unittest.TestCase):
 
-def test_raise_catch(exc):
-    try:
-        raise exc, "spam"
-    except exc, err:
-        buf = str(err)
-    try:
-        raise exc("spam")
-    except exc, err:
-        buf = str(err)
-    print buf
+    def testReload(self):
+        # Reloading the built-in exceptions module failed prior to Py2.2, while it
+        # should act the same as reloading built-in sys.
+        try:
+            import exceptions
+            reload(exceptions)
+        except ImportError, e:
+            self.fail("reloading exceptions: %s" % e)
 
-def r(thing):
-    test_raise_catch(thing)
-    print getattr(thing, '__name__', thing)
+    def raise_catch(self, exc, excname):
+        try:
+            raise exc, "spam"
+        except exc, err:
+            buf1 = str(err)
+        try:
+            raise exc("spam")
+        except exc, err:
+            buf2 = str(err)
+        self.assertEquals(buf1, buf2)
+        self.assertEquals(exc.__name__, excname)
 
-r(AttributeError)
-import sys
-try: x = sys.undefined_attribute
-except AttributeError: pass
+    def testRaising(self):
+        self.raise_catch(AttributeError, "AttributeError")
+        self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
 
-r(EOFError)
-import sys
-fp = open(TESTFN, 'w')
-fp.close()
-fp = open(TESTFN, 'r')
-savestdin = sys.stdin
-try:
-    try:
-        import marshal
-        marshal.loads('')
-    except EOFError:
-        pass
-finally:
-    sys.stdin = savestdin
-    fp.close()
+        self.raise_catch(EOFError, "EOFError")
+        fp = open(TESTFN, 'w')
+        fp.close()
+        fp = open(TESTFN, 'r')
+        savestdin = sys.stdin
+        try:
+            try:
+                import marshal
+                marshal.loads('')
+            except EOFError:
+                pass
+        finally:
+            sys.stdin = savestdin
+            fp.close()
+            unlink(TESTFN)
 
-r(IOError)
-try: open('this file does not exist', 'r')
-except IOError: pass
+        self.raise_catch(IOError, "IOError")
+        self.assertRaises(IOError, open, 'this file does not exist', 'r')
 
-r(ImportError)
-try: import undefined_module
-except ImportError: pass
+        self.raise_catch(ImportError, "ImportError")
+        self.assertRaises(ImportError, __import__, "undefined_module")
 
-r(IndexError)
-x = []
-try: a = x[10]
-except IndexError: pass
+        self.raise_catch(IndexError, "IndexError")
+        x = []
+        self.assertRaises(IndexError, x.__getitem__, 10)
 
-r(KeyError)
-x = {}
-try: a = x['key']
-except KeyError: pass
+        self.raise_catch(KeyError, "KeyError")
+        x = {}
+        self.assertRaises(KeyError, x.__getitem__, 'key')
 
-r(KeyboardInterrupt)
-print '(not testable in a script)'
+        self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
 
-r(MemoryError)
-print '(not safe to test)'
+        self.raise_catch(MemoryError, "MemoryError")
 
-r(NameError)
-try: x = undefined_variable
-except NameError: pass
+        self.raise_catch(NameError, "NameError")
+        try: x = undefined_variable
+        except NameError: pass
 
-r(OverflowError)
-x = 1
-for dummy in range(128):
-    x += x  # this simply shouldn't blow up
+        self.raise_catch(OverflowError, "OverflowError")
+        x = 1
+        for dummy in range(128):
+            x += x  # this simply shouldn't blow up
 
-r(RuntimeError)
-print '(not used any more?)'
+        self.raise_catch(RuntimeError, "RuntimeError")
 
-r(SyntaxError)
-try: exec '/\n'
-except SyntaxError: pass
+        self.raise_catch(SyntaxError, "SyntaxError")
+        try: exec '/\n'
+        except SyntaxError: pass
 
-# make sure the right exception message is raised for each of these
-# code fragments:
+        self.raise_catch(IndentationError, "IndentationError")
 
-def ckmsg(src, msg):
-    try:
-        compile(src, '<fragment>', 'exec')
-    except SyntaxError, e:
-        print e.msg
-        if e.msg == msg:
-            print "ok"
-        else:
-            print "expected:", msg
-    else:
-        print "failed to get expected SyntaxError"
+        self.raise_catch(TabError, "TabError")
+        # can only be tested under -tt, and is the only test for -tt
+        #try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')
+        #except TabError: pass
+        #else: self.fail("TabError not raised")
 
-s = '''\
-while 1:
-    try:
-        pass
-    finally:
-        continue
-'''
-if sys.platform.startswith('java'):
-    print "'continue' not supported inside 'finally' clause"
-    print "ok"
-else:
-    ckmsg(s, "'continue' not supported inside 'finally' clause")
-s = '''\
-try:
-    continue
-except:
-    pass
-'''
-ckmsg(s, "'continue' not properly in loop")
-ckmsg("continue\n", "'continue' not properly in loop")
+        self.raise_catch(SystemError, "SystemError")
 
-r(IndentationError)
+        self.raise_catch(SystemExit, "SystemExit")
+        self.assertRaises(SystemExit, sys.exit, 0)
 
-r(TabError)
-# can only be tested under -tt, and is the only test for -tt
-#try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')
-#except TabError: pass
-#else: raise TestFailed
+        self.raise_catch(TypeError, "TypeError")
+        try: [] + ()
+        except TypeError: pass
 
-r(SystemError)
-print '(hard to reproduce)'
+        self.raise_catch(ValueError, "ValueError")
+        self.assertRaises(ValueError, chr, 10000)
 
-r(SystemExit)
-import sys
-try: sys.exit(0)
-except SystemExit: pass
+        self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
+        try: x = 1/0
+        except ZeroDivisionError: pass
 
-r(TypeError)
-try: [] + ()
-except TypeError: pass
+        self.raise_catch(Exception, "Exception")
+        try: x = 1/0
+        except Exception, e: pass
 
-r(ValueError)
-try: x = chr(10000)
-except ValueError: pass
+    def testSyntaxErrorMessage(self):
+        # make sure the right exception message is raised for each of
+        # these code fragments
 
-r(ZeroDivisionError)
-try: x = 1/0
-except ZeroDivisionError: pass
+        def ckmsg(src, msg):
+            try:
+                compile(src, '<fragment>', 'exec')
+            except SyntaxError, e:
+                if e.msg != msg:
+                    self.fail("expected %s, got %s" % (msg, e.msg))
+            else:
+                self.fail("failed to get expected SyntaxError")
 
-r(Exception)
-try: x = 1/0
-except Exception, e: pass
+        s = '''while 1:
+            try:
+                pass
+            finally:
+                continue'''
 
-# test that setting an exception at the C level works even if the
-# exception object can't be constructed.
+        if not sys.platform.startswith('java'):
+            ckmsg(s, "'continue' not supported inside 'finally' clause")
 
-class BadException(Exception):
-    def __init__(self):
-        raise RuntimeError, "can't instantiate BadException"
+        s = '''if 1:
+        try:
+            continue
+        except:
+            pass'''
 
-# Exceptions must inherit from BaseException, raising invalid exception
-# should instead raise SystemError
-class InvalidException:
-    pass
+        ckmsg(s, "'continue' not properly in loop")
+        ckmsg("continue\n", "'continue' not properly in loop")
 
-def test_capi1():
-    import _testcapi
-    try:
-        _testcapi.raise_exception(BadException, 1)
-    except TypeError, err:
-        exc, err, tb = sys.exc_info()
-        co = tb.tb_frame.f_code
-        assert co.co_name == "test_capi1"
-        assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
-    else:
-        print "Expected exception"
+    def testSettingException(self):
+        # test that setting an exception at the C level works even if the
+        # exception object can't be constructed.
 
-def test_capi2():
-    import _testcapi
-    try:
-        _testcapi.raise_exception(BadException, 0)
-    except RuntimeError, err:
-        exc, err, tb = sys.exc_info()
-        co = tb.tb_frame.f_code
-        assert co.co_name == "__init__"
-        assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
-        co2 = tb.tb_frame.f_back.f_code
-        assert co2.co_name == "test_capi2"
-    else:
-        print "Expected exception"
+        class BadException(Exception):
+            def __init__(self_):
+                raise RuntimeError, "can't instantiate BadException"
 
-def test_capi3():
-    import _testcapi
-    try:
-        _testcapi.raise_exception(InvalidException, 1)
-    except SystemError:
-        pass
-    except InvalidException:
-        raise AssertionError("Managed to raise InvalidException");
-    else:
-        print "Expected SystemError exception"
-    
+        class InvalidException:
+            pass
 
-if not sys.platform.startswith('java'):
-    test_capi1()
-    test_capi2()
-    test_capi3()
+        def test_capi1():
+            import _testcapi
+            try:
+                _testcapi.raise_exception(BadException, 1)
+            except TypeError, err:
+                exc, err, tb = sys.exc_info()
+                co = tb.tb_frame.f_code
+                self.assertEquals(co.co_name, "test_capi1")
+                self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
+            else:
+                self.fail("Expected exception")
 
-unlink(TESTFN)
+        def test_capi2():
+            import _testcapi
+            try:
+                _testcapi.raise_exception(BadException, 0)
+            except RuntimeError, err:
+                exc, err, tb = sys.exc_info()
+                co = tb.tb_frame.f_code
+                self.assertEquals(co.co_name, "__init__")
+                self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
+                co2 = tb.tb_frame.f_back.f_code
+                self.assertEquals(co2.co_name, "test_capi2")
+            else:
+                self.fail("Expected exception")
 
-#  test that exception attributes are happy.
-try: str(u'Hello \u00E1')
-except Exception, e: sampleUnicodeEncodeError = e
-try: unicode('\xff')
-except Exception, e: sampleUnicodeDecodeError = e
-exceptionList = [
-        ( BaseException, (), { 'message' : '', 'args' : () }),
-        ( BaseException, (1, ), { 'message' : 1, 'args' : ( 1, ) }),
-        ( BaseException, ('foo', ), { 'message' : 'foo', 'args' : ( 'foo', ) }),
-        ( BaseException, ('foo', 1), { 'message' : '', 'args' : ( 'foo', 1 ) }),
-        ( SystemExit, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ),
-                'code' : 'foo' }),
-        ( IOError, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ), }),
-        ( IOError, ('foo', 'bar'), { 'message' : '',
-                'args' : ('foo', 'bar'), }),
-        ( IOError, ('foo', 'bar', 'baz'),
-                 { 'message' : '', 'args' : ('foo', 'bar'), }),
-        ( EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
-                { 'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
-                    'strerror' : 'strErrorStr',
-                    'errno' : 'errnoStr', 'filename' : 'filenameStr' }),
-        ( EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
-                { 'message' : '', 'args' : (1, 'strErrorStr'),
-                    'strerror' : 'strErrorStr', 'errno' : 1,
-                    'filename' : 'filenameStr' }),
-        ( SyntaxError, ('msgStr',),
-                { 'message' : 'msgStr', 'args' : ('msgStr', ),
-                    'print_file_and_line' : None, 'msg' : 'msgStr',
-                    'filename' : None, 'lineno' : None, 'offset' : None,
-                    'text' : None }),
-        ( SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
-                        'textStr')),
-                { 'message' : '', 'args' : ('msgStr', ('filenameStr',
-                        'linenoStr', 'offsetStr', 'textStr' )),
-                    'print_file_and_line' : None, 'msg' : 'msgStr',
-                    'filename' : 'filenameStr', 'lineno' : 'linenoStr',
-                    'offset' : 'offsetStr', 'text' : 'textStr' }),
-        ( SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
-                    'textStr', 'print_file_and_lineStr'),
-                { 'message' : '', 'args' : ('msgStr', 'filenameStr',
-                        'linenoStr', 'offsetStr', 'textStr',
-                        'print_file_and_lineStr'),
-                    'print_file_and_line' : None, 'msg' : 'msgStr',
-                    'filename' : None, 'lineno' : None, 'offset' : None,
-                    'text' : None }),
-        ( UnicodeError, (),
-                { 'message' : '', 'args' : (), }),
-        ( sampleUnicodeEncodeError,
-                { 'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
-                        'ordinal not in range(128)'),
-                    'encoding' : 'ascii', 'object' : u'Hello \xe1',
-                    'start' : 6, 'reason' : 'ordinal not in range(128)' }),
-        ( sampleUnicodeDecodeError,
-                { 'message' : '', 'args' : ('ascii', '\xff', 0, 1,
-                        'ordinal not in range(128)'),
-                    'encoding' : 'ascii', 'object' : '\xff',
-                    'start' : 0, 'reason' : 'ordinal not in range(128)' }),
-        ( UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
-                { 'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
-                    'object' : u'\u3042', 'reason' : 'ouch',
-                    'start' : 0, 'end' : 1 }),
+        def test_capi3():
+            import _testcapi
+            self.assertRaises(SystemError, _testcapi.raise_exception,
+                              InvalidException, 1)
+
+        if not sys.platform.startswith('java'):
+            test_capi1()
+            test_capi2()
+            test_capi3()
+
+    def testAttributes(self):
+        # test that exception attributes are happy
+        try: str(u'Hello \u00E1')
+        except Exception, e: sampleUnicodeEncodeError = e
+
+        try: unicode('\xff')
+        except Exception, e: sampleUnicodeDecodeError = e
+
+        exceptionList = [
+            (BaseException, (), {'message' : '', 'args' : ()}),
+            (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
+            (BaseException, ('foo',),
+                {'message' : 'foo', 'args' : ('foo',)}),
+            (BaseException, ('foo', 1),
+                {'message' : '', 'args' : ('foo', 1)}),
+            (SystemExit, ('foo',),
+                {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
+            (IOError, ('foo',),
+                {'message' : 'foo', 'args' : ('foo',)}),
+            (IOError, ('foo', 'bar'),
+                {'message' : '', 'args' : ('foo', 'bar')}),
+            (IOError, ('foo', 'bar', 'baz'),
+                {'message' : '', 'args' : ('foo', 'bar')}),
+            (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
+                {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
+                 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
+                 'filename' : 'filenameStr'}),
+            (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
+                {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
+                 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
+            (SyntaxError, ('msgStr',),
+                {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
+                 'print_file_and_line' : None, 'msg' : 'msgStr',
+                 'filename' : None, 'lineno' : None, 'offset' : None}),
+            (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
+                           'textStr')),
+                {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
+                 'args' : ('msgStr', ('filenameStr', 'linenoStr',
+                                      'offsetStr', 'textStr')),
+                 'print_file_and_line' : None, 'msg' : 'msgStr',
+                 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
+            (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
+                           'textStr', 'print_file_and_lineStr'),
+                {'message' : '', 'text' : None,
+                 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
+                           'textStr', 'print_file_and_lineStr'),
+                 'print_file_and_line' : None, 'msg' : 'msgStr',
+                 'filename' : None, 'lineno' : None, 'offset' : None}),
+            (UnicodeError, (), {'message' : '', 'args' : (),}),
+            (sampleUnicodeEncodeError,
+                {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
+                                           'ordinal not in range(128)'),
+                 'encoding' : 'ascii', 'object' : u'Hello \xe1',
+                 'start' : 6, 'reason' : 'ordinal not in range(128)'}),
+            (sampleUnicodeDecodeError,
+                {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
+                                           'ordinal not in range(128)'),
+                 'encoding' : 'ascii', 'object' : '\xff',
+                 'start' : 0, 'reason' : 'ordinal not in range(128)'}),
+            (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
+                {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
+                 'object' : u'\u3042', 'reason' : 'ouch',
+                 'start' : 0, 'end' : 1}),
         ]
-try:
-    exceptionList.append(
-            ( WindowsError, (1, 'strErrorStr', 'filenameStr'),
-                    { 'message' : '', 'args' : (1, 'strErrorStr'),
-                        'strerror' : 'strErrorStr',
-                        'errno' : 22, 'filename' : 'filenameStr',
-                        'winerror' : 1 }))
-except NameError: pass
+        try:
+            exceptionList.append(
+                (WindowsError, (1, 'strErrorStr', 'filenameStr'),
+                    {'message' : '', 'args' : (1, 'strErrorStr'),
+                     'strerror' : 'strErrorStr', 'winerror' : 1,
+                     'errno' : 22, 'filename' : 'filenameStr'})
+            )
+        except NameError: pass
 
-for args in exceptionList:
-    expected = args[-1]
-    try:
-        if len(args) == 2: raise args[0]
-        else: raise apply(args[0], args[1])
-    except BaseException, e:
-        for checkArgName in expected.keys():
-            if repr(getattr(e, checkArgName)) != repr(expected[checkArgName]):
-                raise TestFailed('Checking exception arguments, exception '
-                        '"%s", attribute "%s" expected %s got %s.' %
-                        ( repr(e), checkArgName,
-                            repr(expected[checkArgName]),
-                            repr(getattr(e, checkArgName)) ))
+        import pickle, random
+
+        for args in exceptionList:
+            expected = args[-1]
+            try:
+                exc = args[0]
+                if len(args) == 2: raise exc
+                else: raise exc(*args[1])
+            except BaseException, e:
+                if (e is not exc and     # needed for sampleUnicode errors
+                    type(e) is not exc):
+                    raise
+                # Verify no ref leaks in Exc_str()
+                s = str(e)
+                for checkArgName in expected:
+                    self.assertEquals(repr(getattr(e, checkArgName)),
+                                      repr(expected[checkArgName]),
+                                      'exception "%s", attribute "%s"' %
+                                       (repr(e), checkArgName))
+
+                # test for pickling support
+                new = pickle.loads(pickle.dumps(e, random.randint(0, 2)))
+                for checkArgName in expected:
+                    self.assertEquals(repr(getattr(e, checkArgName)),
+                                      repr(expected[checkArgName]),
+                                      'pickled exception "%s", attribute "%s' %
+                                      (repr(e), checkArgName))
+
+    def testKeywordArgs(self):
+        # test that builtin exception don't take keyword args,
+        # but user-defined subclasses can if they want
+        self.assertRaises(TypeError, BaseException, a=1)
+
+        class DerivedException(BaseException):
+            def __init__(self, fancy_arg):
+                BaseException.__init__(self)
+                self.fancy_arg = fancy_arg
+
+        x = DerivedException(fancy_arg=42)
+        self.assertEquals(x.fancy_arg, 42)
+
+def test_main():
+    run_unittest(ExceptionTests)
+
+if __name__ == '__main__':
+    test_main()
diff --git a/Lib/test/test_functional.py b/Lib/test/test_functools.py
similarity index 97%
rename from Lib/test/test_functional.py
rename to Lib/test/test_functools.py
index 5078a2e..609e8f4 100644
--- a/Lib/test/test_functional.py
+++ b/Lib/test/test_functools.py
@@ -1,4 +1,4 @@
-import functional
+import functools
 import unittest
 from test import test_support
 from weakref import proxy
@@ -21,7 +21,7 @@
 
 class TestPartial(unittest.TestCase):
 
-    thetype = functional.partial
+    thetype = functools.partial
 
     def test_basic_examples(self):
         p = self.thetype(capture, 1, 2, a=10, b=20)
@@ -140,7 +140,7 @@
         join = self.thetype(''.join)
         self.assertEqual(join(data), '0123456789')
 
-class PartialSubclass(functional.partial):
+class PartialSubclass(functools.partial):
     pass
 
 class TestPartialSubclass(TestPartial):
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index c4ed3bc..b2a9b55 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -766,7 +766,7 @@
 
 >>> from operator import itemgetter
 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
->>> di = sorted(d.iteritems(), key=itemgetter(1))
+>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
 >>> for k, g in groupby(di, itemgetter(1)):
 ...     print k, map(itemgetter(0), g)
 ...
diff --git a/Lib/test/test_operations.py b/Lib/test/test_operations.py
index b599c9d..fafc062 100644
--- a/Lib/test/test_operations.py
+++ b/Lib/test/test_operations.py
@@ -5,27 +5,16 @@
 print 'XXX Mostly not yet implemented'
 
 
-print '3.1 Dictionary lookups succeed even if __cmp__() raises an exception'
-
-# SourceForge bug #112558:
-# http://sourceforge.net/bugs/?func=detailbug&bug_id=112558&group_id=5470
+print '3.1 Dictionary lookups fail if __cmp__() raises an exception'
 
 class BadDictKey:
-    already_printed_raising_error = 0
 
     def __hash__(self):
         return hash(self.__class__)
 
     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"
+            print "raising error"
             raise RuntimeError, "gotcha"
         return other
 
@@ -33,8 +22,21 @@
 x1 = BadDictKey()
 x2 = BadDictKey()
 d[x1] = 1
-d[x2] = 2
-print "No exception passed through."
+for stmt in ['d[x2] = 2',
+             'z = d[x2]',
+             'x2 in d',
+             'd.has_key(x2)',
+             'd.get(x2)',
+             'd.setdefault(x2, 42)',
+             'd.pop(x2)',
+             'd.update({x2: 2})']:
+    try:
+        exec stmt
+    except RuntimeError:
+        print "%s: caught the RuntimeError outside" % (stmt,)
+    else:
+        print "%s: No exception passed through!"     # old CPython behavior
+
 
 # Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
 # This version got an assert failure in debug build, infinite loop in
@@ -50,3 +52,27 @@
     del d[i]
 for i in range(5, 9):  # i==8 was the problem
     d[i] = i
+
+
+# Another dict resizing bug (SF bug #1456209).
+# This caused Segmentation faults or Illegal instructions.
+
+class X(object):
+    def __hash__(self):
+        return 5
+    def __eq__(self, other):
+        if resizing:
+            d.clear()
+        return False
+d = {}
+resizing = False
+d[X()] = 1
+d[X()] = 2
+d[X()] = 3
+d[X()] = 4
+d[X()] = 5
+# now trigger a resize
+resizing = True
+d[9] = 6
+
+print 'resize bugs not triggered.'
diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py
index 991c06d..79df906 100644
--- a/Lib/test/test_optparse.py
+++ b/Lib/test/test_optparse.py
@@ -230,7 +230,7 @@
 
     def test_attr_invalid(self):
         self.assertOptionError(
-            "option -b: invalid keyword arguments: foo, bar",
+            "option -b: invalid keyword arguments: bar, foo",
             ["-b"], {'foo': None, 'bar': None})
 
     def test_action_invalid(self):
@@ -718,9 +718,8 @@
     def test_ambiguous_option(self):
         self.parser.add_option("--foz", action="store",
                                type="string", dest="foo")
-        possibilities = ", ".join({"--foz": None, "--foo": None}.keys())
         self.assertParseFail(["--f=bar"],
-                             "ambiguous option: --f (%s?)" % possibilities)
+                             "ambiguous option: --f (--foo, --foz?)")
 
 
     def test_short_and_long_option_split(self):
@@ -1537,10 +1536,9 @@
     def test_match_abbrev_error(self):
         s = "--f"
         wordmap = {"--foz": None, "--foo": None, "--fie": None}
-        possibilities = ", ".join(wordmap.keys())
         self.assertRaises(
             _match_abbrev, (s, wordmap), None,
-            BadOptionError, "ambiguous option: --f (%s?)" % possibilities)
+            BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)")
 
 
 class TestParseNumber(BaseTest):
diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py
index 27d6b52..09ba268 100644
--- a/Lib/test/test_pprint.py
+++ b/Lib/test/test_pprint.py
@@ -11,16 +11,21 @@
 # list, tuple and dict subclasses that do or don't overwrite __repr__
 class list2(list):
     pass
+
 class list3(list):
     def __repr__(self):
         return list.__repr__(self)
+
 class tuple2(tuple):
     pass
+
 class tuple3(tuple):
     def __repr__(self):
         return tuple.__repr__(self)
+
 class dict2(dict):
     pass
+
 class dict3(dict):
     def __repr__(self):
         return dict.__repr__(self)
@@ -101,7 +106,13 @@
 
     def test_same_as_repr(self):
         # Simple objects, small containers and classes that overwrite __repr__
-        # For those the result should be the same as repr()
+        # For those the result should be the same as repr().
+        # Ahem.  The docs don't say anything about that -- this appears to
+        # be testing an implementation quirk.  Starting in Python 2.5, it's
+        # not true for dicts:  pprint always sorts dicts by key now; before,
+        # it sorted a dict display if and only if the display required
+        # multiple lines.  For that reason, dicts with more than one element
+        # aren't tested here.
         verify = self.assert_
         for simple in (0, 0L, 0+0j, 0.0, "", uni(""),
                        (), tuple2(), tuple3(),
@@ -112,9 +123,7 @@
                        (1,2), [3,4], {5: 6, 7: 8},
                        tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
                        [3,4], list2([3,4]), list3([3,4]), list3(range(100)),
-                       {5: 6, 7: 8}, dict2({5: 6, 7: 8}), dict3({5: 6, 7: 8}),
-                       dict3([(x,x) for x in range(100)]),
-                       {"xy\tab\n": (3,), 5: [[]], (): {}},
+                       {5: 6, 7: 8}, dict2({5: 6}), dict3({5: 6}),
                        range(10, -11, -1)
                       ):
             native = repr(simple)
@@ -160,6 +169,24 @@
         for type in [list, list2]:
             self.assertEqual(pprint.pformat(type(o), indent=4), exp)
 
+    def test_sorted_dict(self):
+        # Starting in Python 2.5, pprint sorts dict displays by key regardless
+        # of how small the dictionary may be.
+        # Before the change, on 32-bit Windows pformat() gave order
+        # 'a', 'c', 'b' here, so this test failed.
+        d = {'a': 1, 'b': 1, 'c': 1}
+        self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
+        self.assertEqual(pprint.pformat([d, d]),
+            "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
+
+        # The next one is kind of goofy.  The sorted order depends on the
+        # alphabetic order of type names:  "int" < "str" < "tuple".  Before
+        # Python 2.5, this was in the test_same_as_repr() test.  It's worth
+        # keeping around for now because it's one of few tests of pprint
+        # against a crazy mix of types.
+        self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
+            r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
+
     def test_subclassing(self):
         o = {'names with spaces': 'should be presented using repr()',
              'others.should.not.be': 'like.this'}
diff --git a/Lib/test/test_repr.py b/Lib/test/test_repr.py
index 9128585..1dfa282 100644
--- a/Lib/test/test_repr.py
+++ b/Lib/test/test_repr.py
@@ -5,6 +5,7 @@
 
 import sys
 import os
+import shutil
 import unittest
 
 from test.test_support import run_unittest
@@ -198,8 +199,10 @@
         self.pkgname = os.path.join(longname)
         self.subpkgname = os.path.join(longname, longname)
         # Make the package and subpackage
+        shutil.rmtree(self.pkgname, ignore_errors=True)
         os.mkdir(self.pkgname)
         touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
+        shutil.rmtree(self.subpkgname, ignore_errors=True)
         os.mkdir(self.subpkgname)
         touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
         # Remember where we are
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index 7981a52..af835f7 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -2,7 +2,7 @@
 import test.test_support
 import struct
 import array
-import unittest
+import warnings
 
 import sys
 ISBIGENDIAN = sys.byteorder == "big"
@@ -10,7 +10,14 @@
 verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN,
        "bigendian determination appears wrong")
 
-PY_STRUCT_RANGE_CHECKING = 1
+try:
+    import _struct
+except ImportError:
+    PY_STRUCT_RANGE_CHECKING = 0
+    PY_STRUCT_OVERFLOW_MASKING = 1
+else:
+    PY_STRUCT_RANGE_CHECKING = getattr(_struct, '_PY_STRUCT_RANGE_CHECKING', 0)
+    PY_STRUCT_OVERFLOW_MASKING = getattr(_struct, '_PY_STRUCT_OVERFLOW_MASKING', 0)
 
 def string_reverse(s):
     chars = list(s)
@@ -35,12 +42,39 @@
 def any_err(func, *args):
     try:
         func(*args)
-    except (struct.error, OverflowError, TypeError):
+    except (struct.error, TypeError):
         pass
     else:
         raise TestFailed, "%s%s did not raise error" % (
             func.__name__, args)
 
+def deprecated_err(func, *args):
+    # The `warnings` module doesn't have an advertised way to restore
+    # its filter list.  Cheat.
+    save_warnings_filters = warnings.filters[:]
+    # Grrr, we need this function to warn every time.  Without removing
+    # the warningregistry, running test_tarfile then test_struct would fail
+    # on 64-bit platforms.
+    globals = func.func_globals
+    if '__warningregistry__' in globals:
+        del globals['__warningregistry__']
+    warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning)
+    warnings.filterwarnings("error", r""".*format requires.*""",
+                            DeprecationWarning)
+    try:
+        try:
+            func(*args)
+        except (struct.error, TypeError):
+            pass
+        except DeprecationWarning:
+            if not PY_STRUCT_OVERFLOW_MASKING:
+                raise TestFailed, "%s%s expected to raise struct.error" % (
+                    func.__name__, args)
+        else:
+            raise TestFailed, "%s%s did not raise error" % (
+                func.__name__, args)
+    finally:
+        warnings.filters[:] = save_warnings_filters[:]
 
 simple_err(struct.calcsize, 'Z')
 
@@ -272,8 +306,8 @@
                 if verbose:
                     print "Skipping buggy range check for code", code
             else:
-                any_err(pack, ">" + code, x)
-                any_err(pack, "<" + code, x)
+                deprecated_err(pack, ">" + code, x)
+                deprecated_err(pack, "<" + code, x)
 
         # Much the same for unsigned.
         code = self.unsigned_code
@@ -327,8 +361,8 @@
                 if verbose:
                     print "Skipping buggy range check for code", code
             else:
-                any_err(pack, ">" + code, x)
-                any_err(pack, "<" + code, x)
+                deprecated_err(pack, ">" + code, x)
+                deprecated_err(pack, "<" + code, x)
 
     def run(self):
         from random import randrange
@@ -448,91 +482,98 @@
     for endian in ('', '>', '<'):
         for cls in (int, long):
             for fmt in ('B', 'H', 'I', 'L'):
-                any_err(struct.pack, endian + fmt, cls(-1))
+                deprecated_err(struct.pack, endian + fmt, cls(-1))
 
-            any_err(struct.pack, endian + 'B', cls(300))
-            any_err(struct.pack, endian + 'H', cls(70000))
+            deprecated_err(struct.pack, endian + 'B', cls(300))
+            deprecated_err(struct.pack, endian + 'H', cls(70000))
 
-        any_err(struct.pack, endian + 'I', sys.maxint * 4L)
-        any_err(struct.pack, endian + 'L', sys.maxint * 4L)
+        deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L)
+        deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L)
 
 if PY_STRUCT_RANGE_CHECKING:
     test_1229380()
 
-class PackBufferTestCase(unittest.TestCase):
-    """
-    Test the packing methods that work on buffers.
-    """
 
-    def test_unpack_from( self ):
-        test_string = 'abcd01234'
-        fmt = '4s'
-        s = struct.Struct(fmt)
-        for cls in (str, buffer):
-            data = cls(test_string)
-            self.assertEquals(s.unpack_from(data), ('abcd',))
-            self.assertEquals(s.unpack_from(data, 2), ('cd01',))
-            self.assertEquals(s.unpack_from(data, 4), ('0123',))
-            for i in xrange(6):
-                self.assertEquals(s.unpack_from(data, i), (data[i:i+4],))
-            for i in xrange(6, len(test_string) + 1):
-                simple_err(s.unpack_from, data, i)
-        for cls in (str, buffer):
-            data = cls(test_string)
-            self.assertEquals(struct.unpack_from(fmt, data), ('abcd',))
-            self.assertEquals(struct.unpack_from(fmt, data, 2), ('cd01',))
-            self.assertEquals(struct.unpack_from(fmt, data, 4), ('0123',))
-            for i in xrange(6):
-                self.assertEquals(struct.unpack_from(fmt, data, i),
-                                  (data[i:i+4],))
-            for i in xrange(6, len(test_string) + 1):
-                simple_err(struct.unpack_from, fmt, data, i)
+###########################################################################
+# Packing and unpacking to/from buffers.
 
-    def test_pack_to( self ):
-        test_string = 'Reykjavik rocks, eow!'
-        writable_buf = array.array('c', ' '*100)
-        fmt = '21s'
-        s = struct.Struct(fmt)
+# Copied and modified from unittest.
+def assertRaises(excClass, callableObj, *args, **kwargs):
+    try:
+        callableObj(*args, **kwargs)
+    except excClass:
+        return
+    else:
+        raise RuntimeError("%s not raised." % excClass)
 
-        # Test without offset
-        s.pack_to(writable_buf, 0, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)]
-        self.assertEquals(from_buf, test_string)
+def test_unpack_from():
+    test_string = 'abcd01234'
+    fmt = '4s'
+    s = struct.Struct(fmt)
+    for cls in (str, buffer):
+        data = cls(test_string)
+        assert s.unpack_from(data) == ('abcd',)
+        assert s.unpack_from(data, 2) == ('cd01',)
+        assert s.unpack_from(data, 4) == ('0123',)
+        for i in xrange(6):
+            assert s.unpack_from(data, i) == (data[i:i+4],)
+        for i in xrange(6, len(test_string) + 1):
+            simple_err(s.unpack_from, data, i)
+    for cls in (str, buffer):
+        data = cls(test_string)
+        assert struct.unpack_from(fmt, data) == ('abcd',)
+        assert struct.unpack_from(fmt, data, 2) == ('cd01',)
+        assert struct.unpack_from(fmt, data, 4) == ('0123',)
+        for i in xrange(6):
+            assert (struct.unpack_from(fmt, data, i) == (data[i:i+4],))
+        for i in xrange(6, len(test_string) + 1):
+            simple_err(struct.unpack_from, fmt, data, i)
 
-        # Test with offset.
-        s.pack_to(writable_buf, 10, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)+10]
-        self.assertEquals(from_buf, (test_string[:10] + test_string))
+def test_pack_to():
+    test_string = 'Reykjavik rocks, eow!'
+    writable_buf = array.array('c', ' '*100)
+    fmt = '21s'
+    s = struct.Struct(fmt)
 
-        # Go beyond boundaries.
-        small_buf = array.array('c', ' '*10)
-        self.assertRaises(struct.error, s.pack_to, small_buf, 0, test_string)
-        self.assertRaises(struct.error, s.pack_to, small_buf, 2, test_string)
+    # Test without offset
+    s.pack_to(writable_buf, 0, test_string)
+    from_buf = writable_buf.tostring()[:len(test_string)]
+    assert from_buf == test_string
 
-    def test_pack_to_fn( self ):
-        test_string = 'Reykjavik rocks, eow!'
-        writable_buf = array.array('c', ' '*100)
-        fmt = '21s'
-        pack_to = lambda *args: struct.pack_to(fmt, *args)
+    # Test with offset.
+    s.pack_to(writable_buf, 10, test_string)
+    from_buf = writable_buf.tostring()[:len(test_string)+10]
+    assert from_buf == (test_string[:10] + test_string)
 
-        # Test without offset
-        pack_to(writable_buf, 0, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)]
-        self.assertEquals(from_buf, test_string)
+    # Go beyond boundaries.
+    small_buf = array.array('c', ' '*10)
+    assertRaises(struct.error, s.pack_to, small_buf, 0, test_string)
+    assertRaises(struct.error, s.pack_to, small_buf, 2, test_string)
 
-        # Test with offset.
-        pack_to(writable_buf, 10, test_string)
-        from_buf = writable_buf.tostring()[:len(test_string)+10]
-        self.assertEquals(from_buf, (test_string[:10] + test_string))
+def test_pack_to_fn():
+    test_string = 'Reykjavik rocks, eow!'
+    writable_buf = array.array('c', ' '*100)
+    fmt = '21s'
+    pack_to = lambda *args: struct.pack_to(fmt, *args)
 
-        # Go beyond boundaries.
-        small_buf = array.array('c', ' '*10)
-        self.assertRaises(struct.error, pack_to, small_buf, 0, test_string)
-        self.assertRaises(struct.error, pack_to, small_buf, 2, test_string)
+    # Test without offset
+    pack_to(writable_buf, 0, test_string)
+    from_buf = writable_buf.tostring()[:len(test_string)]
+    assert from_buf == test_string
 
+    # Test with offset.
+    pack_to(writable_buf, 10, test_string)
+    from_buf = writable_buf.tostring()[:len(test_string)+10]
+    assert from_buf == (test_string[:10] + test_string)
 
-def test_main():
-    test.test_support.run_unittest(PackBufferTestCase)
+    # Go beyond boundaries.
+    small_buf = array.array('c', ' '*10)
+    assertRaises(struct.error, pack_to, small_buf, 0, test_string)
+    assertRaises(struct.error, pack_to, small_buf, 2, test_string)
 
-if __name__ == "__main__":
-    test_main()
+    
+# Test methods to pack and unpack from buffers rather than strings.
+test_unpack_from()
+test_pack_to()
+test_pack_to_fn()
+
diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
index c8f19bc..034b9d0 100644
--- a/Lib/test/test_urllib2.py
+++ b/Lib/test/test_urllib2.py
@@ -76,10 +76,11 @@
     >>> mgr.find_user_password("c", "http://example.com/bar")
     ('bar', 'nini')
 
-    Currently, we use the highest-level path where more than one match:
+    Actually, this is really undefined ATM
+##     Currently, we use the highest-level path where more than one match:
 
-    >>> mgr.find_user_password("Some Realm", "http://example.com/ni")
-    ('joe', 'password')
+##     >>> mgr.find_user_password("Some Realm", "http://example.com/ni")
+##     ('joe', 'password')
 
     Use latest add_password() in case of conflict:
 
@@ -110,6 +111,53 @@
     pass
 
 
+def test_password_manager_default_port(self):
+    """
+    >>> mgr = urllib2.HTTPPasswordMgr()
+    >>> add = mgr.add_password
+
+    The point to note here is that we can't guess the default port if there's
+    no scheme.  This applies to both add_password and find_user_password.
+
+    >>> add("f", "http://g.example.com:80", "10", "j")
+    >>> add("g", "http://h.example.com", "11", "k")
+    >>> add("h", "i.example.com:80", "12", "l")
+    >>> add("i", "j.example.com", "13", "m")
+    >>> mgr.find_user_password("f", "g.example.com:100")
+    (None, None)
+    >>> mgr.find_user_password("f", "g.example.com:80")
+    ('10', 'j')
+    >>> mgr.find_user_password("f", "g.example.com")
+    (None, None)
+    >>> mgr.find_user_password("f", "http://g.example.com:100")
+    (None, None)
+    >>> mgr.find_user_password("f", "http://g.example.com:80")
+    ('10', 'j')
+    >>> mgr.find_user_password("f", "http://g.example.com")
+    ('10', 'j')
+    >>> mgr.find_user_password("g", "h.example.com")
+    ('11', 'k')
+    >>> mgr.find_user_password("g", "h.example.com:80")
+    ('11', 'k')
+    >>> mgr.find_user_password("g", "http://h.example.com:80")
+    ('11', 'k')
+    >>> mgr.find_user_password("h", "i.example.com")
+    (None, None)
+    >>> mgr.find_user_password("h", "i.example.com:80")
+    ('12', 'l')
+    >>> mgr.find_user_password("h", "http://i.example.com:80")
+    ('12', 'l')
+    >>> mgr.find_user_password("i", "j.example.com")
+    ('13', 'm')
+    >>> mgr.find_user_password("i", "j.example.com:80")
+    (None, None)
+    >>> mgr.find_user_password("i", "http://j.example.com")
+    ('13', 'm')
+    >>> mgr.find_user_password("i", "http://j.example.com:80")
+    (None, None)
+
+    """
+
 class MockOpener:
     addheaders = []
     def open(self, req, data=None):
@@ -270,6 +318,27 @@
 
 class OpenerDirectorTests(unittest.TestCase):
 
+    def test_badly_named_methods(self):
+        # test work-around for three methods that accidentally follow the
+        # naming conventions for handler methods
+        # (*_open() / *_request() / *_response())
+
+        # These used to call the accidentally-named methods, causing a
+        # TypeError in real code; here, returning self from these mock
+        # methods would either cause no exception, or AttributeError.
+
+        from urllib2 import URLError
+
+        o = OpenerDirector()
+        meth_spec = [
+            [("do_open", "return self"), ("proxy_open", "return self")],
+            [("redirect_request", "return self")],
+            ]
+        handlers = add_ordered_mock_handlers(o, meth_spec)
+        o.add_handler(urllib2.UnknownHandler())
+        for scheme in "do", "proxy", "redirect":
+            self.assertRaises(URLError, o.open, scheme+"://example.com/")
+
     def test_handled(self):
         # handler returning non-None means no more handlers will be called
         o = OpenerDirector()
@@ -560,6 +629,7 @@
                 self.method = method
                 self.selector = url
                 self.req_headers += headers.items()
+                self.req_headers.sort()
                 if body:
                     self.data = body
                 if self.raise_on_endheaders:
@@ -758,6 +828,8 @@
         realm = "ACME Widget Store"
         http_handler = MockHTTPHandler(
             401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
+        opener.add_handler(auth_handler)
+        opener.add_handler(http_handler)
         self._test_basic_auth(opener, auth_handler, "Authorization",
                               realm, http_handler, password_manager,
                               "http://acme.example.com/protected",
@@ -773,6 +845,8 @@
         realm = "ACME Networks"
         http_handler = MockHTTPHandler(
             407, 'Proxy-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
+        opener.add_handler(auth_handler)
+        opener.add_handler(http_handler)
         self._test_basic_auth(opener, auth_handler, "Proxy-authorization",
                               realm, http_handler, password_manager,
                               "http://acme.example.com:3128/protected",
@@ -784,29 +858,53 @@
         # response (http://python.org/sf/1479302), where it should instead
         # return None to allow another handler (especially
         # HTTPBasicAuthHandler) to handle the response.
+
+        # Also (http://python.org/sf/14797027, RFC 2617 section 1.2), we must
+        # try digest first (since it's the strongest auth scheme), so we record
+        # order of calls here to check digest comes first:
+        class RecordingOpenerDirector(OpenerDirector):
+            def __init__(self):
+                OpenerDirector.__init__(self)
+                self.recorded = []
+            def record(self, info):
+                self.recorded.append(info)
         class TestDigestAuthHandler(urllib2.HTTPDigestAuthHandler):
-            handler_order = 400  # strictly before HTTPBasicAuthHandler
-        opener = OpenerDirector()
+            def http_error_401(self, *args, **kwds):
+                self.parent.record("digest")
+                urllib2.HTTPDigestAuthHandler.http_error_401(self,
+                                                             *args, **kwds)
+        class TestBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
+            def http_error_401(self, *args, **kwds):
+                self.parent.record("basic")
+                urllib2.HTTPBasicAuthHandler.http_error_401(self,
+                                                            *args, **kwds)
+
+        opener = RecordingOpenerDirector()
         password_manager = MockPasswordManager()
         digest_handler = TestDigestAuthHandler(password_manager)
-        basic_handler = urllib2.HTTPBasicAuthHandler(password_manager)
-        opener.add_handler(digest_handler)
+        basic_handler = TestBasicAuthHandler(password_manager)
         realm = "ACME Networks"
         http_handler = MockHTTPHandler(
             401, 'WWW-Authenticate: Basic realm="%s"\r\n\r\n' % realm)
+        opener.add_handler(basic_handler)
+        opener.add_handler(digest_handler)
+        opener.add_handler(http_handler)
+
+        # check basic auth isn't blocked by digest handler failing
         self._test_basic_auth(opener, basic_handler, "Authorization",
                               realm, http_handler, password_manager,
                               "http://acme.example.com/protected",
                               "http://acme.example.com/protected",
                               )
+        # check digest was tried before basic (twice, because
+        # _test_basic_auth called .open() twice)
+        self.assertEqual(opener.recorded, ["digest", "basic"]*2)
 
     def _test_basic_auth(self, opener, auth_handler, auth_header,
                          realm, http_handler, password_manager,
                          request_url, protected_url):
         import base64, httplib
         user, password = "wile", "coyote"
-        opener.add_handler(auth_handler)
-        opener.add_handler(http_handler)
 
         # .add_password() fed through to password manager
         auth_handler.add_password(realm, request_url, user, password)
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index 392e5fa..18ab401 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -1053,8 +1053,8 @@
 ...
 >>> obj = Dict(red=1, green=2, blue=3)   # this object is weak referencable
 >>> r = weakref.ref(obj)
->>> print r()
-{'blue': 3, 'green': 2, 'red': 1}
+>>> print r() is obj
+True
 
 >>> import weakref
 >>> class Object: