Commit ed03b412 authored by Thomas Wouters's avatar Thomas Wouters

Merge the trunk changes in. Breaks socket.ssl for now.

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

........
  r57395 | georg.brandl | 2007-08-24 19:23:23 +0200 (Fri, 24 Aug 2007) | 2 lines

  Bug #1011: fix rfc822.Message.getheader docs.
........
  r57397 | georg.brandl | 2007-08-24 19:38:49 +0200 (Fri, 24 Aug 2007) | 2 lines

  Patch #1006: port test_winreg to unittest.
........
  r57398 | georg.brandl | 2007-08-24 19:46:54 +0200 (Fri, 24 Aug 2007) | 2 lines

  Fix #1012: wrong URL to :mod:`site` in install/index.rst.
........
  r57399 | georg.brandl | 2007-08-24 20:07:52 +0200 (Fri, 24 Aug 2007) | 2 lines

  Patch #1008: port test_signal to unittest.
........
  r57400 | georg.brandl | 2007-08-24 20:22:54 +0200 (Fri, 24 Aug 2007) | 2 lines

  Port test_frozen to unittest.
........
  r57401 | georg.brandl | 2007-08-24 20:27:43 +0200 (Fri, 24 Aug 2007) | 2 lines

  Document new utility functions in test_support.
........
  r57402 | georg.brandl | 2007-08-24 20:30:06 +0200 (Fri, 24 Aug 2007) | 2 lines

  Remove test_rgbimg output file, there is no test_rgbimg.py.
........
  r57403 | georg.brandl | 2007-08-24 20:35:27 +0200 (Fri, 24 Aug 2007) | 2 lines

  Remove output file for test_ossaudiodev, also properly close the dsp object.
........
  r57404 | georg.brandl | 2007-08-24 20:46:27 +0200 (Fri, 24 Aug 2007) | 2 lines

  Convert test_linuxaudiodev to unittest. Fix a wrong finally clause in test_ossaudiodev.
........
  r57406 | collin.winter | 2007-08-24 21:13:58 +0200 (Fri, 24 Aug 2007) | 1 line

  Convert test_pkg to use unittest.
........
  r57408 | georg.brandl | 2007-08-24 21:22:34 +0200 (Fri, 24 Aug 2007) | 2 lines

  Catch the correct errors.
........
  r57409 | georg.brandl | 2007-08-24 21:33:53 +0200 (Fri, 24 Aug 2007) | 2 lines

  Port test_class to unittest. Patch #1671298.
........
  r57415 | collin.winter | 2007-08-24 23:09:42 +0200 (Fri, 24 Aug 2007) | 1 line

  Make test_structmembers pass when run with regrtests's -R flag.
........
  r57455 | nick.coghlan | 2007-08-25 06:32:07 +0200 (Sat, 25 Aug 2007) | 1 line

  Revert misguided attempt at fixing incompatibility between -m and -i switches (better fix coming soon)
........
  r57456 | nick.coghlan | 2007-08-25 06:35:54 +0200 (Sat, 25 Aug 2007) | 1 line

  Revert compile.c changes that shouldn't have been included in previous checkin
........
  r57461 | nick.coghlan | 2007-08-25 12:50:41 +0200 (Sat, 25 Aug 2007) | 1 line

  Fix bug 1764407 - the -i switch now does the right thing when using the -m switch
........
  r57464 | guido.van.rossum | 2007-08-25 17:08:43 +0200 (Sat, 25 Aug 2007) | 4 lines

  Server-side SSL and certificate validation, by Bill Janssen.
  While cleaning up Bill's C style, I may have cleaned up some code
  he didn't touch as well (in _ssl.c).
........
  r57465 | neal.norwitz | 2007-08-25 18:41:36 +0200 (Sat, 25 Aug 2007) | 3 lines

  Try to get this to build with Visual Studio by moving all the variable
  declarations to the beginning of a scope.
........
  r57466 | neal.norwitz | 2007-08-25 18:54:38 +0200 (Sat, 25 Aug 2007) | 1 line

  Fix test so it is skipped properly if there is no SSL support.
........
  r57467 | neal.norwitz | 2007-08-25 18:58:09 +0200 (Sat, 25 Aug 2007) | 2 lines

  Fix a few more variables to try to get this to compile with Visual Studio.
........
  r57473 | neal.norwitz | 2007-08-25 19:25:17 +0200 (Sat, 25 Aug 2007) | 1 line

  Try to get this test to pass for systems that do not have SO_REUSEPORT
........
  r57482 | gregory.p.smith | 2007-08-26 02:26:00 +0200 (Sun, 26 Aug 2007) | 7 lines

  keep setup.py from listing unneeded hash modules (_md5, _sha*) as
  missing when they were not built because _hashlib with openssl provided
  their functionality instead.

  don't build bsddb185 if bsddb was built.
........
  r57483 | neal.norwitz | 2007-08-26 03:08:16 +0200 (Sun, 26 Aug 2007) | 1 line

  Fix typo in docstring (missing c in reacquire)
........
  r57484 | neal.norwitz | 2007-08-26 03:42:03 +0200 (Sun, 26 Aug 2007) | 2 lines

  Spell check (also americanify behaviour, it's almost 3 times as common)
........
  r57503 | neal.norwitz | 2007-08-26 08:29:57 +0200 (Sun, 26 Aug 2007) | 4 lines

  Reap children before the test starts so hopefully SocketServer
  won't find any old children left around which causes an exception
  in collect_children() and the test to fail.
........
  r57510 | neal.norwitz | 2007-08-26 20:50:39 +0200 (Sun, 26 Aug 2007) | 1 line

  Fail gracefully if the cert files cannot be created
........
  r57513 | guido.van.rossum | 2007-08-26 21:35:09 +0200 (Sun, 26 Aug 2007) | 4 lines

  Bill Janssen wrote:
  Here's a patch which makes test_ssl a better player in the buildbots
  environment.  I deep-ended on "try-except-else" clauses.
........
  r57518 | neal.norwitz | 2007-08-26 23:40:16 +0200 (Sun, 26 Aug 2007) | 1 line

  Get the test passing by commenting out some writes (should they be removed?)
........
  r57522 | neal.norwitz | 2007-08-27 00:16:23 +0200 (Mon, 27 Aug 2007) | 3 lines

  Catch IOError for when the device file doesn't exist or the user doesn't have
  permission to write to the device.
........
  r57524 | neal.norwitz | 2007-08-27 00:20:03 +0200 (Mon, 27 Aug 2007) | 5 lines

  Another patch from Bill Janssen that:
  1)  Fixes the bug that two class names are initial-lower-case.
  2)  Replaces the poll waiting for the server to become ready with
      a threading.Event signal.
........
  r57536 | neal.norwitz | 2007-08-27 02:58:33 +0200 (Mon, 27 Aug 2007) | 1 line

  Stop using string.join (from the module) to ease upgrade to py3k
........
  r57537 | neal.norwitz | 2007-08-27 03:03:18 +0200 (Mon, 27 Aug 2007) | 1 line

  Make a utility function for handling (printing) an error
........
  r57538 | neal.norwitz | 2007-08-27 03:15:33 +0200 (Mon, 27 Aug 2007) | 4 lines

  If we can't create a certificate, print a warning, but don't fail the test.
  Modified patch from what Bill Janssen sent on python-3000.
........
  r57539 | facundo.batista | 2007-08-27 03:15:34 +0200 (Mon, 27 Aug 2007) | 7 lines


  Ignore test failures caused by 'resource temporarily unavailable'
  exceptions raised in the test server thread, since SimpleXMLRPCServer
  does not gracefully handle them.  Changed number of requests handled
  by tests server thread to one (was 2) because no tests require more
  than one request. [GSoC - Alan McIntyre]
........
  r57561 | guido.van.rossum | 2007-08-27 19:19:42 +0200 (Mon, 27 Aug 2007) | 8 lines

  > Regardless, building a fixed test certificate and checking it in sounds like
  > the better option.  Then the openssl command in the test code can be turned
  > into a comment describing how the test data was pregenerated.

  Here's a patch that does that.

  Bill
........
  r57568 | guido.van.rossum | 2007-08-27 20:42:23 +0200 (Mon, 27 Aug 2007) | 26 lines

  > Some of the code sets the error string in this directly before
  > returning NULL, and other pieces of the code call PySSL_SetError,
  > which creates the error string.  I think some of the places which set
  > the string directly probably shouldn't; instead, they should call
  > PySSL_SetError to cons up the error name directly from the err code.
  > However, PySSL_SetError only works after the construction of an ssl
  > object, which means it can't be used there...  I'll take a longer look
  > at it and see if there's a reasonable fix.

  Here's a patch which addresses this.  It also fixes the indentation in
  PySSL_SetError, bringing it into line with PEP 7, fixes a compile warning
  about one of the OpenSSL macros, and makes the namespace a bit more
  consistent.  I've tested it on FC 7 and OS X 10.4.

  % ./python ./Lib/test/regrtest.py -R :1: -u all test_ssl
  test_ssl
  beginning 6 repetitions
  123456
  ......
  1 test OK.
  [29244 refs]
  %

  [GvR: slightly edited to enforce 79-char line length, even if it required
   violating the style guide.]
........
  r57570 | guido.van.rossum | 2007-08-27 21:11:11 +0200 (Mon, 27 Aug 2007) | 2 lines

  Patch 10124 by Bill Janssen, docs for the new ssl code.
........
  r57574 | guido.van.rossum | 2007-08-27 22:51:00 +0200 (Mon, 27 Aug 2007) | 3 lines

  Patch # 1739906 by Christian Heimes -- add reduce to functools (importing
  it from __builtin__).
........
  r57575 | guido.van.rossum | 2007-08-27 22:52:10 +0200 (Mon, 27 Aug 2007) | 2 lines

  News about functools.reduce.
........
  r57611 | georg.brandl | 2007-08-28 10:29:08 +0200 (Tue, 28 Aug 2007) | 2 lines

  Document rev. 57574.
........
  r57612 | sean.reifschneider | 2007-08-28 11:07:54 +0200 (Tue, 28 Aug 2007) | 2 lines

  Adding basic imputil documentation.
........
  r57614 | georg.brandl | 2007-08-28 12:48:18 +0200 (Tue, 28 Aug 2007) | 2 lines

  Fix some glitches.
........
  r57616 | lars.gustaebel | 2007-08-28 14:31:09 +0200 (Tue, 28 Aug 2007) | 5 lines

  TarFile.__init__() no longer fails if no name argument is passed and
  the fileobj argument has no usable name attribute (e.g. StringIO).

  (will backport to 2.5)
........
  r57619 | thomas.wouters | 2007-08-28 17:28:19 +0200 (Tue, 28 Aug 2007) | 22 lines


  Improve extended slicing support in builtin types and classes. Specifically:

   - Specialcase extended slices that amount to a shallow copy the same way as
     is done for simple slices, in the tuple, string and unicode case.

   - Specialcase step-1 extended slices to optimize the common case for all
     involved types.

   - For lists, allow extended slice assignment of differing lengths as long
     as the step is 1. (Previously, 'l[:2:1] = []' failed even though
     'l[:2] = []' and 'l[:2:None] = []' do not.)

   - Implement extended slicing for buffer, array, structseq, mmap and
     UserString.UserString.

   - Implement slice-object support (but not non-step-1 slice assignment) for
     UserString.MutableString.

   - Add tests for all new functionality.
........
parent 9e7c8da6
......@@ -604,8 +604,6 @@ value of ``sys.path``. ::
The null string in ``sys.path`` represents the current working directory.
.. % $ <-- bow to font-lock
The expected convention for locally installed packages is to put them in the
:file:`{...}/site-packages/` directory, but you may want to install Python
modules into some arbitrary directory. For example, your site may have a
......@@ -624,9 +622,8 @@ installing fixed versions of standard modules.)
Paths can be absolute or relative, in which case they're relative to the
directory containing the :file:`.pth` file. Any directories added to the search
path will be scanned in turn for :file:`.pth` files. See `site module
documentation <http://www.python.org/dev/doc/devel/lib/module-site.html>`_ for
more information.
path will be scanned in turn for :file:`.pth` files. See the documentation of
the :mod:`site` module for more information.
A slightly less convenient way is to edit the :file:`site.py` file in Python's
standard library, and modify ``sys.path``. :file:`site.py` is automatically
......
......@@ -109,7 +109,7 @@ UNICODE is defined or not::
*windll* does not try to select one of them by magic, you must access the
version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
explicitely, and then call it with normal strings or unicode strings
explicitly, and then call it with normal strings or unicode strings
respectively.
Sometimes, dlls export functions with names which aren't valid Python
......@@ -383,7 +383,7 @@ course, it must be one of integer, string, or unicode::
If you don't want to store the instance's data in the :attr:`_as_parameter_`
instance variable, you could define a ``property`` which makes the data
avaiblable.
available.
.. _ctypes-specifying-required-argument-types:
......@@ -600,7 +600,7 @@ Structure/union alignment and byte order
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, Structure and Union fields are aligned in the same way the C
compiler does it. It is possible to override this behaviour be specifying a
compiler does it. It is possible to override this behavior be specifying a
:attr:`_pack_` class attribute in the subclass definition. This must be set to a
positive integer and specifies the maximum alignment for the fields. This is
what ``#pragma pack(n)`` also does in MSVC.
......@@ -643,7 +643,7 @@ positive integer::
TenPointsArrayType = POINT * 10
Here is an example of an somewhat artifical data type, a structure containing 4
Here is an example of an somewhat artificial data type, a structure containing 4
POINTs among other stuff::
>>> from ctypes import *
......@@ -1134,7 +1134,7 @@ hit the NULL entry::
>>>
The fact that standard Python has a frozen module and a frozen package
(indicated by the negative size member) is not wellknown, it is only used for
(indicated by the negative size member) is not well known, it is only used for
testing. Try it out with ``import __hello__`` for example.
......@@ -1167,7 +1167,7 @@ Consider the following example::
>>>
Hm. We certainly expected the last statement to print ``3 4 1 2``. What
happended? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::
>>> temp0, temp1 = rc.b, rc.a
>>> rc.a = temp0
......@@ -1180,8 +1180,8 @@ contents of ``temp0`` into ``rc`` 's buffer. This, in turn, changes the
contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
the expected effect.
Keep in mind that retrieving subobjects from Structure, Unions, and Arrays
doesn't *copy* the subobject, instead it retrieves a wrapper object accessing
Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
the root-object's underlying buffer.
Another example that may behave different from what one would expect is this::
......@@ -1292,11 +1292,11 @@ library to load.
is the form used for the posix linker option :option:`-l`). If no library can
be found, returns ``None``.
The exact functionality is system dependend.
The exact functionality is system dependent.
On Linux, ``find_library`` tries to run external programs (/sbin/ldconfig, gcc,
and objdump) to find the library file. It returns the filename of the library
file. Here are sone examples::
file. Here are some examples::
>>> from ctypes.util import find_library
>>> find_library("m")
......@@ -1308,7 +1308,7 @@ file. Here are sone examples::
>>>
On OS X, ``find_library`` tries several predefined naming schemes and paths to
locate the library, and returns a full pathname if successfull::
locate the library, and returns a full pathname if successful::
>>> from ctypes.util import find_library
>>> find_library("c")
......@@ -1367,7 +1367,7 @@ way is to instantiate one of the following classes:
platform.
The Python GIL is released before calling any function exported by these
libraries, and reaquired afterwards.
libraries, and reacquired afterwards.
.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)
......@@ -1411,7 +1411,7 @@ details, consult the ``dlopen(3)`` manpage, on Windows, *mode* is ignored.
*RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.
Instances of these classes have no public methods, however :meth:`__getattr__`
and :meth:`__getitem__` have special behaviour: functions exported by the shared
and :meth:`__getitem__` have special behavior: functions exported by the shared
library can be accessed as attributes of by index. Please note that both
:meth:`__getattr__` and :meth:`__getitem__` cache their result, so calling them
repeatedly returns the same object each time.
......@@ -1427,7 +1427,7 @@ underscore to not clash with exported function names:
.. attribute:: PyDLL._name
The name of the library passed in the contructor.
The name of the library passed in the constructor.
Shared libraries can also be loaded by using one of the prefabricated objects,
which are instances of the :class:`LibraryLoader` class, either by calling the
......@@ -1440,7 +1440,7 @@ loader instance.
Class which loads shared libraries. ``dlltype`` should be one of the
:class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.
:meth:`__getattr__` has special behaviour: It allows to load a shared library by
:meth:`__getattr__` has special behavior: It allows to load a shared library by
accessing it as attribute of a library loader instance. The result is cached,
so repeated attribute accesses return the same library each time.
......@@ -1508,7 +1508,7 @@ They are instances of a private class:
Instances of foreign functions are also C compatible data types; they represent
C function pointers.
This behaviour can be customized by assigning to special attributes of the
This behavior can be customized by assigning to special attributes of the
foreign function object.
......@@ -1520,7 +1520,7 @@ foreign function object.
It is possible to assign a callable Python object that is not a ctypes type, in
this case the function is assumed to return a C ``int``, and the callable will
be called with this integer, allowing to do further processing or error
checking. Using this is deprecated, for more flexible postprocessing or error
checking. Using this is deprecated, for more flexible post processing or error
checking use a ctypes data type as :attr:`restype` and assign a callable to the
:attr:`errcheck` attribute.
......@@ -1558,10 +1558,10 @@ foreign function object.
:attr:`restype` attribute.
``func`` is the foreign function object itself, this allows to reuse the same
callable object to check or postprocess the results of several functions.
callable object to check or post process the results of several functions.
``arguments`` is a tuple containing the parameters originally passed to the
function call, this allows to specialize the behaviour on the arguments used.
function call, this allows to specialize the behavior on the arguments used.
The object that this function returns will be returned from the foreign function
call, but it can also check the result value and raise an exception if the
......@@ -1634,7 +1634,7 @@ different ways, depending on the type and number of the parameters in the call.
:noindex:
Returns a foreign function that will call a COM method. ``vtbl_index`` is the
index into the virtual function table, a small nonnegative integer. *name* is
index into the virtual function table, a small non-negative integer. *name* is
name of the COM method. *iid* is an optional pointer to the interface identifier
which is used in extended error reporting.
......@@ -1827,14 +1827,14 @@ Utility functions
.. function:: DllCanUnloadNow()
Windows only: This function is a hook which allows to implement inprocess COM
Windows only: This function is a hook which allows to implement in-process COM
servers with ctypes. It is called from the DllCanUnloadNow function that the
_ctypes extension dll exports.
.. function:: DllGetClassObject()
Windows only: This function is a hook which allows to implement inprocess COM
Windows only: This function is a hook which allows to implement in-process COM
servers with ctypes. It is called from the DllGetClassObject function that the
``_ctypes`` extension dll exports.
......@@ -1920,7 +1920,7 @@ Utility functions
Windows only: this function is probably the worst-named thing in ctypes. It
creates an instance of WindowsError. If *code* is not specified,
``GetLastError`` is called to determine the error code. If ``descr`` is not
spcified, :func:`FormatError` is called to get a textual description of the
specified, :func:`FormatError` is called to get a textual description of the
error.
......@@ -1982,13 +1982,13 @@ Common instance variables of ctypes data types:
Sometimes ctypes data instances do not own the memory block they contain,
instead they share part of the memory block of a base object. The
:attr:`_b_base_` readonly member is the root ctypes object that owns the memory
:attr:`_b_base_` read-only member is the root ctypes object that owns the memory
block.
.. attribute:: _CData._b_needsfree_
This readonly variable is true when the ctypes data instance has allocated the
This read-only variable is true when the ctypes data instance has allocated the
memory block itself, false otherwise.
......@@ -2033,7 +2033,7 @@ converted to native Python types. In other words, if a foreign function has a
:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
*not* a :class:`c_char_p` instance.
Subclasses of fundamental data types do *not* inherit this behaviour. So, if a
Subclasses of fundamental data types do *not* inherit this behavior. So, if a
foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
receive an instance of this subclass from the function call. Of course, you can
get the value of the pointer by accessing the ``value`` attribute.
......
......@@ -15,7 +15,15 @@ The :mod:`functools` module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.
The :mod:`functools` module defines the following function:
The :mod:`functools` module defines the following functions:
.. function:: reduce(function, iterable[, initializer])
This is the same function as :func:`reduce`. It is made available in this module
to allow writing code more forward-compatible with Python 3.
.. versionadded:: 2.6
.. function:: partial(func[,*args][, **keywords])
......
:mod:`imputil` --- Import utilities
=====================================================
.. module:: imputil
:synopsis: Manage and augment the import process.
.. index:: statement: import
This module provides a very handy and useful mechanism for custom
:keyword:`import` hooks. Compared to the older :mod:`ihooks` module,
:mod:`imputil` takes a dramatically simpler and more straight-forward
approach to custom :keyword:`import` functions.
.. class:: ImportManager([fs_imp])
Manage the import process.
.. method:: ImportManager.install([namespace])
Install this ImportManager into the specified namespace.
.. method:: ImportManager.uninstall()
Restore the previous import mechanism.
.. method:: ImportManager.add_suffix(suffix, importFunc)
Undocumented.
.. class:: Importer()
Base class for replacing standard import functions.
.. method:: Importer.import_top(name)
Import a top-level module.
.. method:: Importer.get_code(parent, modname, fqname)
Find and retrieve the code for the given module.
*parent* specifies a parent module to define a context for importing.
It may be ``None``, indicating no particular context for the search.
*modname* specifies a single module (not dotted) within the parent.
*fqname* specifies the fully-qualified module name. This is a
(potentially) dotted name from the "root" of the module namespace
down to the modname.
If there is no parent, then modname==fqname.
This method should return ``None``, or a 3-tuple.
* If the module was not found, then ``None`` should be returned.
* The first item of the 2- or 3-tuple should be the integer 0 or 1,
specifying whether the module that was found is a package or not.
* The second item is the code object for the module (it will be
executed within the new module's namespace). This item can also
be a fully-loaded module object (e.g. loaded from a shared lib).
* The third item is a dictionary of name/value pairs that will be
inserted into new module before the code object is executed. This
is provided in case the module's code expects certain values (such
as where the module was found). When the second item is a module
object, then these names/values will be inserted *after* the module
has been loaded/initialized.
.. class:: BuiltinImporter()
Emulate the import mechanism for builtin and frozen modules. This is a
sub-class of the :class:`Importer` class.
.. method:: BuiltinImporter.get_code(parent, modname, fqname)
Undocumented.
.. function:: py_suffix_importer(filename, finfo, fqname)
Undocumented.
.. class:: DynLoadSuffixImporter([desc])
Undocumented.
.. method:: DynLoadSuffixImporter.import_file(filename, finfo, fqname)
Undocumented.
.. _examples-imputil:
Examples
--------
This is a re-implementation of hierarchical module import.
This code is intended to be read, not executed. However, it does work
-- all you need to do to enable it is "import knee".
(The name is a pun on the klunkier predecessor of this module, "ni".)
::
import sys, imp, __builtin__
# Replacement for __import__()
def import_hook(name, globals=None, locals=None, fromlist=None):
parent = determine_parent(globals)
q, tail = find_head_package(parent, name)
m = load_tail(q, tail)
if not fromlist:
return q
if hasattr(m, "__path__"):
ensure_fromlist(m, fromlist)
return m
def determine_parent(globals):
if not globals or not globals.has_key("__name__"):
return None
pname = globals['__name__']
if globals.has_key("__path__"):
parent = sys.modules[pname]
assert globals is parent.__dict__
return parent
if '.' in pname:
i = pname.rfind('.')
pname = pname[:i]
parent = sys.modules[pname]
assert parent.__name__ == pname
return parent
return None
def find_head_package(parent, name):
if '.' in name:
i = name.find('.')
head = name[:i]
tail = name[i+1:]
else:
head = name
tail = ""
if parent:
qname = "%s.%s" % (parent.__name__, head)
else:
qname = head
q = import_module(head, qname, parent)
if q: return q, tail
if parent:
qname = head
parent = None
q = import_module(head, qname, parent)
if q: return q, tail
raise ImportError, "No module named " + qname
def load_tail(q, tail):
m = q
while tail:
i = tail.find('.')
if i < 0: i = len(tail)
head, tail = tail[:i], tail[i+1:]
mname = "%s.%s" % (m.__name__, head)
m = import_module(head, mname, m)
if not m:
raise ImportError, "No module named " + mname
return m
def ensure_fromlist(m, fromlist, recursive=0):
for sub in fromlist:
if sub == "*":
if not recursive:
try:
all = m.__all__
except AttributeError:
pass
else:
ensure_fromlist(m, all, 1)
continue
if sub != "*" and not hasattr(m, sub):
subname = "%s.%s" % (m.__name__, sub)
submod = import_module(sub, subname, m)
if not submod:
raise ImportError, "No module named " + subname
def import_module(partname, fqname, parent):
try:
return sys.modules[fqname]
except KeyError:
pass
try:
fp, pathname, stuff = imp.find_module(partname,
parent and parent.__path__)
except ImportError:
return None
try:
m = imp.load_module(fqname, fp, pathname, stuff)
finally:
if fp: fp.close()
if parent:
setattr(parent, partname, m)
return m
# Replacement for reload()
def reload_hook(module):
name = module.__name__
if '.' not in name:
return import_module(name, name, None)
i = name.rfind('.')
pname = name[:i]
parent = sys.modules[pname]
return import_module(name[i+1:], name, parent)
# Save the original hooks
original_import = __builtin__.__import__
original_reload = __builtin__.reload
# Now install our hooks
__builtin__.__import__ = import_hook
__builtin__.reload = reload_hook
.. index::
module: knee
Also see the :mod:`importers` module (which can be found
in :file:`Demo/imputil/` in the Python source distribution) for additional
examples.
......@@ -19,6 +19,7 @@ The list of modules described in this chapter is:
subprocess.rst
socket.rst
ssl.rst
signal.rst
asyncore.rst
asynchat.rst
......@@ -14,6 +14,7 @@ The full list of modules described in this chapter is:
.. toctree::
imp.rst
imputil.rst
zipimport.rst
pkgutil.rst
modulefinder.rst
......
......@@ -198,10 +198,12 @@ A :class:`Message` instance has the following methods:
.. method:: Message.getheader(name[, default])
Like ``getrawheader(name)``, but strip leading and trailing whitespace.
Return a single string consisting of the last header matching *name*,
but strip leading and trailing whitespace.
Internal whitespace is not stripped. The optional *default* argument can be
used to specify a different default to be returned when there is no header
matching *name*.
matching *name*; it defaults to ``None``.
This is the preferred way to get parsed headers.
.. method:: Message.get(name[, default])
......
......@@ -52,11 +52,9 @@ The :mod:`runpy` module provides a single function:
If the argument *alter_sys* is supplied and evaluates to ``True``, then
``sys.argv[0]`` is updated with the value of ``__file__`` and
``sys.modules[__name__]`` is updated with a new module object for the module
being executed. Note that neither ``sys.argv[0]`` nor ``sys.modules[__name__]``
are restored to their original values before the function returns -- if client
code needs these values preserved, it must either save them explicitly or
else avoid enabling the automatic alterations to :mod:`sys`.
``sys.modules[__name__]`` is updated with a temporary module object for the
module being executed. Both ``sys.argv[0]`` and ``sys.modules[__name__]``
are restored to their original values before the function returns.
Note that this manipulation of :mod:`sys` is not thread-safe. Other threads may
see the partially initialised module, as well as the altered list of arguments.
......
......@@ -300,17 +300,6 @@ The module :mod:`socket` exports the following constants and functions:
omitted in that case.
.. function:: ssl(sock[, keyfile, certfile])
Initiate a SSL connection over the socket *sock*. *keyfile* is the name of a PEM
formatted file that contains your private key. *certfile* is a PEM formatted
certificate chain file. On success, a new :class:`SSLObject` is returned.
.. warning::
This does not do any certificate verification!
.. function:: socketpair([family[, type[, proto]]])
Build a pair of connected socket objects using the given address family, socket
......@@ -752,40 +741,6 @@ values given to the :class:`socket` constructor.
.. versionadded:: 2.5
.. _ssl-objects:
SSL Objects
-----------
SSL objects have the following methods.
.. method:: SSL.write(s)
Writes the string *s* to the on the object's SSL connection. The return value is
the number of bytes written.
.. method:: SSL.read([n])
If *n* is provided, read *n* bytes from the SSL connection, otherwise read until
EOF. The return value is a string of the bytes read.
.. method:: SSL.server()
Returns a string describing the server's certificate. Useful for debugging
purposes; do not parse the content of this string because its format can't be
parsed unambiguously.
.. method:: SSL.issuer()
Returns a string describing the issuer of the server's certificate. Useful for
debugging purposes; do not parse the content of this string because its format
can't be parsed unambiguously.
.. _socket-example:
Example
......@@ -903,39 +858,3 @@ sends traffic to the first one connected successfully. ::
s.close()
print 'Received', repr(data)
This example connects to an SSL server, prints the server and issuer's
distinguished names, sends some bytes, and reads part of the response::
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.verisign.com', 443))
ssl_sock = socket.ssl(s)
print repr(ssl_sock.server())
print repr(ssl_sock.issuer())
# Set a simple HTTP request -- use httplib in actual code.
ssl_sock.write("""GET / HTTP/1.0\r
Host: www.verisign.com\r\n\r\n""")
# Read a chunk of data. Will not necessarily
# read all the data returned by the server.
data = ssl_sock.read()
# Note that you need to close the underlying socket, not the SSL object.
del ssl_sock
s.close()
At this writing, this SSL example prints the following output (line breaks
inserted for readability)::
'/C=US/ST=California/L=Mountain View/
O=VeriSign, Inc./OU=Production Services/
OU=Terms of use at www.verisign.com/rpa (c)00/
CN=www.verisign.com'
'/O=VeriSign Trust Network/OU=VeriSign, Inc./
OU=VeriSign International Server CA - Class 3/
OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign'
This diff is collapsed.
......@@ -284,8 +284,38 @@ The :mod:`test.test_support` module defines the following functions:
This will run all tests defined in the named module.
The :mod:`test.test_support` module defines the following classes:
.. function:: catch_warning()
This is a context manager that guards the warnings filter from being
permanently changed and records the data of the last warning that has been
issued.
Use like this::
with catch_warning() as w:
warnings.warn("foo")
assert str(w.message) == "foo"
.. versionadded:: 2.6
.. function:: captured_stdout()
This is a context manager than runs the :keyword:`with` statement body using
a :class:`StringIO.StringIO` object as sys.stdout. That object can be
retrieved using the ``as`` clause of the with statement.
Example use::
with captured_stdout() as s:
print "hello"
assert s.getvalue() == "hello"
.. versionadded:: 2.6
The :mod:`test.test_support` module defines the following classes:
.. class:: TransientResource(exc[, **kwargs])
......@@ -314,4 +344,3 @@ The :mod:`test.test_support` module defines the following classes:
.. method:: EnvironmentVarGuard.unset(envvar)
Temporarily unset the environment variable ``envvar``.
......@@ -69,7 +69,7 @@ The :mod:`urllib2` module defines the following functions:
:class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
:class:`HTTPErrorProcessor`.
If the Python installation has SSL support (:func:`socket.ssl` exists),
If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
:class:`HTTPSHandler` will also be added.
Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
......
......@@ -185,15 +185,41 @@ class MutableString(UserString):
def __hash__(self):
raise TypeError, "unhashable type (it is mutable)"
def __setitem__(self, index, sub):
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + sub + self.data[index+1:]
if isinstance(index, slice):
if isinstance(sub, UserString):
sub = sub.data
elif not isinstance(sub, basestring):
sub = str(sub)
start, stop, step = index.indices(len(self.data))
if step == -1:
start, stop = stop+1, start+1
sub = sub[::-1]
elif step != 1:
# XXX(twouters): I guess we should be reimplementing
# the extended slice assignment/deletion algorithm here...
raise TypeError, "invalid step in slicing assignment"
start = min(start, stop)
self.data = self.data[:start] + sub + self.data[stop:]
else:
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + sub + self.data[index+1:]
def __delitem__(self, index):
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + self.data[index+1:]
if isinstance(index, slice):
start, stop, step = index.indices(len(self.data))
if step == -1:
start, stop = stop+1, start+1
elif step != 1:
# XXX(twouters): see same block in __setitem__
raise TypeError, "invalid step in slicing deletion"
start = min(start, stop)
self.data = self.data[:start] + self.data[stop:]
else:
if index < 0:
index += len(self.data)
if index < 0 or index >= len(self.data): raise IndexError
self.data = self.data[:index] + self.data[index+1:]
def __setslice__(self, start, end, sub):
start = max(start, 0); end = max(end, 0)
if isinstance(sub, UserString):
......
......@@ -336,7 +336,7 @@ class CDLL(object):
<obj>['qsort'] -> callable object
Calling the functions releases the Python GIL during the call and
reaquires it afterwards.
reacquires it afterwards.
"""
class _FuncPtr(_CFuncPtr):
_flags_ = _FUNCFLAG_CDECL
......
......@@ -21,8 +21,9 @@ __all__ = [
]
def _run_code(code, run_globals, init_globals,
mod_name, mod_fname, mod_loader):
def _run_code(code, run_globals, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None):
"""Helper for _run_module_code"""
if init_globals is not None:
run_globals.update(init_globals)
......@@ -33,21 +34,31 @@ def _run_code(code, run_globals, init_globals,
return run_globals
def _run_module_code(code, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, alter_sys=False):
mod_name=None, mod_fname=None,
mod_loader=None):
"""Helper for run_module"""
# Set up the top level namespace dictionary
if alter_sys:
# Modify sys.argv[0] and sys.modules[mod_name]
sys.argv[0] = mod_fname
module = imp.new_module(mod_name)
sys.modules[mod_name] = module
mod_globals = module.__dict__
else:
# Leave the sys module alone
mod_globals = {}
return _run_code(code, mod_globals, init_globals,
mod_name, mod_fname, mod_loader)
temp_module = imp.new_module(mod_name)
mod_globals = temp_module.__dict__
# Modify sys.argv[0] and sys.module[mod_name]
saved_argv0 = sys.argv[0]
restore_module = mod_name in sys.modules
if restore_module:
saved_module = sys.modules[mod_name]
sys.argv[0] = mod_fname
sys.modules[mod_name] = temp_module
try:
_run_code(code, mod_globals, init_globals,
mod_name, mod_fname, mod_loader)
finally:
sys.argv[0] = saved_argv0
if restore_module:
sys.modules[mod_name] = saved_module
else:
del sys.modules[mod_name]
# Copy the globals of the temporary module, as they
# may be cleared when the temporary module goes away
return mod_globals.copy()
# This helper is needed due to a missing component in the PEP 302
......@@ -60,13 +71,8 @@ def _get_filename(loader, mod_name):
else:
return get_filename(mod_name)
def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
# Helper to get the loader, code and filename for a module
def _get_module_details(mod_name):
loader = get_loader(mod_name)
if loader is None:
raise ImportError("No module named %s" % mod_name)
......@@ -77,10 +83,40 @@ def run_module(mod_name, init_globals=None,
if code is None:
raise ImportError("No code object available for %s" % mod_name)
filename = _get_filename(loader, mod_name)
return loader, code, filename
# XXX ncoghlan: Should this be documented and made public?
def _run_module_as_main(mod_name, set_argv0=True):
"""Runs the designated module in the __main__ namespace
These __*__ magic variables will be overwritten:
__file__
__loader__
"""
loader, code, fname = _get_module_details(mod_name)
main_globals = sys.modules["__main__"].__dict__
if set_argv0:
sys.argv[0] = fname
return _run_code(code, main_globals, None,
"__main__", fname, loader)
def run_module(mod_name, init_globals=None,
run_name=None, alter_sys=False):
"""Execute a module's code without importing it
Returns the resulting top level namespace dictionary
"""
loader, code, fname = _get_module_details(mod_name)
if run_name is None:
run_name = mod_name
return _run_module_code(code, init_globals, run_name,
filename, loader, alter_sys)
if alter_sys:
return _run_module_code(code, init_globals, run_name,
fname, loader)
else:
# Leave the sys module alone
return _run_code(code, {}, init_globals,
run_name, fname, loader)
if __name__ == "__main__":
......@@ -89,4 +125,4 @@ if __name__ == "__main__":
print("No module specified for execution", file=sys.stderr)
else:
del sys.argv[0] # Make the requested module sys.argv[0]
run_module(sys.argv[0], run_name="__main__", alter_sys=True)
_run_module_as_main(sys.argv[0])
......@@ -65,6 +65,10 @@ __all__ = ["getfqdn"]
__all__.extend(os._get_exports_list(_socket))
if _have_ssl:
__all__.extend(os._get_exports_list(_ssl))
def ssl(sock, keyfile=None, certfile=None):
import ssl as realssl
return realssl.sslwrap_simple(sock, keyfile, certfile)
__all__.append("ssl")
# WSA error codes
if sys.platform.lower().startswith("win"):
......
# Wrapper module for _ssl, providing some additional facilities
# implemented in Python. Written by Bill Janssen.
"""\
This module provides some more Pythonic support for SSL.
Object types:
sslsocket -- subtype of socket.socket which does SSL over the socket
Exceptions:
sslerror -- exception raised for I/O errors
Functions:
cert_time_to_seconds -- convert time string used for certificate
notBefore and notAfter functions to integer
seconds past the Epoch (the time values
returned from time.time())
fetch_server_certificate (HOST, PORT) -- fetch the certificate provided
by the server running on HOST at port PORT. No
validation of the certificate is performed.
Integer constants:
SSL_ERROR_ZERO_RETURN
SSL_ERROR_WANT_READ
SSL_ERROR_WANT_WRITE
SSL_ERROR_WANT_X509_LOOKUP
SSL_ERROR_SYSCALL
SSL_ERROR_SSL
SSL_ERROR_WANT_CONNECT
SSL_ERROR_EOF
SSL_ERROR_INVALID_ERROR_CODE
The following group define certificate requirements that one side is
allowing/requiring from the other side:
CERT_NONE - no certificates from the other side are required (or will
be looked at if provided)
CERT_OPTIONAL - certificates are not required, but if provided will be
validated, and if validation fails, the connection will
also fail
CERT_REQUIRED - certificates are required, and will be validated, and
if validation fails, the connection will also fail
The following constants identify various SSL protocol variants:
PROTOCOL_SSLv2
PROTOCOL_SSLv3
PROTOCOL_SSLv23
PROTOCOL_TLSv1
"""
import os, sys
import _ssl # if we can't import it, let the error propagate
from socket import socket
from _ssl import sslerror
from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1
# Root certs:
#
# The "ca_certs" argument to sslsocket() expects a file containing one or more
# certificates that are roots of various certificate signing chains. This file
# contains the certificates in PEM format (RFC ) where each certificate is
# encoded in base64 encoding and surrounded with a header and footer:
# -----BEGIN CERTIFICATE-----
# ... (CA certificate in base64 encoding) ...
# -----END CERTIFICATE-----
# The various certificates in the file are just concatenated together:
# -----BEGIN CERTIFICATE-----
# ... (CA certificate in base64 encoding) ...
# -----END CERTIFICATE-----
# -----BEGIN CERTIFICATE-----
# ... (a second CA certificate in base64 encoding) ...
# -----END CERTIFICATE-----
#
# Some "standard" root certificates are available at
#
# http://www.thawte.com/roots/ (for Thawte roots)
# http://www.verisign.com/support/roots.html (for Verisign)
class sslsocket (socket):
def __init__(self, sock, keyfile=None, certfile=None,
server_side=False, cert_reqs=CERT_NONE,
ssl_version=PROTOCOL_SSLv23, ca_certs=None):
socket.__init__(self, _sock=sock._sock)
if certfile and not keyfile:
keyfile = certfile
if server_side:
self._sslobj = _ssl.sslwrap(self._sock, 1, keyfile, certfile,
cert_reqs, ssl_version, ca_certs)
else:
# see if it's connected
try:
socket.getpeername(self)
except:
# no, no connection yet
self._sslobj = None
else:
# yes, create the SSL object
self._sslobj = _ssl.sslwrap(self._sock, 0, keyfile, certfile,
cert_reqs, ssl_version, ca_certs)
self.keyfile = keyfile
self.certfile = certfile
self.cert_reqs = cert_reqs
self.ssl_version = ssl_version
self.ca_certs = ca_certs
def read(self, len=1024):
return self._sslobj.read(len)
def write(self, data):
return self._sslobj.write(data)
def getpeercert(self):
return self._sslobj.peer_certificate()
def send (self, data, flags=0):
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to send() on %s" %
self.__class__)
return self._sslobj.write(data)
def send_to (self, data, addr, flags=0):
raise ValueError("send_to not allowed on instances of %s" %
self.__class__)
def sendall (self, data, flags=0):
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to sendall() on %s" %
self.__class__)
return self._sslobj.write(data)
def recv (self, buflen=1024, flags=0):
if flags != 0:
raise ValueError(
"non-zero flags not allowed in calls to sendall() on %s" %
self.__class__)
return self._sslobj.read(data, buflen)
def recv_from (self, addr, buflen=1024, flags=0):
raise ValueError("recv_from not allowed on instances of %s" %
self.__class__)
def shutdown(self):
if self._sslobj:
self._sslobj.shutdown()
self._sslobj = None
else:
socket.shutdown(self)
def close(self):
if self._sslobj:
self.shutdown()
else:
socket.close(self)
def connect(self, addr):
# Here we assume that the socket is client-side, and not
# connected at the time of the call. We connect it, then wrap it.
if self._sslobj or (self.getsockname()[1] != 0):
raise ValueError("attempt to connect already-connected sslsocket!")
socket.connect(self, addr)
self._sslobj = _ssl.sslwrap(self._sock, 0, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs)
def accept(self):
raise ValueError("accept() not supported on an sslsocket")
# some utility functions
def cert_time_to_seconds(cert_time):
import time
return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT"))
# a replacement for the old socket.ssl function
def sslwrap_simple (sock, keyfile=None, certfile=None):
return _ssl.sslwrap(sock._sock, 0, keyfile, certfile, CERT_NONE,
PROTOCOL_SSLv23, None)
# fetch the certificate that the server is providing in PEM form
def fetch_server_certificate (host, port):
import re, tempfile, os
def subproc(cmd):
from subprocess import Popen, PIPE, STDOUT
proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
status = proc.wait()
output = proc.stdout.read()
return status, output
def strip_to_x509_cert(certfile_contents, outfile=None):
m = re.search(r"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
r".*[\r]*^[-]+END CERTIFICATE[-]+)$",
certfile_contents, re.MULTILINE | re.DOTALL)
if not m:
return None
else:
tn = tempfile.mktemp()
fp = open(tn, "w")
fp.write(m.group(1) + "\n")
fp.close()
try:
tn2 = (outfile or tempfile.mktemp())
status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
(tn, tn2))
if status != 0:
raise OperationError(status, tsig, output)
fp = open(tn2, 'rb')
data = fp.read()
fp.close()
os.unlink(tn2)
return data
finally:
os.unlink(tn)
if sys.platform.startswith("win"):
tfile = tempfile.mktemp()
fp = open(tfile, "w")
fp.write("quit\n")
fp.close()
try:
status, output = subproc(
'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
(host, port, tfile))
finally:
os.unlink(tfile)
else:
status, output = subproc(
'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
(host, port))
if status != 0:
raise OSError(status)
certtext = strip_to_x509_cert(output)
if not certtext:
raise ValueError("Invalid response received from server at %s:%s" %
(host, port))
return certtext
......@@ -1508,7 +1508,7 @@ class TarFile(object):
if hasattr(fileobj, "mode"):
self._mode = fileobj.mode
self._extfileobj = True
self.name = os.path.abspath(name)
self.name = os.path.abspath(name) if name else None
self.fileobj = fileobj
# Init attributes.
......
-----BEGIN RSA PRIVATE KEY-----
MIICXwIBAAKBgQC8ddrhm+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9L
opdJhTvbGfEj0DQs1IE8M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVH
fhi/VwovESJlaBOp+WMnfhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQAB
AoGBAK0FZpaKj6WnJZN0RqhhK+ggtBWwBnc0U/ozgKz2j1s3fsShYeiGtW6CK5nU
D1dZ5wzhbGThI7LiOXDvRucc9n7vUgi0alqPQ/PFodPxAN/eEYkmXQ7W2k7zwsDA
IUK0KUhktQbLu8qF/m8qM86ba9y9/9YkXuQbZ3COl5ahTZrhAkEA301P08RKv3KM
oXnGU2UHTuJ1MAD2hOrPxjD4/wxA/39EWG9bZczbJyggB4RHu0I3NOSFjAm3HQm0
ANOu5QK9owJBANgOeLfNNcF4pp+UikRFqxk5hULqRAWzVxVrWe85FlPm0VVmHbb/
loif7mqjU8o1jTd/LM7RD9f2usZyE2psaw8CQQCNLhkpX3KO5kKJmS9N7JMZSc4j
oog58yeYO8BBqKKzpug0LXuQultYv2K4veaIO04iL9VLe5z9S/Q1jaCHBBuXAkEA
z8gjGoi1AOp6PBBLZNsncCvcV/0aC+1se4HxTNo2+duKSDnbq+ljqOM+E7odU+Nq
ewvIWOG//e8fssd0mq3HywJBAJ8l/c8GVmrpFTx8r/nZ2Pyyjt3dH1widooDXYSV
q6Gbf41Llo5sYAtmxdndTLASuHKecacTgZVhy0FryZpLKrU=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIICpzCCAhCgAwIBAgIJAP+qStv1cIGNMA0GCSqGSIb3DQEBBQUAMIGJMQswCQYD
VQQGEwJVUzERMA8GA1UECBMIRGVsYXdhcmUxEzARBgNVBAcTCldpbG1pbmd0b24x
IzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9uMQwwCgYDVQQLEwNT
U0wxHzAdBgNVBAMTFnNvbWVtYWNoaW5lLnB5dGhvbi5vcmcwHhcNMDcwODI3MTY1
NDUwWhcNMTMwMjE2MTY1NDUwWjCBiTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCERl
bGF3YXJlMRMwEQYDVQQHEwpXaWxtaW5ndG9uMSMwIQYDVQQKExpQeXRob24gU29m
dHdhcmUgRm91bmRhdGlvbjEMMAoGA1UECxMDU1NMMR8wHQYDVQQDExZzb21lbWFj
aGluZS5weXRob24ub3JnMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ddrh
m+LutBvjYcQlnH21PPIseJ1JVG2HMmN2CmZk2YukO+9LopdJhTvbGfEj0DQs1IE8
M+kTUyOmuKfVrFMKwtVeCJphrAnhoz7TYOuLBSqt7lVHfhi/VwovESJlaBOp+WMn
fhcduPEYHYx/6cnVapIkZnLt30zu2um+DzA9jQIDAQABoxUwEzARBglghkgBhvhC
AQEEBAMCBkAwDQYJKoZIhvcNAQEFBQADgYEAF4Q5BVqmCOLv1n8je/Jw9K669VXb
08hyGzQhkemEBYQd6fzQ9A/1ZzHkJKb1P6yreOLSEh4KcxYPyrLRC1ll8nr5OlCx
CMhKkTnR6qBsdNV0XtdU2+N25hqW+Ma4ZeqsN/iiJVCGNOZGnvQuvCAGWF8+J/f/
iHkC6gGdBJhogs4=
-----END CERTIFICATE-----
......@@ -179,8 +179,10 @@ class CommonTest(seq_tests.CommonTest):
self.assertEqual(a, self.type2test(range(10)))
self.assertRaises(TypeError, a.__setslice__, 0, 1, 5)
self.assertRaises(TypeError, a.__setitem__, slice(0, 1, 5))
self.assertRaises(TypeError, a.__setslice__)
self.assertRaises(TypeError, a.__setitem__)
def test_delslice(self):
a = self.type2test([0, 1])
......
test_class
__init__: ()
__add__: (1,)
__radd__: (1,)
__sub__: (1,)
__rsub__: (1,)
__mul__: (1,)
__rmul__: (1,)
__truediv__: (1,)
__rtruediv__: (1,)
__mod__: (1,)
__rmod__: (1,)
__divmod__: (1,)
__rdivmod__: (1,)
__pow__: (1,)
__rpow__: (1,)
__rshift__: (1,)
__rrshift__: (1,)
__lshift__: (1,)
__rlshift__: (1,)
__and__: (1,)
__rand__: (1,)
__or__: (1,)
__ror__: (1,)
__xor__: (1,)
__rxor__: (1,)
__contains__: (1,)
__getitem__: (1,)
__setitem__: (1, 1)
__delitem__: (1,)
__getslice__: (0, 42)
__setslice__: (0, 42, 'The Answer')
__delslice__: (0, 42)
__getitem__: (slice(2, 1024, 10),)
__setitem__: (slice(2, 1024, 10), 'A lot')
__delitem__: (slice(2, 1024, 10),)
__getitem__: ((slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100),)
__setitem__: ((slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100), 'Strange')
__delitem__: ((slice(None, 42, None), Ellipsis, slice(None, 24, None), 24, 100),)
__getitem__: (slice(None, 42, None),)
__setitem__: (slice(None, 42, None), 'The Answer')
__delitem__: (slice(None, 42, None),)
__neg__: ()
__pos__: ()
__abs__: ()
__int__: ()
__int__: ()
__float__: ()
__index__: ()
__hash__: ()
__repr__: ()
__str__: ()
__eq__: (1,)
__lt__: (1,)
__gt__: (1,)
__ne__: (1,)
__eq__: (1,)
__gt__: (1,)
__lt__: (1,)
__ne__: (1,)
__del__: ()
__getattr__: ('spam',)
__setattr__: ('eggs', 'spam, spam, spam and ham')
__delattr__: ('cardinal',)
test_frozen
Hello world...
Hello world...
Hello world...
test_ossaudiodev
playing test sound file (expected running time: 2.93 sec)
test_signal
starting pause() loop...
test_winreg
Local registry tests worked
Remote registry calls can be tested using 'test_winreg.py --remote \\machine_name'
......@@ -935,7 +935,6 @@ class MixinStrUnicodeUserStringTest:
self.checkequal('abc', 'abc', '__getitem__', slice(0, 1000))
self.checkequal('a', 'abc', '__getitem__', slice(0, 1))
self.checkequal('', 'abc', '__getitem__', slice(0, 0))
# FIXME What about negative indices? This is handled differently by [] and __getitem__(slice)
self.checkraises(TypeError, 'abc', '__getitem__', 'def')
......@@ -949,10 +948,21 @@ class MixinStrUnicodeUserStringTest:
self.checkequal('', 'abc', '__getslice__', 1000, 1000)
self.checkequal('', 'abc', '__getslice__', 2000, 1000)
self.checkequal('', 'abc', '__getslice__', 2, 1)
# FIXME What about negative indizes? This is handled differently by [] and __getslice__
self.checkraises(TypeError, 'abc', '__getslice__', 'def')
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
s = string.ascii_letters + string.digits
indices = (0, None, 1, 3, 41, -1, -2, -37)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
L = list(s)[start:stop:step]
self.checkequal("".join(L), s, '__getitem__',
slice(start, stop, step))
def test_mul(self):
self.checkequal('', 'abc', '__mul__', -1)
self.checkequal('', 'abc', '__mul__', 0)
......
......@@ -468,6 +468,18 @@ class BaseTest(unittest.TestCase):
array.array(self.typecode)
)
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing
# (Assumes list conversion works correctly, too)
a = array.array(self.typecode, self.example)
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Everything except the initial 0 (invalid step)
for step in indices[1:]:
self.assertEqual(list(a[start:stop:step]),
list(a)[start:stop:step])
def test_setslice(self):
a = array.array(self.typecode, self.example)
a[:1] = a
......@@ -551,12 +563,34 @@ class BaseTest(unittest.TestCase):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.__setslice__, 0, 0, None)
self.assertRaises(TypeError, a.__setitem__, slice(0, 0), None)
self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None)
b = array.array(self.badtypecode())
self.assertRaises(TypeError, a.__setslice__, 0, 0, b)
self.assertRaises(TypeError, a.__setitem__, slice(0, 0), b)
self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b)
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Everything except the initial 0 (invalid step)
for step in indices[1:]:
a = array.array(self.typecode, self.example)
L = list(a)
# Make sure we have a slice of exactly the right length,
# but with (hopefully) different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
a[start:stop:step] = array.array(self.typecode, data)
self.assertEquals(a, array.array(self.typecode, L))
del L[start:stop:step]
del a[start:stop:step]
self.assertEquals(a, array.array(self.typecode, L))
def test_index(self):
example = 2*self.example
a = array.array(self.typecode, example)
......
......@@ -37,6 +37,18 @@ class BufferTests(unittest.TestCase):
self.failIf(a == b)
self.assertRaises(TypeError, lambda: a < b)
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
s = bytes(range(255, -1, -1))
b = buffer(s)
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(b[start:stop:step],
s[start:stop:step])
def test_main():
test_support.run_unittest(BufferTests)
......
This diff is collapsed.
......@@ -3,18 +3,25 @@ import test.test_support, unittest
import sys
import subprocess
def _spawn_python(*args):
cmd_line = [sys.executable]
cmd_line.extend(args)
return subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def _kill_python(p):
p.stdin.close()
data = p.stdout.read()
p.stdout.close()
# try to cleanup the child so we don't appear to leak when running
# with regrtest -R. This should be a no-op on Windows.
subprocess._cleanup()
return data
class CmdLineTest(unittest.TestCase):
def start_python(self, cmd_line):
cmd = '"%s" %s' % (sys.executable, cmd_line)
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.close()
data = p.stdout.read()
p.stdout.close()
# try to cleanup the child so we don't appear to leak when running
# with regrtest -R. This should be a no-op on Windows.
subprocess._cleanup()
return data
def start_python(self, *args):
p = _spawn_python(*args)
return _kill_python(p)
def exit_code(self, *args):
cmd_line = [sys.executable]
......@@ -72,6 +79,17 @@ class CmdLineTest(unittest.TestCase):
self.exit_code('-m', 'timeit', '-n', '1'),
0)
def test_run_module_bug1764407(self):
# -m and -i need to play well together
# Runs the timeit module and checks the __main__
# namespace has been populated appropriately
p = _spawn_python('-i', '-m', 'timeit', '-n', '1')
p.stdin.write('Timer\n')
p.stdin.write('exit()\n')
data = _kill_python(p)
self.assertTrue(data.find(b'1 loop') != -1)
self.assertTrue(data.find(b'__main__.Timer') != -1)
def test_run_code(self):
# Test expected operation of the '-c' switch
# Switch needs an argument
......
# Test the frozen module defined in frozen.c.
from __future__ import with_statement
from test.test_support import TestFailed
from test.test_support import captured_stdout, run_unittest
import unittest
import sys, os
try:
import __hello__
except ImportError as x:
raise TestFailed, "import __hello__ failed:" + str(x)
try:
import __phello__
except ImportError as x:
raise TestFailed, "import __phello__ failed:" + str(x)
try:
import __phello__.spam
except ImportError as x:
raise TestFailed, "import __phello__.spam failed:" + str(x)
if sys.platform != "mac": # On the Mac this import does succeed.
try:
import __phello__.foo
except ImportError:
pass
else:
raise TestFailed, "import __phello__.foo should have failed"
class FrozenTests(unittest.TestCase):
def test_frozen(self):
with captured_stdout() as stdout:
try:
import __hello__
except ImportError as x:
self.fail("import __hello__ failed:" + str(x))
try:
import __phello__
except ImportError as x:
self.fail("import __phello__ failed:" + str(x))
try:
import __phello__.spam
except ImportError as x:
self.fail("import __phello__.spam failed:" + str(x))
if sys.platform != "mac": # On the Mac this import does succeed.
try:
import __phello__.foo
except ImportError:
pass
else:
self.fail("import __phello__.foo should have failed")
self.assertEquals(stdout.getvalue(),
'Hello world...\nHello world...\nHello world...\n')
def test_main():
run_unittest(FrozenTests)
......@@ -305,6 +305,40 @@ class MmapTests(unittest.TestCase):
m[x] = b
self.assertEqual(m[x], b)
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
s = bytes(reversed(range(256)))
m = mmap.mmap(-1, len(s))
m[:] = s
self.assertEqual(m[:], s)
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(m[start:stop:step],
s[start:stop:step])
def test_extended_set_del_slice(self):
# Test extended slicing by comparing with list slicing.
s = bytes(reversed(range(256)))
m = mmap.mmap(-1, len(s))
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip invalid step 0
for step in indices[1:]:
m[:] = s
self.assertEqual(m[:], s)
L = list(s)
# Make sure we have a slice of exactly the right length,
# but with different data.
data = L[start:stop:step]
data = bytes(reversed(data))
L[start:stop:step] = data
m[start:stop:step] = data
self.assertEquals(m[:], bytes(L))
def test_main():
run_unittest(MmapTests)
......
......@@ -77,8 +77,7 @@ class OSSAudioDevTests(unittest.TestCase):
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
print ("playing test sound file (expected running time: %.2f sec)"
% expected_time)
self.assertEquals("%.2f" % expected_time, "2.93")
t1 = time.time()
dsp.write(data)
dsp.close()
......@@ -121,7 +120,6 @@ class OSSAudioDevTests(unittest.TestCase):
"setparameters%r: returned %r" % (config, result))
def set_bad_parameters(self, dsp):
# Now try some configurations that are presumably bogus: eg. 300
# channels currently exceeds even Hollywood's ambitions, and
# negative sampling rate is utter nonsense. setparameters() should
......@@ -166,7 +164,7 @@ class OSSAudioDevTests(unittest.TestCase):
def test_main():
try:
dsp = ossaudiodev.open('w')
except IOError as msg:
except (ossaudiodev.error, IOError) as msg:
if msg.args[0] in (errno.EACCES, errno.ENOENT,
errno.ENODEV, errno.EBUSY):
raise TestSkipped(msg)
......
......@@ -155,7 +155,8 @@ class Test(unittest.TestCase):
("t4 sub.py", "raise RuntimeError('Shouldnt load sub.py')"),
("t4 sub", None),
("t4 sub __init__.py", ""),
("t4 sub subsub.py", "raise RuntimeError('Shouldnt load subsub.py')"),
("t4 sub subsub.py",
"raise RuntimeError('Shouldnt load subsub.py')"),
("t4 sub subsub", None),
("t4 sub subsub __init__.py", "spam = 1"),
]
......@@ -196,7 +197,8 @@ class Test(unittest.TestCase):
def test_6(self):
hier = [
("t6", None),
("t6 __init__.py", "__all__ = ['spam', 'ham', 'eggs']"),
("t6 __init__.py",
"__all__ = ['spam', 'ham', 'eggs']"),
("t6 spam.py", ""),
("t6 ham.py", ""),
("t6 eggs.py", ""),
......@@ -223,10 +225,11 @@ class Test(unittest.TestCase):
("t7.py", ""),
("t7", None),
("t7 __init__.py", ""),
("t7 sub.py", "raise RuntimeError('Shouldnt load sub.py')"),
("t7 sub.py",
"raise RuntimeError('Shouldnt load sub.py')"),
("t7 sub", None),
("t7 sub __init__.py", ""),
("t7 sub subsub.py",
("t7 sub .py",
"raise RuntimeError('Shouldnt load subsub.py')"),
("t7 sub subsub", None),
("t7 sub subsub __init__.py",
......
......@@ -5,7 +5,7 @@ import os.path
import sys
import tempfile
from test.test_support import verbose, run_unittest, forget
from runpy import _run_module_code, run_module
from runpy import _run_code, _run_module_code, _run_module_as_main, run_module
# Set up the test code and expected results
......@@ -29,6 +29,16 @@ class RunModuleCodeTest(unittest.TestCase):
"nested = runpy._run_module_code('x=1\\n', mod_name='<run>')\n"
)
def test_run_code(self):
saved_argv0 = sys.argv[0]
d = _run_code(self.test_source, {})
self.failUnless(d["result"] == self.expected_result)
self.failUnless(d["__name__"] is None)
self.failUnless(d["__file__"] is None)
self.failUnless(d["__loader__"] is None)
self.failUnless(d["run_argv0"] is saved_argv0)
self.failUnless("run_name" not in d)
self.failUnless(sys.argv[0] is saved_argv0)
def test_run_module_code(self):
initial = object()
......@@ -37,44 +47,24 @@ class RunModuleCodeTest(unittest.TestCase):
loader = "Now you're just being silly"
d1 = dict(initial=initial)
saved_argv0 = sys.argv[0]
try:
d2 = _run_module_code(self.test_source,
d1,
name,
file,
loader,
alter_sys=True)
self.failUnless("result" not in d1)
self.failUnless(d2["initial"] is initial)
self.assertEqual(d2["result"], self.expected_result)
self.assertEqual(d2["nested"]["x"], 1)
self.assertEqual(d2["nested"]["__name__"], "<run>")
self.failUnless(d2["__name__"] is name)
self.failUnless(d2["__file__"] is file)
self.failUnless(d2["__loader__"] is loader)
self.failUnless(d2["run_argv0"] is file)
self.failUnless(d2["run_name_in_sys_modules"])
self.failUnless(d2["module_in_sys_modules"])
self.failUnless(sys.argv[0] is not saved_argv0)
self.failUnless(name in sys.modules)
finally:
sys.argv[0] = saved_argv0
if name in sys.modules:
del sys.modules[name]
def test_run_module_code_defaults(self):
saved_argv0 = sys.argv[0]
d = _run_module_code(self.test_source)
self.assertEqual(d["result"], self.expected_result)
self.failUnless(d["nested"]["x"] == 1)
self.failUnless(d["nested"]["__name__"] == "<run>")
self.failUnless(d["__name__"] is None)
self.failUnless(d["__file__"] is None)
self.failUnless(d["__loader__"] is None)
self.failUnless(d["run_argv0"] is saved_argv0)
self.failUnless(not d["run_name_in_sys_modules"])
d2 = _run_module_code(self.test_source,
d1,
name,
file,
loader)
self.failUnless("result" not in d1)
self.failUnless(d2["initial"] is initial)
self.assertEqual(d2["result"], self.expected_result)
self.assertEqual(d2["nested"]["x"], 1)
self.failUnless(d2["__name__"] is name)
self.failUnless(d2["run_name_in_sys_modules"])
self.failUnless(d2["module_in_sys_modules"])
self.failUnless(d2["__file__"] is file)
self.failUnless(d2["run_argv0"] is file)
self.failUnless(d2["__loader__"] is loader)
self.failUnless(sys.argv[0] is saved_argv0)
self.failUnless(None not in sys.modules)
self.failUnless(name not in sys.modules)
class RunModuleTest(unittest.TestCase):
......
This diff is collapsed.
This diff is collapsed.
......@@ -5,7 +5,7 @@ from _testcapi import test_structmembersType, \
LONG_MAX, LONG_MIN, ULONG_MAX, \
LLONG_MAX, LLONG_MIN, ULLONG_MAX
import warnings, unittest
import warnings, unittest, sys
from test import test_support
ts=test_structmembersType(1,2,3,4,5,6,7,8,9.99999,10.1010101010)
......@@ -59,7 +59,7 @@ class ReadWriteTests(unittest.TestCase):
class TestWarnings(unittest.TestCase):
def has_warned(self, w):
self.assert_(w.category is RuntimeWarning)
self.assertEqual(w.category, RuntimeWarning)
def test_byte_max(self):
with test_support.catch_warning() as w:
......@@ -94,10 +94,13 @@ class TestWarnings(unittest.TestCase):
def test_main(verbose=None):
test_support.run_unittest(
ReadWriteTests,
TestWarnings
)
# Obscure hack so that this test passes after reloads or repeated calls
# to test_main (regrtest -R).
if '__warningregistry__' in globals():
del globals()['__warningregistry__']
if hasattr(sys, '__warningregistry__'):
del sys.__warningregistry__
test_support.run_unittest(__name__)
if __name__ == "__main__":
test_main(verbose=True)
......@@ -97,6 +97,18 @@ class StructSeqTest(unittest.TestCase):
t = time.gmtime()
x = t.__reduce__()
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
t = time.gmtime()
L = list(t)
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(list(t[start:stop:step]),
L[start:stop:step])
def test_main():
test_support.run_unittest(StructSeqTest)
......
......@@ -362,6 +362,22 @@ def transient_internet():
return contextlib.nested(time_out, socket_peer_reset, ioerror_peer_reset)
@contextlib.contextmanager
def captured_stdout():
"""Run the with statement body using a StringIO object as sys.stdout.
Example use::
with captured_stdout() as s:
print "hello"
assert s.getvalue() == "hello"
"""
import io
orig_stdout = sys.stdout
sys.stdout = io.StringIO()
yield sys.stdout
sys.stdout = orig_stdout
#=======================================================================
# Decorator for running a function in a different locale, correctly resetting
# it afterwards.
......
......@@ -140,11 +140,25 @@ class UstarReadTest(ReadTest):
class MiscReadTest(ReadTest):
def test_no_filename(self):
def test_no_name_argument(self):
fobj = open(self.tarname, "rb")
tar = tarfile.open(fileobj=fobj, mode=self.mode)
self.assertEqual(tar.name, os.path.abspath(fobj.name))
def test_no_name_attribute(self):
data = open(self.tarname, "rb").read()
fobj = io.BytesIO(data)
self.assertRaises(AttributeError, getattr, fobj, "name")
tar = tarfile.open(fileobj=fobj, mode=self.mode)
self.assertEqual(tar.name, None)
def test_empty_name_attribute(self):
data = open(self.tarname, "rb").read()
fobj = io.BytesIO(data)
fobj.name = ""
tar = tarfile.open(fileobj=fobj, mode=self.mode)
self.assertEqual(tar.name, None)
def test_fail_comp(self):
# For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
if self.mode == "r:":
......
......@@ -3,6 +3,7 @@
# UserString instances should behave similar to builtin string objects.
import unittest
import string
from test import test_support, string_tests
from UserString import UserString, MutableString
......@@ -86,6 +87,28 @@ class MutableStringTest(UserStringTest):
del s[-1:10]
self.assertEqual(s, "fo")
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
orig = string.ascii_letters + string.digits
for start in indices:
for stop in indices:
# Use indices[1:] when MutableString can handle real
# extended slices
for step in (None, 1, -1):
s = self.type2test(orig)
L = list(orig)
# Make sure we have a slice of exactly the right length,
# but with (hopefully) different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
s[start:stop:step] = "".join(data)
self.assertEquals(s, "".join(L))
del L[start:stop:step]
del s[start:stop:step]
self.assertEquals(s, "".join(L))
def test_immutable(self):
s = self.type2test("foobar")
s2 = s.immutable()
......
This diff is collapsed.
......@@ -284,6 +284,27 @@ def http_server(evt, numrequests):
evt.set()
def is_unavailable_exception(e):
'''Returns True if the given ProtocolError is the product of a server-side
exception caused by the 'temporarily unavailable' response sometimes
given by operations on non-blocking sockets.'''
# sometimes we get a -1 error code and/or empty headers
if e.errcode == -1 or e.headers is None:
return True
exc_mess = e.headers.get('X-exception')
if exc_mess and 'temporarily unavailable' in exc_mess.lower():
return True
return False
# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
# condition occurs infrequently on some platforms, frequently on others, and
# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket.
# If the server class is updated at some point in the future to handle this
# situation more gracefully, these tests should be modified appropriately.
class SimpleServerTestCase(unittest.TestCase):
def setUp(self):
# enable traceback reporting
......@@ -291,7 +312,7 @@ class SimpleServerTestCase(unittest.TestCase):
self.evt = threading.Event()
# start server thread to handle requests
serv_args = (self.evt, 2)
serv_args = (self.evt, 1)
threading.Thread(target=http_server, args=serv_args).start()
# wait for port to be assigned to server
......@@ -314,8 +335,10 @@ class SimpleServerTestCase(unittest.TestCase):
p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
self.assertEqual(p.pow(6,8), 6**8)
except xmlrpclib.ProtocolError as e:
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
def test_introspection1(self):
try:
......@@ -325,8 +348,10 @@ class SimpleServerTestCase(unittest.TestCase):
'system.methodHelp', 'system.methodSignature', 'system.multicall'])
self.assertEqual(set(meth), expected_methods)
except xmlrpclib.ProtocolError as e:
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
def test_introspection2(self):
try:
......@@ -334,19 +359,23 @@ class SimpleServerTestCase(unittest.TestCase):
divhelp = p.system.methodHelp('div')
self.assertEqual(divhelp, 'This is the div function')
except xmlrpclib.ProtocolError as e:
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
def test_introspection3(self):
# the SimpleXMLRPCServer doesn't support signatures, but
# at least check that we can try
# at least check that we can try making the call
try:
p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
divsig = p.system.methodSignature('div')
self.assertEqual(divsig, 'signatures not supported')
except xmlrpclib.ProtocolError as e:
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
def test_multicall(self):
try:
......@@ -360,8 +389,10 @@ class SimpleServerTestCase(unittest.TestCase):
self.assertEqual(pow_result, 6**8)
self.assertEqual(div_result, 127//42)
except xmlrpclib.ProtocolError as e:
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# ignore failures due to non-blocking socket 'unavailable' errors
if not is_unavailable_exception(e):
# protocol error; provide additional information in test output
self.fail("%s\n%s" % (e, e.headers))
# This is a contrived way to make a failure occur on the server side
......
This diff is collapsed.
This diff is collapsed.
......@@ -138,17 +138,16 @@ static int RunModule(char *module)
fprintf(stderr, "Could not import runpy module\n");
return -1;
}
runmodule = PyObject_GetAttrString(runpy, "run_module");
runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
if (runmodule == NULL) {
fprintf(stderr, "Could not access runpy.run_module\n");
fprintf(stderr, "Could not access runpy._run_module_as_main\n");
Py_DECREF(runpy);
return -1;
}
runargs = Py_BuildValue("sOsO", module,
Py_None, "__main__", Py_True);
runargs = Py_BuildValue("(s)", module);
if (runargs == NULL) {
fprintf(stderr,
"Could not create arguments for runpy.run_module\n");
"Could not create arguments for runpy._run_module_as_main\n");
Py_DECREF(runpy);
Py_DECREF(runmodule);
return -1;
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -1146,6 +1146,17 @@ string_subscript(PyStringObject* self, PyObject* item)
if (slicelength <= 0) {
return PyString_FromStringAndSize("", 0);
}
else if (start == 0 && step == 1 &&
slicelength == PyString_GET_SIZE(self) &&
PyString_CheckExact(self)) {
Py_INCREF(self);
return (PyObject *)self;
}
else if (step == 1) {
return PyString_FromStringAndSize(
PyString_AS_STRING(self) + start,
slicelength);
}
else {
source_buf = PyString_AsString((PyObject*)self);
result_buf = (char *)PyMem_Malloc(slicelength);
......
This diff is collapsed.
......@@ -586,6 +586,12 @@ tuplesubscript(PyTupleObject* self, PyObject* item)
if (slicelength <= 0) {
return PyTuple_New(0);
}
else if (start == 0 && step == 1 &&
slicelength == PyTuple_GET_SIZE(self) &&
PyTuple_CheckExact(self)) {
Py_INCREF(self);
return (PyObject *)self;
}
else {
result = PyTuple_New(slicelength);
if (!result) return NULL;
......
......@@ -8096,6 +8096,12 @@ unicode_subscript(PyUnicodeObject* self, PyObject* item)
if (slicelength <= 0) {
return PyUnicode_FromUnicode(NULL, 0);
} else if (start == 0 && step == 1 && slicelength == self->length &&
PyUnicode_CheckExact(self)) {
Py_INCREF(self);
return (PyObject *)self;
} else if (step == 1) {
return PyUnicode_FromUnicode(self->str + start, slicelength);
} else {
source_buf = PyUnicode_AS_UNICODE((PyObject*)self);
result_buf = (Py_UNICODE *)PyMem_MALLOC(slicelength*
......
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment