Python-checkins
Threads by month
- ----- 2025 -----
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2003 -----
- December
- November
- October
- September
- August
May 2004
- 57 participants
- 330 discussions

[Python-checkins] python/dist/src/Doc/whatsnew whatsnew24.tex, 1.48, 1.49
by loewis@users.sourceforge.net May 31, 2004
by loewis@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Doc/whatsnew
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27715/Doc/whatsnew
Modified Files:
whatsnew24.tex
Log Message:
Patch #963318: Add support for client-side cookie management.
Index: whatsnew24.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew24.tex,v
retrieving revision 1.48
retrieving revision 1.49
diff -C2 -d -r1.48 -r1.49
*** whatsnew24.tex 31 …
[View More]May 2004 03:15:02 -0000 1.48
--- whatsnew24.tex 31 May 2004 18:22:40 -0000 1.49
***************
*** 570,573 ****
--- 570,592 ----
% whole new modules get described in \subsections here
+ \subsection{cookielib}
+
+ The \module{cookielib} library supports client-side handling for HTTP
+ cookies, just as the \module{Cookie} provides server-side cookie
+ support in CGI scripts. This library manages cookies in a way similar
+ to web browsers. Cookies are stored in cookie jars; the library
+ transparently stores cookies offered by the web server in the cookie
+ jar, and fetches the cookie from the jar when connecting to the
+ server. Similar to web browsers, policy objects control whether
+ cookies are accepted or not.
+
+ In order to store cookies across sessions, two implementations of
+ cookie jars are provided: one that stores cookies in the Netscape
+ format, so applications can use the Mozilla or Lynx cookie jars, and
+ one that stores cookies in the same format as the Perl libwww libary.
+
+ \module{urllib2} has been changed to interact with \module{cookielib}:
+ \class{HTTPCookieProcessor} manages a cookie jar that is used when
+ accessing URLs.
% ======================================================================
[View Less]
1
0

python/dist/src/Doc/lib libcookielib.tex, NONE, 1.1 lib.tex, 1.225, 1.226 libcookie.tex, 1.11, 1.12 liburllib2.tex, 1.17, 1.18
by loewis@users.sourceforge.net May 31, 2004
by loewis@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Doc/lib
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27715/Doc/lib
Modified Files:
lib.tex libcookie.tex liburllib2.tex
Added Files:
libcookielib.tex
Log Message:
Patch #963318: Add support for client-side cookie management.
--- NEW FILE: libcookielib.tex ---
\section{\module{cookielib} ---
Cookie handling for HTTP clients}
\declaremodule{standard}{cookielib}
\moduleauthor{John J. Lee}{jjl(a)pobox.com}
\sectionauthor{John J. …
[View More]Lee}{jjl(a)pobox.com}
\modulesynopsis{Cookie handling for HTTP clients}
The \module{cookielib} module defines classes for automatic handling
of HTTP cookies. It is useful for accessing web sites that require
small pieces of data -- \dfn{cookies} -- to be set on the client
machine by an HTTP response from a web server, and then returned to
the server in later HTTP requests.
Both the regular Netscape cookie protocol and the protocol defined by
\rfc{2965} are handled. RFC 2965 handling is switched off by default.
\rfc{2109} cookies are parsed as Netscape cookies and subsequently
treated as RFC 2965 cookies. Note that the great majority of cookies
on the Internet are Netscape cookies. \module{cookielib} attempts to
follow the de-facto Netscape cookie protocol (which differs
substantially from that set out in the original Netscape
specification), including taking note of the \code{max-age} and
\code{port} cookie-attributes introduced with RFC 2109. \note{The
various named parameters found in \mailheader{Set-Cookie} and
\mailheader{Set-Cookie2} headers (eg. \code{domain} and
\code{expires}) are conventionally referred to as \dfn{attributes}.
To distinguish them from Python attributes, the documentation for this
module uses the term \dfn{cookie-attribute} instead}.
The module defines the following exception:
\begin{excdesc}{LoadError}
Instances of \class{FileCookieJar} raise this exception on failure to
load cookies from a file.
\end{excdesc}
The following classes are provided:
\begin{classdesc}{CookieJar}{policy=\constant{None}}
\var{policy} is an object implementing the \class{CookiePolicy}
interface.
The \class{CookieJar} class stores HTTP cookies. It extracts cookies
from HTTP requests, and returns them in HTTP responses.
\class{CookieJar} instances automatically expire contained cookies
when necessary. Subclasses are also responsible for storing and
retrieving cookies from a file or database.
\end{classdesc}
\begin{classdesc}{FileCookieJar}{filename, delayload=\constant{None},
policy=\constant{None}}
\var{policy} is an object implementing the \class{CookiePolicy}
interface. For the other arguments, see the documentation for the
corresponding attributes.
A \class{CookieJar} which can load cookies from, and perhaps save
cookies to, a file on disk. Cookies are \strong{NOT} loaded from the
named file until either the \method{load()} or \method{revert()}
method is called. Subclasses of this class are documented in section
\ref{file-cookie-jar-classes}.
\end{classdesc}
\begin{classdesc}{CookiePolicy}{}
This class is responsible for deciding whether each cookie should be
accepted from / returned to the server.
\end{classdesc}
\begin{classdesc}{DefaultCookiePolicy}{
blocked_domains=\constant{None},
allowed_domains=\constant{None},
netscape=\constant{True}, rfc2965=\constant{False},
hide_cookie2=\constant{False},
strict_domain=\constant{False},
strict_rfc2965_unverifiable=\constant{True},
strict_ns_unverifiable=\constant{False},
strict_ns_domain=\constant{DefaultCookiePolicy.DomainLiberal},
strict_ns_set_initial_dollar=\constant{False},
strict_ns_set_path=\constant{False}
}
Constructor arguments should be passed as keyword arguments only.
\var{blocked_domains} is a sequence of domain names that we never
accept cookies from, nor return cookies to. \var{allowed_domains} if
not \constant{None}, this is a sequence of the only domains for which
we accept and return cookies. For all other arguments, see the
documentation for \class{CookiePolicy} and \class{DefaultCookiePolicy}
objects.
\class{DefaultCookiePolicy} implements the standard accept / reject
rules for Netscape and RFC 2965 cookies. RFC 2109 cookies
(ie. cookies received in a \mailheader{Set-Cookie} header with a
version cookie-attribute of 1) are treated according to the RFC 2965
rules. \class{DefaultCookiePolicy} also provides some parameters to
allow some fine-tuning of policy.
\end{classdesc}
\begin{classdesc}{Cookie}{}
This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is
not expected that users of \module{cookielib} construct their own
\class{Cookie} instances. Instead, if necessary, call
\method{make_cookies()} on a \class{CookieJar} instance.
\end{classdesc}
\begin{seealso}
\seemodule{urllib2}{URL opening with automatic cookie handling.}
\seemodule{Cookie}{HTTP cookie classes, principally useful for
server-side code. The \module{cookielib} and \module{Cookie} modules
do not depend on each other.}
\seeurl{http://wwwsearch.sf.net/ClientCookie/}{Extensions to this
module, including a class for reading Microsoft Internet Explorer
cookies on Windows.}
\seeurl{http://www.netscape.com/newsref/std/cookie_spec.html}{The
specification of the original Netscape cookie protocol. Though this
is still the dominant protocol, the 'Netscape cookie protocol'
implemented by all the major browsers (and \module{cookielib}) only
bears a passing resemblance to the one sketched out in
\code{cookie_spec.html}.}
\seerfc{2109}{HTTP State Management Mechanism}{Obsoleted by RFC 2965.
Uses \mailheader{Set-Cookie} with version=1.}
\seerfc{2965}{HTTP State Management Mechanism}{The Netscape protocol
with the bugs fixed. Uses \mailheader{Set-Cookie2} in place of
\mailheader{Set-Cookie}. Not widely used.}
\seeurl{http://kristol.org/cookie/errata.html}{Unfinished errata to
RFC 2965.}
\seerfc{2964}{Use of HTTP State Management}{}
\end{seealso}
\subsection{CookieJar and FileCookieJar Objects \label{cookie-jar-objects}}
\class{CookieJar} objects support the iterator protocol.
\class{CookieJar} has the following methods:
\begin{methoddesc}[CookieJar]{add_cookie_header}{request}
Add correct \mailheader{Cookie} header to \var{request}.
If the CookiePolicy allows (ie. the \class{CookiePolicy} instance's
\member{rfc2965} and \member{hide_cookie2} attributes are true and
false respectively), the \mailheader{Cookie2} header is also added
when appropriate.
The \var{request} object (usually a \class{urllib2.Request} instance)
must support the methods \method{get_full_url()}, \method{get_host()},
\method{get_type()}, \method{unverifiable()},
\method{get_origin_req_host()}, \method{has_header()},
\method{get_header()}, \method{header_items()}, and
\method{add_unredirected_header()},as documented by \module{urllib2}.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{extract_cookies}{response, request}
Extract cookies from HTTP \var{response} and store them in the
\class{CookieJar}, where allowed by policy.
The \class{CookieJar} will look for allowable \mailheader{Set-Cookie}
and \mailheader{Set-Cookie2} headers in the \var{response} argument,
and store cookies as appropriate (subject to the
\method{CookiePolicy.set_ok()} method's approval).
The \var{response} object (usually the result of a call to
\method{urllib2.urlopen()}, or similar) should support an
\method{info()} method, which returns an object with a
\method{getallmatchingheaders()} method (usually a
\class{mimetools.Message} instance).
The \var{request} object (usually a \class{urllib2.Request} instance)
must support the methods \method{get_full_url()}, \method{get_host()},
\method{unverifiable()}, and \method{get_origin_req_host()}, as
documented by \module{urllib2}. The request is used to set default
values for cookie-attributes as well as for checking that the cookie
is allowed to be set.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{set_policy}{policy}
Set the \class{CookiePolicy} instance to be used.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{make_cookies}{response, request}
Return sequence of \class{Cookie} objects extracted from
\var{response} object.
See the documentation for \method{extract_cookies} for the interfaces
required of the \var{response} and \var{request} arguments.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{set_cookie_if_ok}{cookie, request}
Set a \class{Cookie} if policy says it's OK to do so.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{set_cookie}{cookie}
Set a \class{Cookie}, without checking with policy to see whether or
not it should be set.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{clear}{\optional{domain\optional{,
path\optional{, name}}}}
Clear some cookies.
If invoked without arguments, clear all cookies. If given a single
argument, only cookies belonging to that \var{domain} will be removed.
If given two arguments, cookies belonging to the specified
\var{domain} and URL \var{path} are removed. If given three
arguments, then the cookie with the specified \var{domain}, \var{path}
and \var{name} is removed.
Raises \exception{KeyError} if no matching cookie exists.
\end{methoddesc}
\begin{methoddesc}[CookieJar]{clear_session_cookies}{}
Discard all session cookies.
Discards all contained cookies that have a true \member{discard}
attribute (usually because they had either no \code{max-age} or
\code{expires} cookie-attribute, or an explicit \code{discard}
cookie-attribute). For interactive browsers, the end of a session
usually corresponds to closing the browser window.
Note that the \method{save()} method won't save session cookies
anyway, unless you ask otherwise by passing a true
\var{ignore_discard} argument.
\end{methoddesc}
\class{FileCookieJar} implements the following additional methods:
\begin{methoddesc}[FileCookieJar]{save}{filename=\constant{None},
ignore_discard=\constant{False}, ignore_expires=\constant{False}}
Save cookies to a file.
This base class raises \class{NotImplementedError}. Subclasses may
leave this method unimplemented.
\var{filename} is the name of file in which to save cookies. If
\var{filename} is not specified, \member{self.filename} is used (whose
default is the value passed to the constructor, if any); if
\member{self.filename} is \constant{None}, \exception{ValueError} is
raised.
\var{ignore_discard}: save even cookies set to be discarded.
\var{ignore_expires}: save even cookies that have expired
The file is overwritten if it already exists, thus wiping all the
cookies it contains. Saved cookies can be restored later using the
\method{load()} or \method{revert()} methods.
\end{methoddesc}
\begin{methoddesc}[FileCookieJar]{load}{filename=\constant{None},
ignore_discard=\constant{False}, ignore_expires=\constant{False}}
Load cookies from a file.
Old cookies are kept unless overwritten by newly loaded ones.
Arguments are as for \method{save()}.
The named file must be in the format understood by the class, or
\exception{LoadError} will be raised.
\end{methoddesc}
\begin{methoddesc}[FileCookieJar]{revert}{filename=\constant{None},
ignore_discard=\constant{False}, ignore_expires=\constant{False}}
Clear all cookies and reload cookies from a saved file.
Raises \exception{cookielib.LoadError} or \exception{IOError} if
reversion is not successful; the object's state will not be altered if
this happens.
\end{methoddesc}
\class{FileCookieJar} instances have the following public attributes:
\begin{memberdesc}{filename}
Filename of default file in which to keep cookies.
\end{memberdesc}
\begin{memberdesc}{delayload}
If true, load cookies lazily from disk. This is only a hint, since
this only affects performance, not behaviour (unless the cookies on
disk are changing). A \class{CookieJar} object may ignore it. None
of the \class{FileCookieJar} classes included in the standard library
lazily loads cookies.
\end{memberdesc}
\subsection{FileCookieJar subclasses and co-operation with web browsers
\label{file-cookie-jar-classes}}
The following \class{CookieJar} subclasses are provided for reading
and writing . Further \class{CookieJar} subclasses, including one
that reads Microsoft Internet Explorer cookies, are available at
\url{http://wwwsearch.sf.net/ClientCookie/}.
\begin{classdesc}{MozillaCookieJar}{filename, delayload=\constant{None},
policy=\constant{None}}
A \class{FileCookieJar} that can load from and save cookies to disk in
the Mozilla \code{cookies.txt} file format (which is also used by the
lynx and Netscape browsers). \note{This loses information about RFC
2965 cookies, and also about newer or non-standard cookie-attributes
such as \code{port}.}
\warning{Back up your cookies before saving if you have cookies whose
loss / corruption would be inconvenient (there are some subtleties
which may lead to slight changes in the file over a load / save
round-trip).}
Also note that cookies saved while Mozilla is running will get
clobbered by Mozilla.
\end{classdesc}
\begin{classdesc}{LWPCookieJar}{filename, delayload=\constant{None},
policy=\constant{None}}
A \class{FileCookieJar} that can load from and save cookies to disk in
format compatible with the libwww-perl library's \code{Set-Cookie3}
file format. This is convenient if you want to store cookies in a
human-readable file.
\end{classdesc}
\subsection{CookiePolicy Objects \label{cookie-policy-objects}}
Objects implementing the \class{CookiePolicy} interface have the
following methods:
\begin{methoddesc}[CookiePolicy]{set_ok}{cookie, request}
Return boolean value indicating whether cookie should be accepted from server.
\var{cookie} is a \class{cookielib.Cookie} instance. \var{request} is
an object implementing the interface defined by the documentation for
\method{CookieJar.extract_cookies()}.
\end{methoddesc}
\begin{methoddesc}[CookiePolicy]{return_ok}{cookie, request}
Return boolean value indicating whether cookie should be returned to server.
\var{cookie} is a \class{cookielib.Cookie} instance. \var{request} is
an object implementing the interface defined by the documentation for
\method{CookieJar.add_cookie_header()}.
\end{methoddesc}
\begin{methoddesc}[CookiePolicy]{domain_return_ok}{domain, request}
Return false if cookies should not be returned, given cookie domain.
This method is an optimization. It removes the need for checking
every cookie with a particular domain (which might involve reading
many files). The default implementations of
\method{domain_return_ok()} and \method{path_return_ok()}
(\samp{return True}) leave all the work to \method{return_ok()}.
If \method{domain_return_ok()} returns true for the cookie domain,
\method{path_return_ok()} is called for the cookie path. Otherwise,
\method{path_return_ok()} and \method{return_ok()} are never called
for that cookie domain. If \method{path_return_ok()} returns true,
\method{return_ok()} is called with the \class{Cookie} object itself
for a full check. Otherwise, \method{return_ok()} is never called for
that cookie path.
Note that \method{domain_return_ok()} is called for every
\emph{cookie} domain, not just for the \emph{request} domain. For
example, the function might be called with both \code{".example.com"}
and \code{"www.example.com"} if the request domain is
\code{"www.example.com"}. The same goes for
\method{path_return_ok()}.
The \var{request} argument is as documented for \method{return_ok()}.
\end{methoddesc}
\begin{methoddesc}[CookiePolicy]{path_return_ok}{path, request}
Return false if cookies should not be returned, given cookie path.
See the documentation for \method{domain_return_ok()}.
\end{methoddesc}
In addition to implementing the methods above, implementations of the
\class{CookiePolicy} interface must also supply the following
attributes, indicating which protocols should be used, and how. All
of these attributes may be assigned to.
\begin{memberdesc}{netscape}
Implement netscape protocol.
\end{memberdesc}
\begin{memberdesc}{rfc2965}
Implement RFC 2965 protocol.
\end{memberdesc}
\begin{memberdesc}{hide_cookie2}
Don't add Cookie2 header to requests (the presence of this header
indicates to the server that we understand RFC 2965 cookies).
\end{memberdesc}
The most useful way to define a \class{CookiePolicy} class is by
subclassing from \class{DefaultCookiePolicy} and overriding some or
all of the methods above. \class{CookiePolicy} itself may be used as
a 'null policy' to allow setting and receiving any and all cookies.
\subsection{DefaultCookiePolicy Objects \label{default-cookie-policy-objects}}
Implements the standard rules for accepting and returning cookies.
Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is
switched off by default.
The easiest way to provide your own policy is to override this class
and call its methods in your overriden implementations before adding
your own additional checks:
\begin{verbatim}
import cookielib
class MyCookiePolicy(cookielib.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request):
return False
if i_dont_want_to_store_this_cookie(cookie):
return False
return True
\end{verbatim}
In addition to the features required to implement the
\class{CookiePolicy} interface, this class allows you to block and
allow domains from setting and receiving cookies. There are also some
strictness switches that allow you to tighten up the rather loose
Netscape protocol rules a little bit (at the cost of blocking some
benign cookies).
A domain blacklist and whitelist is provided (both off by default).
Only domains not in the blacklist and present in the whitelist (if the
whitelist is active) participate in cookie setting and returning. Use
the \var{blocked_domains} constructor argument, and
\method{blocked_domains()} and \method{set_blocked_domains()} methods
(and the corresponding argument and methods for
\var{allowed_domains}). If you set a whitelist, you can turn it off
again by setting it to \constant{None}.
Domains in block or allow lists that do not start with a dot must be
equal. For example, \code{"example.com"} matches a blacklist entry of
\code{"example.com"}, but \code{"www.example.com"} does not. Domains
that do start with a dot are matched by more specific domains too.
For example, both \code{"www.example.com"} and
\code{"www.coyote.example.com"} match \code{".example.com"} (but
\code{"example.com"} itself does not). IP addresses are an exception,
and must match exactly. For example, if blocked_domains contains
\code{"192.168.1.2"} and \code{".168.1.2"}, 192.168.1.2 is blocked,
but 193.168.1.2 is not.
\class{DefaultCookiePolicy} implements the following additional
methods:
\begin{methoddesc}[DefaultCookiePolicy]{blocked_domains}{}
Return the sequence of blocked domains (as a tuple).
\end{methoddesc}
\begin{methoddesc}[DefaultCookiePolicy]{set_blocked_domains}
{blocked_domains}
Set the sequence of blocked domains.
\end{methoddesc}
\begin{methoddesc}[DefaultCookiePolicy]{is_blocked}{domain}
Return whether \var{domain} is on the blacklist for setting or
receiving cookies.
\end{methoddesc}
\begin{methoddesc}[DefaultCookiePolicy]{allowed_domains}{}
Return \constant{None}, or the sequence of allowed domains (as a tuple).
\end{methoddesc}
\begin{methoddesc}[DefaultCookiePolicy]{set_allowed_domains}
{allowed_domains}
Set the sequence of allowed domains, or \constant{None}.
\end{methoddesc}
\begin{methoddesc}[DefaultCookiePolicy]{is_not_allowed}{domain}
Return whether \var{domain} is not on the whitelist for setting or
receiving cookies.
\end{methoddesc}
\class{DefaultCookiePolicy} instances have the following attributes,
which are all initialised from the constructor arguments of the same
name, and which may all be assigned to.
General strictness switches:
\begin{memberdesc}{strict_domain}
Don't allow sites to set two-component domains with country-code
top-level domains like \code{.co.uk}, \code{.gov.uk},
\code{.co.nz}.etc. This is far from perfect and isn't guaranteed to
work!
\end{memberdesc}
RFC 2965 protocol strictness switches:
\begin{memberdesc}{strict_rfc2965_unverifiable}
Follow RFC 2965 rules on unverifiable transactions (usually, an
unverifiable transaction is one resulting from a redirect or a request
for an image hosted on another site). If this is false, cookies are
\emph{never} blocked on the basis of verifiability
\end{memberdesc}
Netscape protocol strictness switches:
\begin{memberdesc}{strict_ns_unverifiable}
apply RFC 2965 rules on unverifiable transactions even to Netscape
cookies
\end{memberdesc}
\begin{memberdesc}{strict_ns_domain}
Flags indicating how strict to be with domain-matching rules for
Netscape cookies. See below for acceptable values.
\end{memberdesc}
\begin{memberdesc}{strict_ns_set_initial_dollar}
Ignore cookies in Set-Cookie: headers that have names starting with
\code{'\$'}.
\end{memberdesc}
\begin{memberdesc}{strict_ns_set_path}
Don't allow setting cookies whose path doesn't path-match request URI.
\end{memberdesc}
\member{strict_ns_domain} is a collection of flags. Its value is
constructed by or-ing together (for example,
\code{DomainStrictNoDots|DomainStrictNonDomain} means both flags are
set).
\begin{memberdesc}{DomainStrictNoDots}
When setting cookies, the 'host prefix' must not contain a dot
(eg. \code{www.foo.bar.com} can't set a cookie for \code{.bar.com},
because \code{www.foo} contains a dot).
\end{memberdesc}
\begin{memberdesc}{DomainStrictNonDomain}
Cookies that did not explicitly specify a \code{domain}
cookie-attribute can only be returned to a domain that string-compares
equal to the domain that set the cookie (eg. \code{spam.example.com}
won't be returned cookies from \code{example.com} that had no
\code{domain} cookie-attribute).
\end{memberdesc}
\begin{memberdesc}{DomainRFC2965Match}
When setting cookies, require a full RFC 2965 domain-match.
\end{memberdesc}
The following attributes are provided for convenience, and are the
most useful combinations of the above flags:
\begin{memberdesc}{DomainLiberal}
Equivalent to 0 (ie. all of the above Netscape domain strictness flags
switched off).
\end{memberdesc}
\begin{memberdesc}{DomainStrict}
Equivalent to \code{DomainStrictNoDots|DomainStrictNonDomain}.
\end{memberdesc}
\subsection{Cookie Objects \label{cookie-jar-objects}}
\class{Cookie} instances have Python attributes roughly corresponding
to the standard cookie-attributes specified in the various cookie
standards. The correspondence is not one-to-one, because there are
complicated rules for assigning default values, and because the
\code{max-age} and \code{expires} cookie-attributes contain equivalent
information.
Assignment to these attributes should not be necessary other than in
rare circumstances in a \class{CookiePolicy} method. The class does
not enforce internal consistency, so you should know what you're
doing if you do that.
\begin{memberdesc}[Cookie]{version}
Integer or \constant{None}. Netscape cookies have version 0. RFC
2965 and RFC 2109 cookies have version 1.
\end{memberdesc}
\begin{memberdesc}[Cookie]{name}
Cookie name (a string), or \constant{None}.
\end{memberdesc}
\begin{memberdesc}[Cookie]{value}
Cookie value (a string).
\end{memberdesc}
\begin{memberdesc}[Cookie]{port}
String representing a port or a set of ports (eg. '80', or '80,8080'),
or \constant{None}.
\end{memberdesc}
\begin{memberdesc}[Cookie]{path}
Cookie path (a string, eg. '/acme/rocket_launchers').
\end{memberdesc}
\begin{memberdesc}[Cookie]{secure}
True if cookie should only be returned over a secure connection.
\end{memberdesc}
\begin{memberdesc}[Cookie]{expires}
Integer expiry date in seconds since epoch, or \constant{None}. See
also the \method{is_expired()} method.
\end{memberdesc}
\begin{memberdesc}[Cookie]{discard}
True if this is a session cookie.
\end{memberdesc}
\begin{memberdesc}[Cookie]{comment}
String comment from the server explaining the function of this cookie,
or \constant{None}.
\end{memberdesc}
\begin{memberdesc}[Cookie]{comment_url}
URL linking to a comment from the server explaining the function of
this cookie, or \constant{None}.
\end{memberdesc}
\begin{memberdesc}[Cookie]{port_specified}
True if a port or set of ports was explicitly specified by the server
(in the \mailheader{Set-Cookie} / \mailheader{Set-Cookie2} header).
\end{memberdesc}
\begin{memberdesc}[Cookie]{domain_specified}
True if a domain was explicitly specified by the server.
\end{memberdesc}
\begin{memberdesc}[Cookie]{domain_initial_dot}
True if the domain explicitly specified by the server began with a
dot ('.').
\end{memberdesc}
Cookies may have additional non-standard cookie-attributes. These may
be accessed using the following methods:
\begin{methoddesc}[Cookie]{has_nonstandard_attr}{name}
Return true if cookie has the named cookie-attribute.
\end{methoddesc}
\begin{methoddesc}[Cookie]{get_nonstandard_attr}{name, default=\constant{None}}
If cookie has the named cookie-attribute, return its value.
Otherwise, return \var{default}.
\end{methoddesc}
\begin{methoddesc}[Cookie]{set_nonstandard_attr}{name, value}
Set the value of the named cookie-attribute.
\end{methoddesc}
The \class{Cookie} class also defines the following method:
\begin{methoddesc}[Cookie]{is_expired}{\optional{now=\constant{None}}}
True if cookie has passed the time at which the server requested it
should expire. If \var{now} is given (in seconds since the epoch),
return whether the cookie has expired at the specified time.
\end{methoddesc}
\subsection{Examples \label{cookielib-examples}}
The first example shows the most common usage of \module{cookielib}:
\begin{verbatim}
import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
\end{verbatim}
This example illustrates how to open a URL using your Netscape,
Mozilla, or lynx cookies (assumes \UNIX{} convention for location of
the cookies file):
\begin{verbatim}
import os, cookielib, urllib2
cj = cookielib.MozillaCookieJar()
cj.load(os.path.join(os.environ["HOME"], "/.netscape/cookies.txt"))
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
\end{verbatim}
The next example illustrates the use of \class{DefaultCookiePolicy}.
Turn on RFC 2965 cookies, be more strict about domains when setting
and returning Netscape cookies, and block some domains from setting
cookies or having them returned:
\begin{verbatim}
import urllib2
from cookielib import CookieJar, DefaultCookiePolicy as Policy
policy = Policy(rfc2965=True, strict_ns_domain=Policy.DomainStrict,
blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
\end{verbatim}
Index: lib.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/lib/lib.tex,v
retrieving revision 1.225
retrieving revision 1.226
diff -C2 -d -r1.225 -r1.226
*** lib.tex 29 Jan 2004 07:35:45 -0000 1.225
--- lib.tex 31 May 2004 18:22:39 -0000 1.226
***************
*** 234,237 ****
--- 234,238 ----
\input{libsimplehttp}
\input{libcgihttp}
+ \input{libcookielib}
\input{libcookie}
\input{libxmlrpclib}
Index: libcookie.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/lib/libcookie.tex,v
retrieving revision 1.11
retrieving revision 1.12
diff -C2 -d -r1.11 -r1.12
*** libcookie.tex 25 Aug 2003 04:28:03 -0000 1.11
--- libcookie.tex 31 May 2004 18:22:39 -0000 1.12
***************
*** 69,72 ****
--- 69,76 ----
\begin{seealso}
+ \seemodule{cookielib}{HTTP cookie handling for for web
+ \emph{clients}. The \module{cookielib} and \module{Cookie}
+ modules do not depend on each other.}
+
\seerfc{2109}{HTTP State Management Mechanism}{This is the state
management specification implemented by this module.}
Index: liburllib2.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/lib/liburllib2.tex,v
retrieving revision 1.17
retrieving revision 1.18
diff -C2 -d -r1.17 -r1.18
*** liburllib2.tex 12 May 2004 03:07:27 -0000 1.17
--- liburllib2.tex 31 May 2004 18:22:39 -0000 1.18
***************
*** 11,15 ****
The \module{urllib2} module defines functions and classes which help
in opening URLs (mostly HTTP) in a complex world --- basic and digest
! authentication, redirections and more.
The \module{urllib2} module defines the following functions:
--- 11,15 ----
The \module{urllib2} module defines functions and classes which help
in opening URLs (mostly HTTP) in a complex world --- basic and digest
! authentication, redirections, cookies and more.
The \module{urllib2} module defines the following functions:
***************
*** 17,22 ****
\begin{funcdesc}{urlopen}{url\optional{, data}}
Open the URL \var{url}, which can be either a string or a \class{Request}
! object (currently the code checks that it really is a \class{Request}
! instance, or an instance of a subclass of \class{Request}).
\var{data} should be a string, which specifies additional data to
--- 17,21 ----
\begin{funcdesc}{urlopen}{url\optional{, data}}
Open the URL \var{url}, which can be either a string or a \class{Request}
! object.
\var{data} should be a string, which specifies additional data to
***************
*** 88,92 ****
The following classes are provided:
! \begin{classdesc}{Request}{url\optional{, data\optional{, headers}}}
This class is an abstraction of a URL request.
--- 87,92 ----
The following classes are provided:
! \begin{classdesc}{Request}{url\optional{, data}\optional{, headers}
! \optional{, origin_req_host}\optional{, unverifiable}}
This class is an abstraction of a URL request.
***************
*** 95,98 ****
--- 95,116 ----
\var{headers} should be a dictionary, and will be treated as if
\method{add_header()} was called with each key and value as arguments.
+
+ The final two arguments are only of interest for correct handling of
+ third-party HTTP cookies:
+
+ \var{origin_req_host} should be the request-host of the origin
+ transaction, as defined by \rfc{2965}. It defaults to
+ \code{cookielib.request_host(self)}. This is the host name or IP
+ address of the original request that was initiated by the user. For
+ example, if the request is for an image in an HTML document, this
+ should be the request-host of the request for the page containing the
+ image.
+
+ \var{unverifiable} should indicate whether the request is
+ unverifiable, as defined by RFC 2965. It defaults to False. An
+ unverifiable request is one whose URL the user did not have the option
+ to approve. For example, if the request is for an image in an HTML
+ document, and the user had no option to approve the automatic fetching
+ of the image, this should be true.
\end{classdesc}
***************
*** 117,120 ****
--- 135,142 ----
\end{classdesc}
+ \begin{classdesc}{HTTPCookieProcessor}{\optional{cookiejar}}
+ A class to handle HTTP Cookies.
+ \end{classdesc}
+
\begin{classdesc}{ProxyHandler}{\optional{proxies}}
Cause requests to go through a proxy.
***************
*** 218,225 ****
\begin{methoddesc}[Request]{add_data}{data}
! Set the \class{Request} data to \var{data}. This is ignored
! by all handlers except HTTP handlers --- and there it should be an
! \mimetype{application/x-www-form-encoded} buffer, and will change the
! request to be \code{POST} rather than \code{GET}.
\end{methoddesc}
--- 240,247 ----
\begin{methoddesc}[Request]{add_data}{data}
! Set the \class{Request} data to \var{data}. This is ignored by all
! handlers except HTTP handlers --- and there it should be a byte
! string, and will change the request to be \code{POST} rather than
! \code{GET}.
\end{methoddesc}
***************
*** 283,286 ****
--- 305,319 ----
\end{methoddesc}
+ \begin{methoddesc}[Request]{get_origin_req_host}{}
+ Return the request-host of the origin transaction, as defined by
+ \rfc{2965}. See the documentation for the \class{Request}
+ constructor.
+ \end{methoddesc}
+
+ \begin{methoddesc}[Request]{is_unverifiable}{}
+ Return whether the request is unverifiable, as defined by RFC 2965.
+ See the documentation for the \class{Request} constructor.
+ \end{methoddesc}
+
\subsection{OpenerDirector Objects \label{opener-director-objects}}
***************
*** 290,301 ****
\begin{methoddesc}[OpenerDirector]{add_handler}{handler}
\var{handler} should be an instance of \class{BaseHandler}. The
! following methods are searched, and added to the possible chains.
\begin{itemize}
\item \method{\var{protocol}_open()} ---
signal that the handler knows how to open \var{protocol} URLs.
! \item \method{\var{protocol}_error_\var{type}()} ---
! signal that the handler knows how to handle \var{type} errors from
! \var{protocol}.
\item \method{\var{protocol}_request()} ---
signal that the handler knows how to pre-process \var{protocol}
--- 323,338 ----
\begin{methoddesc}[OpenerDirector]{add_handler}{handler}
\var{handler} should be an instance of \class{BaseHandler}. The
! following methods are searched, and added to the possible chains (note
! that HTTP errors are a special case).
\begin{itemize}
\item \method{\var{protocol}_open()} ---
signal that the handler knows how to open \var{protocol} URLs.
! \item \method{http_error_\var{type}()} ---
! signal that the handler knows how to handle HTTP errors with HTTP
! error code \var{type}.
! \item \method{\var{protocol}_error()} ---
! signal that the handler knows how to handle errors from
! (non-\code{http}) \var{protocol}.
\item \method{\var{protocol}_request()} ---
signal that the handler knows how to pre-process \var{protocol}
***************
*** 307,319 ****
\end{methoddesc}
- \begin{methoddesc}[OpenerDirector]{close}{}
- Explicitly break cycles, and delete all the handlers.
- Because the \class{OpenerDirector} needs to know the registered handlers,
- and a handler needs to know who the \class{OpenerDirector} who called
- it is, there is a reference cycle. Even though recent versions of Python
- have cycle-collection, it is sometimes preferable to explicitly break
- the cycles.
- \end{methoddesc}
-
\begin{methoddesc}[OpenerDirector]{open}{url\optional{, data}}
Open the given \var{url} (which can be a request object or a string),
--- 344,347 ----
***************
*** 321,330 ****
Arguments, return values and exceptions raised are the same as those
of \function{urlopen()} (which simply calls the \method{open()} method
! on the default installed \class{OpenerDirector}).
\end{methoddesc}
\begin{methoddesc}[OpenerDirector]{error}{proto\optional{,
arg\optional{, \moreargs}}}
! Handle an error in a given protocol. This will call the registered
error handlers for the given protocol with the given arguments (which
are protocol specific). The HTTP protocol is a special case which
--- 349,358 ----
Arguments, return values and exceptions raised are the same as those
of \function{urlopen()} (which simply calls the \method{open()} method
! on the currently installed global \class{OpenerDirector}).
\end{methoddesc}
\begin{methoddesc}[OpenerDirector]{error}{proto\optional{,
arg\optional{, \moreargs}}}
! Handle an error of the given protocol. This will call the registered
error handlers for the given protocol with the given arguments (which
are protocol specific). The HTTP protocol is a special case which
***************
*** 336,339 ****
--- 364,406 ----
\end{methoddesc}
+ OpenerDirector objects open URLs in three stages:
+
+ \begin{enumerate}
+ \item Every handler with a method named like
+ \method{\var{protocol}_request()} has that method called to
+ pre-process the request.
+
+ The order in which these methods are called is determined by
+ sorting the handler instances by the \member{.processor_order}
+ attribute.
+
+ \item Handlers with a method named like
+ \method{\var{protocol}_open()} are called to handle the request.
+ This stage ends when a handler either returns a
+ non-\constant{None} value (ie. a response), or raises an exception
+ (usually URLError). Exceptions are allowed to propagate.
+
+ In fact, the above algorithm is first tried for methods named
+ \method{default_open}. If all such methods return
+ \constant{None}, the algorithm is repeated for methods named like
+ \method{\var{protocol}_open()}. If all such methods return
+ \constant{None}, the algorithm is repeated for methods named
+ \method{unknown_open()}.
+
+ Note that the implementation of these methods may involve calls of
+ the parent \class{OpenerDirector} instance's \method{.open()} and
+ \method{.error()} methods.
+
+ The order in which these methods are called is determined by
+ sorting the handler instances.
+
+ \item Every handler with a method named like
+ \method{\var{protocol}_response()} has that method called to
+ post-process the response.
+
+ The order in which these methods are called is determined by
+ sorting the handler instances by the \member{.processor_order}
+ attribute.
+ \end{enumerate}
\subsection{BaseHandler Objects \label{base-handler-objects}}
***************
*** 352,356 ****
The following members and methods should only be used by classes
! derived from \class{BaseHandler}:
\begin{memberdesc}[BaseHandler]{parent}
--- 419,427 ----
The following members and methods should only be used by classes
! derived from \class{BaseHandler}. \note{The convention has been
! adopted that subclasses defining \method{\var{protocol}_request()} or
! \method{\var{protocol}_response()} methods are named
! \class{*Processor}; all others are named \class{*Handler}.}
!
\begin{memberdesc}[BaseHandler]{parent}
***************
*** 424,427 ****
--- 495,521 ----
\end{methoddesc}
+ \begin{methoddescni}[BaseHandler]{\var{protocol}_request}{req}
+ This method is \emph{not} defined in \class{BaseHandler}, but
+ subclasses should define it if they want to pre-process requests of
+ the given protocol.
+
+ This method, if defined, will be called by the parent
+ \class{OpenerDirector}. \var{req} will be a \class{Request} object.
+ The return value should be a \class{Request} object.
+ \end{methoddescni}
+
+ \begin{methoddescni}[BaseHandler]{\var{protocol}_response}{req, response}
+ This method is \emph{not} defined in \class{BaseHandler}, but
+ subclasses should define it if they want to post-process responses of
+ the given protocol.
+
+ This method, if defined, will be called by the parent
+ \class{OpenerDirector}. \var{req} will be a \class{Request} object.
+ \var{response} will be an object implementing the same interface as
+ the return value of \function{urlopen()}. The return value should
+ implement the same interface as the return value of
+ \function{urlopen()}.
+ \end{methoddescni}
+
\subsection{HTTPRedirectHandler Objects \label{http-redirect-handler}}
***************
*** 435,444 ****
Return a \class{Request} or \code{None} in response to a redirect.
This is called by the default implementations of the
! \method{http_error_30*()} methods when a redirection is received
! from the server. If a redirection should take place, return a new
\class{Request} to allow \method{http_error_30*()} to perform the
! redirect. Otherwise, raise \exception{HTTPError} if no other
! \class{Handler} should try to handle this URL, or return \code{None}
! if you can't but another \class{Handler} might.
\begin{notice}
--- 529,538 ----
Return a \class{Request} or \code{None} in response to a redirect.
This is called by the default implementations of the
! \method{http_error_30*()} methods when a redirection is received from
! the server. If a redirection should take place, return a new
\class{Request} to allow \method{http_error_30*()} to perform the
! redirect. Otherwise, raise \exception{HTTPError} if no other handler
! should try to handle this URL, or return \code{None} if you can't but
! another handler might.
\begin{notice}
***************
*** 479,482 ****
--- 573,585 ----
+ \subsection{HTTPCookieProcessor Objects \label{http-cookie-processor}}
+
+ \class{HTTPCookieProcessor} instances have one attribute:
+
+ \begin{memberdesc}{cookiejar}
+ The \class{cookielib.CookieJar} in which cookies are stored.
+ \end{memberdesc}
+
+
\subsection{ProxyHandler Objects \label{proxy-handler}}
[View Less]
1
0

python/dist/src/Lib _LWPCookieJar.py, NONE, 1.1 _MozillaCookieJar.py, NONE, 1.1 cookielib.py, NONE, 1.1 urllib2.py, 1.66, 1.67
by loewis@users.sourceforge.net May 31, 2004
by loewis@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Lib
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27715/Lib
Modified Files:
urllib2.py
Added Files:
_LWPCookieJar.py _MozillaCookieJar.py cookielib.py
Log Message:
Patch #963318: Add support for client-side cookie management.
--- NEW FILE: _LWPCookieJar.py ---
"""Load / save to libwww-perl (LWP) format files.
Actually, the format is slightly extended from that used by LWP's
(libwww-perl's) HTTP::Cookies, to avoid losing some RFC 2965 …
[View More]information
not recorded by LWP.
It uses the version string "2.0", though really there isn't an LWP Cookies
2.0 format. This indicates that there is extra information in here
(domain_dot and # port_spec) while still being compatible with
libwww-perl, I hope.
"""
import time, re, logging
from cookielib import reraise_unmasked_exceptions, FileCookieJar, Cookie, \
MISSING_FILENAME_TEXT, join_header_words, split_header_words, \
iso2time, time2isoz
def lwp_cookie_str(cookie):
"""Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring.
"""
h = [(cookie.name, cookie.value),
("path", cookie.path),
("domain", cookie.domain)]
if cookie.port is not None: h.append(("port", cookie.port))
if cookie.path_specified: h.append(("path_spec", None))
if cookie.port_specified: h.append(("port_spec", None))
if cookie.domain_initial_dot: h.append(("domain_dot", None))
if cookie.secure: h.append(("secure", None))
if cookie.expires: h.append(("expires",
time2isoz(float(cookie.expires))))
if cookie.discard: h.append(("discard", None))
if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
keys = cookie._rest.keys()
keys.sort()
for k in keys:
h.append((k, str(cookie._rest[k])))
h.append(("version", str(cookie.version)))
return join_header_words([h])
class LWPCookieJar(FileCookieJar):
"""
The LWPCookieJar saves a sequence of"Set-Cookie3" lines.
"Set-Cookie3" is the format used by the libwww-perl libary, not known
to be compatible with any browser, but which is easy to read and
doesn't lose information about RFC 2965 cookies.
Additional methods
as_lwp_str(ignore_discard=True, ignore_expired=True)
"""
def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
"""Return cookies as a string of "\n"-separated "Set-Cookie3" headers.
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
"""
now = time.time()
r = []
for cookie in self:
if not ignore_discard and cookie.discard:
continue
if not ignore_expires and cookie.is_expired(now):
continue
r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie))
return "\n".join(r+[""])
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
# There really isn't an LWP Cookies 2.0 format, but this indicates
# that there is extra information in here (domain_dot and
# port_spec) while still being compatible with libwww-perl, I hope.
f.write("#LWP-Cookies-2.0\n")
f.write(self.as_lwp_str(ignore_discard, ignore_expires))
finally:
f.close()
def _really_load(self, f, filename, ignore_discard, ignore_expires):
magic = f.readline()
if not re.search(self.magic_re, magic):
msg = "%s does not seem to contain cookies" % filename
raise IOError(msg)
now = time.time()
header = "Set-Cookie3:"
boolean_attrs = ("port_spec", "path_spec", "domain_dot",
"secure", "discard")
value_attrs = ("version",
"port", "path", "domain",
"expires",
"comment", "commenturl")
try:
while 1:
line = f.readline()
if line == "": break
if not line.startswith(header):
continue
line = line[len(header):].strip()
for data in split_header_words([line]):
name, value = data[0]
# name and value are an exception here, since a plain "foo"
# (with no "=", unlike "bar=foo") means a cookie with no
# name and value "foo". With all other cookie-attributes,
# the situation is reversed: "foo" means an attribute named
# "foo" with no value!
if value is None:
name, value = value, name
standard = {}
rest = {}
for k in boolean_attrs:
standard[k] = False
for k, v in data[1:]:
if k is not None:
lc = k.lower()
else:
lc = None
# don't lose case distinction for unknown fields
if (lc in value_attrs) or (lc in boolean_attrs):
k = lc
if k in boolean_attrs:
if v is None: v = True
standard[k] = v
elif k in value_attrs:
standard[k] = v
else:
rest[k] = v
h = standard.get
expires = h("expires")
discard = h("discard")
if expires is not None:
expires = iso2time(expires)
if expires is None:
discard = True
domain = h("domain")
domain_specified = domain.startswith(".")
c = Cookie(h("version"), name, value,
h("port"), h("port_spec"),
domain, domain_specified, h("domain_dot"),
h("path"), h("path_spec"),
h("secure"),
expires,
discard,
h("comment"),
h("commenturl"),
rest)
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except:
reraise_unmasked_exceptions((IOError,))
raise IOError("invalid Set-Cookie3 format file %s" % filename)
--- NEW FILE: _MozillaCookieJar.py ---
"""Mozilla / Netscape cookie loading / saving."""
import re, time, logging
from cookielib import reraise_unmasked_exceptions, FileCookieJar, Cookie, \
MISSING_FILENAME_TEXT
class MozillaCookieJar(FileCookieJar):
"""
WARNING: you may want to backup your browser's cookies file if you use
this class to save cookies. I *think* it works, but there have been
bugs in the past!
This class differs from CookieJar only in the format it uses to save and
load cookies to and from a file. This class uses the Mozilla/Netscape
`cookies.txt' format. lynx uses this file format, too.
Don't expect cookies saved while the browser is running to be noticed by
the browser (in fact, Mozilla on unix will overwrite your saved cookies if
you change them on disk while it's running; on Windows, you probably can't
save at all while the browser is running).
Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to
Netscape cookies on saving.
In particular, the cookie version and port number information is lost,
together with information about whether or not Path, Port and Discard were
specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the
domain as set in the HTTP header started with a dot (yes, I'm aware some
domains in Netscape files start with a dot and some don't -- trust me, you
really don't want to know any more about this).
Note that though Mozilla and Netscape use the same format, they use
slightly different headers. The class saves cookies using the Netscape
header by default (Mozilla can cope with that).
"""
magic_re = "#( Netscape)? HTTP Cookie File"
header = """\
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html
# This is a generated file! Do not edit.
"""
def _really_load(self, f, filename, ignore_discard, ignore_expires):
now = time.time()
magic = f.readline()
if not re.search(self.magic_re, magic):
f.close()
raise IOError(
"%s does not look like a Netscape format cookies file" %
filename)
try:
while 1:
line = f.readline()
if line == "": break
# last field may be absent, so keep any trailing tab
if line.endswith("\n"): line = line[:-1]
# skip comments and blank lines XXX what is $ for?
if (line.strip().startswith("#") or
line.strip().startswith("$") or
line.strip() == ""):
continue
domain, domain_specified, path, secure, expires, name, value = \
line.split("\t")
secure = (secure == "TRUE")
domain_specified = (domain_specified == "TRUE")
if name == "":
name = value
value = None
initial_dot = domain.startswith(".")
assert domain_specified == initial_dot
discard = False
if expires == "":
expires = None
discard = True
# assume path_specified is false
c = Cookie(0, name, value,
None, False,
domain, domain_specified, initial_dot,
path, False,
secure,
expires,
discard,
None,
None,
{})
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except:
reraise_unmasked_exceptions((IOError,))
raise IOError("invalid Netscape format file %s: %s" %
(filename, line))
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
f.write(self.header)
now = time.time()
for cookie in self:
if not ignore_discard and cookie.discard:
continue
if not ignore_expires and cookie.is_expired(now):
continue
if cookie.secure: secure = "TRUE"
else: secure = "FALSE"
if cookie.domain.startswith("."): initial_dot = "TRUE"
else: initial_dot = "FALSE"
if cookie.expires is not None:
expires = str(cookie.expires)
else:
expires = ""
if cookie.value is None:
# cookies.txt regards 'Set-Cookie: foo' as a cookie
# with no name, whereas cookielib regards it as a
# cookie with no value.
name = ""
value = cookie.name
else:
name = cookie.name
value = cookie.value
f.write(
"\t".join([cookie.domain, initial_dot, cookie.path,
secure, expires, name, value])+
"\n")
finally:
f.close()
--- NEW FILE: cookielib.py ---
"""HTTP cookie handling for web clients.
This module has (now fairly distant) origins in Gisle Aas' Perl module
HTTP::Cookies, from the libwww-perl library.
Docstrings, comments and debug strings in this code refer to the
attributes of the HTTP cookie system as cookie-attributes, to distinguish
them clearly from Python attributes.
Class diagram (note that the classes which do not derive from
FileCookieJar are not distributed with the Python standard library, but
are available from http://wwwsearch.sf.net/):
CookieJar____
/ \ \
FileCookieJar \ \
/ | \ \ \
MozillaCookieJar | LWPCookieJar \ \
| | \
[...1717 lines suppressed...]
"""
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
self._cookies_lock.acquire()
old_state = copy.deepcopy(self._cookies)
self._cookies = {}
try:
self.load(filename, ignore_discard, ignore_expires)
except (LoadError, IOError):
self._cookies = old_state
raise
self._cookies_lock.release()
from _LWPCookieJar import LWPCookieJar, lwp_cookie_str
from _MozillaCookieJar import MozillaCookieJar
Index: urllib2.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/urllib2.py,v
retrieving revision 1.66
retrieving revision 1.67
diff -C2 -d -r1.66 -r1.67
*** urllib2.py 10 May 2004 07:35:33 -0000 1.66
--- urllib2.py 31 May 2004 18:22:40 -0000 1.67
***************
*** 107,110 ****
--- 107,111 ----
import urlparse
import bisect
+ import cookielib
try:
***************
*** 177,181 ****
class Request:
! def __init__(self, url, data=None, headers={}):
# unwrap('<URL:type://host/path>') --> 'type://host/path'
self.__original = unwrap(url)
--- 178,183 ----
class Request:
! def __init__(self, url, data=None, headers={},
! origin_req_host=None, unverifiable=False):
# unwrap('<URL:type://host/path>') --> 'type://host/path'
self.__original = unwrap(url)
***************
*** 189,192 ****
--- 191,198 ----
self.add_header(key, value)
self.unredirected_hdrs = {}
+ if origin_req_host is None:
+ origin_req_host = cookielib.request_host(self)
+ self.origin_req_host = origin_req_host
+ self.unverifiable = unverifiable
def __getattr__(self, attr):
***************
*** 243,246 ****
--- 249,258 ----
self.__r_host = self.__original
+ def get_origin_req_host(self):
+ return self.origin_req_host
+
+ def is_unverifiable(self):
+ return self.unverifiable
+
def add_header(self, key, val):
# useful for something like authentication
***************
*** 255,258 ****
--- 267,279 ----
header_name in self.unredirected_hdrs)
+ def get_header(self, header_name, default=None):
+ return self.headers.get(
+ header_name,
+ self.unredirected_hdrs.get(header_name, default))
+
+ def header_items(self):
+ hdrs = self.unredirected_hdrs.copy()
+ hdrs.update(self.headers)
+ return hdrs.items()
class OpenerDirector:
***************
*** 461,465 ****
class HTTPRedirectHandler(BaseHandler):
! # maximum number of redirections before assuming we're in a loop
max_redirections = 10
--- 482,490 ----
class HTTPRedirectHandler(BaseHandler):
! # maximum number of redirections to any single URL
! # this is needed because of the state that cookies introduce
! max_repeats = 4
! # maximum total number of redirections (regardless of URL) before
! # assuming we're in a loop
max_redirections = 10
***************
*** 482,486 ****
# essentially all clients do redirect in this case, so we
# do the same.
! return Request(newurl, headers=req.headers)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)
--- 507,514 ----
# essentially all clients do redirect in this case, so we
# do the same.
! return Request(newurl,
! headers=req.headers,
! origin_req_host=req.get_origin_req_host(),
! unverifiable=True)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)
***************
*** 491,498 ****
# attribute to the Request object.
def http_error_302(self, req, fp, code, msg, headers):
if 'location' in headers:
! newurl = headers['location']
elif 'uri' in headers:
! newurl = headers['uri']
else:
return
--- 519,528 ----
# attribute to the Request object.
def http_error_302(self, req, fp, code, msg, headers):
+ # Some servers (incorrectly) return multiple Location headers
+ # (so probably same goes for URI). Use first header.
if 'location' in headers:
! newurl = headers.getheaders('location')[0]
elif 'uri' in headers:
! newurl = headers.getheaders('uri')[0]
else:
return
***************
*** 507,524 ****
# loop detection
! # .redirect_dict has a key (url, code) if url was previously
! # visited as a result of a redirection with that code. The
! # code is needed in addition to the URL because visiting a URL
! # twice isn't necessarily a loop: there is more than one way
! # to redirect (301, 302, 303, 307, refresh).
! key = (newurl, code)
if hasattr(req, 'redirect_dict'):
visited = new.redirect_dict = req.redirect_dict
! if key in visited or len(visited) >= self.max_redirections:
raise HTTPError(req.get_full_url(), code,
self.inf_msg + msg, headers, fp)
else:
visited = new.redirect_dict = req.redirect_dict = {}
! visited[key] = None
# Don't close the fp until we are sure that we won't use it
--- 537,550 ----
# loop detection
! # .redirect_dict has a key url if url was previously visited.
if hasattr(req, 'redirect_dict'):
visited = new.redirect_dict = req.redirect_dict
! if (visited.get(newurl, 0) >= self.max_repeats or
! len(visited) >= self.max_redirections):
raise HTTPError(req.get_full_url(), code,
self.inf_msg + msg, headers, fp)
else:
visited = new.redirect_dict = req.redirect_dict = {}
! visited[newurl] = visited.get(newurl, 0) + 1
# Don't close the fp until we are sure that we won't use it
***************
*** 913,917 ****
self._debuglevel = level
! def do_request(self, request):
host = request.get_host()
if not host:
--- 939,943 ----
self._debuglevel = level
! def do_request_(self, request):
host = request.get_host()
if not host:
***************
*** 988,992 ****
return self.do_open(httplib.HTTPConnection, req)
! http_request = AbstractHTTPHandler.do_request
if hasattr(httplib, 'HTTPS'):
--- 1014,1018 ----
return self.do_open(httplib.HTTPConnection, req)
! http_request = AbstractHTTPHandler.do_request_
if hasattr(httplib, 'HTTPS'):
***************
*** 996,1000 ****
return self.do_open(httplib.HTTPSConnection, req)
! https_request = AbstractHTTPHandler.do_request
class UnknownHandler(BaseHandler):
--- 1022,1043 ----
return self.do_open(httplib.HTTPSConnection, req)
! https_request = AbstractHTTPHandler.do_request_
!
! class HTTPCookieProcessor(BaseHandler):
! def __init__(self, cookiejar=None):
! if cookiejar is None:
! cookiejar = CookieJar()
! self.cookiejar = cookiejar
!
! def http_request(self, request):
! self.cookiejar.add_cookie_header(request)
! return request
!
! def http_response(self, request, response):
! self.cookiejar.extract_cookies(response, request)
! return response
!
! https_request = http_request
! https_response = http_response
class UnknownHandler(BaseHandler):
[View Less]
1
0

python/dist/src/Lib/test test_cookielib.py, NONE, 1.1 test_urllib2.py, 1.12, 1.13
by loewis@users.sourceforge.net May 31, 2004
by loewis@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Lib/test
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv27715/Lib/test
Modified Files:
test_urllib2.py
Added Files:
test_cookielib.py
Log Message:
Patch #963318: Add support for client-side cookie management.
--- NEW FILE: test_cookielib.py ---
# -*- coding: utf-8 -*-
"""Tests for cookielib.py."""
import re, os, time
from unittest import TestCase
from test import test_support
class DateTimeTests(TestCase):
def test_time2isoz(self):
…
[View More] from cookielib import time2isoz
base = 1019227000
day = 24*3600
self.assertEquals(time2isoz(base), "2002-04-19 14:36:40Z")
self.assertEquals(time2isoz(base+day), "2002-04-20 14:36:40Z")
self.assertEquals(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
self.assertEquals(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
[...1581 lines suppressed...]
self.assert_(not (
# a permanent cookie got lost accidently
counter["perm_after"] != counter["perm_before"] or
# a session cookie hasn't been cleared
counter["session_after"] != 0 or
# we didn't have session cookies in the first place
counter["session_before"] == 0))
def test_main(verbose=None):
from test import test_sets
test_support.run_unittest(
DateTimeTests,
HeaderTests,
CookieTests,
LWPCookieTests,
)
if __name__ == "__main__":
test_main(verbose=True)
Index: test_urllib2.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_urllib2.py,v
retrieving revision 1.12
retrieving revision 1.13
diff -C2 -d -r1.12 -r1.13
*** test_urllib2.py 24 Feb 2004 19:40:35 -0000 1.12
--- test_urllib2.py 31 May 2004 18:22:40 -0000 1.13
***************
*** 55,58 ****
--- 55,62 ----
def close(self): pass
+ class MockHeaders(dict):
+ def getheaders(self, name):
+ return self.values()
+
class MockResponse(StringIO.StringIO):
def __init__(self, code, msg, headers, data, url=None):
***************
*** 64,67 ****
--- 68,77 ----
return self.url
+ class MockCookieJar:
+ def add_cookie_header(self, request):
+ self.ach_req = request
+ def extract_cookies(self, response, request):
+ self.ec_req, self.ec_r = request, response
+
class FakeMethod:
def __init__(self, meth_name, action, handle):
***************
*** 475,479 ****
req = Request("http://example.com/", data)
r = MockResponse(200, "OK", {}, "")
! newreq = h.do_request(req)
if data is None: # GET
self.assert_("Content-length" not in req.unredirected_hdrs)
--- 485,489 ----
req = Request("http://example.com/", data)
r = MockResponse(200, "OK", {}, "")
! newreq = h.do_request_(req)
if data is None: # GET
self.assert_("Content-length" not in req.unredirected_hdrs)
***************
*** 492,496 ****
req.add_unredirected_header("Host", "baz")
req.add_unredirected_header("Spam", "foo")
! newreq = h.do_request(req)
self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
--- 502,506 ----
req.add_unredirected_header("Host", "baz")
req.add_unredirected_header("Spam", "foo")
! newreq = h.do_request_(req)
self.assertEqual(req.unredirected_hdrs["Content-length"], "foo")
self.assertEqual(req.unredirected_hdrs["Content-type"], "bar")
***************
*** 515,518 ****
--- 525,543 ----
self.assertEqual(o.args, (req, r, 201, "Created", {}))
+ def test_cookies(self):
+ cj = MockCookieJar()
+ h = urllib2.HTTPCookieProcessor(cj)
+ o = h.parent = MockOpener()
+
+ req = Request("http://example.com/")
+ r = MockResponse(200, "OK", {}, "")
+ newreq = h.http_request(req)
+ self.assert_(cj.ach_req is req is newreq)
+ self.assertEquals(req.get_origin_req_host(), "example.com")
+ self.assert_(not req.is_unverifiable())
+ newr = h.http_response(req, r)
+ self.assert_(cj.ec_req is req)
+ self.assert_(cj.ec_r is r is newr)
+
def test_redirect(self):
from_url = "http://example.com/a.html"
***************
*** 529,533 ****
req.add_unredirected_header("Spam", "spam")
try:
! method(req, MockFile(), code, "Blah", {"location": to_url})
except urllib2.HTTPError:
# 307 in response to POST requires user OK
--- 554,559 ----
req.add_unredirected_header("Spam", "spam")
try:
! method(req, MockFile(), code, "Blah",
! MockHeaders({"location": to_url}))
except urllib2.HTTPError:
# 307 in response to POST requires user OK
***************
*** 545,575 ****
# loop detection
req = Request(from_url)
! req.origin_req_host = "example.com"
! def redirect(h, req, code, url=to_url):
! method = getattr(h, "http_error_%s" % code)
! method(req, MockFile(), code, "Blah", {"location": url})
# Note that the *original* request shares the same record of
# redirections with the sub-requests caused by the redirections.
! # once
! redirect(h, req, 302)
! # twice: loop detected
! self.assertRaises(urllib2.HTTPError, redirect, h, req, 302)
! # and again
! self.assertRaises(urllib2.HTTPError, redirect, h, req, 302)
! # but this is a different redirect code, so OK...
! redirect(h, req, 301)
! self.assertRaises(urllib2.HTTPError, redirect, h, req, 301)
! # order doesn't matter
! redirect(h, req, 303)
! redirect(h, req, 307)
! self.assertRaises(urllib2.HTTPError, redirect, h, req, 303)
# detect endless non-repeating chain of redirects
! req = Request(from_url)
! req.origin_req_host = "example.com"
count = 0
try:
while 1:
! redirect(h, req, 302, "http://example.com/%d" % count)
count = count + 1
except urllib2.HTTPError:
--- 571,597 ----
# loop detection
req = Request(from_url)
! def redirect(h, req, url=to_url):
! h.http_error_302(req, MockFile(), 302, "Blah",
! MockHeaders({"location": url}))
# Note that the *original* request shares the same record of
# redirections with the sub-requests caused by the redirections.
!
! # detect infinite loop redirect of a URL to itself
! req = Request(from_url, origin_req_host="example.com")
! count = 0
! try:
! while 1:
! redirect(h, req, "http://example.com/")
! count = count + 1
! except urllib2.HTTPError:
! # don't stop until max_repeats, because cookies may introduce state
! self.assertEqual(count, urllib2.HTTPRedirectHandler.max_repeats)
# detect endless non-repeating chain of redirects
! req = Request(from_url, origin_req_host="example.com")
count = 0
try:
while 1:
! redirect(h, req, "http://example.com/%d" % count)
count = count + 1
except urllib2.HTTPError:
***************
*** 577,580 ****
--- 599,633 ----
urllib2.HTTPRedirectHandler.max_redirections)
+ def test_cookie_redirect(self):
+ class MockHTTPHandler(urllib2.HTTPHandler):
+ def __init__(self): self._count = 0
+ def http_open(self, req):
+ import mimetools
+ from StringIO import StringIO
+ if self._count == 0:
+ self._count = self._count + 1
+ msg = mimetools.Message(
+ StringIO("Location: http://www.cracker.com/\r\n\r\n"))
+ return self.parent.error(
+ "http", req, MockFile(), 302, "Found", msg)
+ else:
+ self.req = req
+ msg = mimetools.Message(StringIO("\r\n\r\n"))
+ return MockResponse(200, "OK", msg, "", req.get_full_url())
+ # cookies shouldn't leak into redirected requests
+ from cookielib import CookieJar
+ from urllib2 import build_opener, HTTPHandler, HTTPError, \
+ HTTPCookieProcessor
+
+ from test_cookielib import interact_netscape
+
+ cj = CookieJar()
+ interact_netscape(cj, "http://www.example.com/", "spam=eggs")
+ hh = MockHTTPHandler()
+ cp = HTTPCookieProcessor(cj)
+ o = build_opener(hh, cp)
+ o.open("http://www.example.com/")
+ self.assert_(not hh.req.has_header("Cookie"))
+
class MiscTests(unittest.TestCase):
[View Less]
1
0

python/dist/src/Lib/test mapping_tests.py, NONE, 1.1 test_os.py, 1.21, 1.22 test_shelve.py, 1.6, 1.7 test_types.py, 1.59, 1.60 test_userdict.py, 1.18, 1.19 test_weakref.py, 1.38, 1.39
by doerwalter@users.sourceforge.net May 31, 2004
by doerwalter@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Lib/test
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3029/Lib/test
Modified Files:
test_os.py test_shelve.py test_types.py test_userdict.py
test_weakref.py
Added Files:
mapping_tests.py
Log Message:
Port the dictionary tests from test_types.py to unittest. Collect as much
mapping tests as possible in mapping_test.py and reuse the tests in
test_dict.py, test_userdict.py, test_weakref.py, test_os.py and test_shelve.py.
>From SF patch #…
[View More]736962.
--- NEW FILE: mapping_tests.py ---
# tests common to dict and UserDict
import unittest
import UserDict
class BasicTestMappingProtocol(unittest.TestCase):
# This base class can be used to check that an object conforms to the
# mapping protocol
# Functions that can be useful to override to adapt to dictionary
# semantics
_tested_class = None # which class is being tested (overwrite in subclasses)
def _reference(self):
"""Return a dictionary of values which are invariant by storage
in the object under test."""
return {1:2, "key1":"value1", "key2":(1,2,3)}
def _empty_mapping(self):
"""Return an empty mapping object"""
return self._tested_class()
def _full_mapping(self, data):
"""Return a mapping object with the value contained in data
dictionary"""
x = self._empty_mapping()
for key, value in data.items():
x[key] = value
return x
def __init__(self, *args, **kw):
unittest.TestCase.__init__(self, *args, **kw)
self.reference = self._reference().copy()
# A (key, value) pair not in the mapping
key, value = self.reference.popitem()
self.other = {key:value}
# A (key, value) pair in the mapping
key, value = self.reference.popitem()
self.inmapping = {key:value}
self.reference[key] = value
def test_read(self):
# Test for read only operations on mapping
p = self._empty_mapping()
p1 = dict(p) #workaround for singleton objects
d = self._full_mapping(self.reference)
if d is p:
p = p1
#Indexing
for key, value in self.reference.items():
self.assertEqual(d[key], value)
knownkey = self.other.keys()[0]
self.failUnlessRaises(KeyError, lambda:d[knownkey])
#len
self.assertEqual(len(p), 0)
self.assertEqual(len(d), len(self.reference))
#has_key
for k in self.reference:
self.assert_(d.has_key(k))
self.assert_(k in d)
for k in self.other:
self.failIf(d.has_key(k))
self.failIf(k in d)
#cmp
self.assertEqual(cmp(p,p), 0)
self.assertEqual(cmp(d,d), 0)
self.assertEqual(cmp(p,d), -1)
self.assertEqual(cmp(d,p), 1)
#__non__zero__
if p: self.fail("Empty mapping must compare to False")
if not d: self.fail("Full mapping must compare to True")
# keys(), items(), iterkeys() ...
def check_iterandlist(iter, lst, ref):
self.assert_(hasattr(iter, 'next'))
self.assert_(hasattr(iter, '__iter__'))
x = list(iter)
self.assert_(set(x)==set(lst)==set(ref))
check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys())
check_iterandlist(iter(d), d.keys(), self.reference.keys())
check_iterandlist(d.itervalues(), d.values(), self.reference.values())
check_iterandlist(d.iteritems(), d.items(), self.reference.items())
#get
key, value = d.iteritems().next()
knownkey, knownvalue = self.other.iteritems().next()
self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.failIf(knownkey in d)
def test_write(self):
# Test for write operations on mapping
p = self._empty_mapping()
#Indexing
for key, value in self.reference.items():
p[key] = value
self.assertEqual(p[key], value)
for key in self.reference.keys():
del p[key]
self.failUnlessRaises(KeyError, lambda:p[key])
p = self._empty_mapping()
#update
p.update(self.reference)
self.assertEqual(dict(p), self.reference)
items = p.items()
p = self._empty_mapping()
p.update(items)
self.assertEqual(dict(p), self.reference)
d = self._full_mapping(self.reference)
#setdefault
key, value = d.iteritems().next()
knownkey, knownvalue = self.other.iteritems().next()
self.assertEqual(d.setdefault(key, knownvalue), value)
self.assertEqual(d[key], value)
self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
self.assertEqual(d[knownkey], knownvalue)
#pop
self.assertEqual(d.pop(knownkey), knownvalue)
self.failIf(knownkey in d)
self.assertRaises(KeyError, d.pop, knownkey)
default = 909
d[knownkey] = knownvalue
self.assertEqual(d.pop(knownkey, default), knownvalue)
self.failIf(knownkey in d)
self.assertEqual(d.pop(knownkey, default), default)
#popitem
key, value = d.popitem()
self.failIf(key in d)
self.assertEqual(value, self.reference[key])
p=self._empty_mapping()
self.assertRaises(KeyError, p.popitem)
def test_constructor(self):
self.assertEqual(self._empty_mapping(), self._empty_mapping())
def test_bool(self):
self.assert_(not self._empty_mapping())
self.assert_(self.reference)
self.assert_(bool(self._empty_mapping()) is False)
self.assert_(bool(self.reference) is True)
def test_keys(self):
d = self._empty_mapping()
self.assertEqual(d.keys(), [])
d = self.reference
self.assert_(self.inmapping.keys()[0] in d.keys())
self.assert_(self.other.keys()[0] not in d.keys())
self.assertRaises(TypeError, d.keys, None)
def test_values(self):
d = self._empty_mapping()
self.assertEqual(d.values(), [])
self.assertRaises(TypeError, d.values, None)
def test_items(self):
d = self._empty_mapping()
self.assertEqual(d.items(), [])
self.assertRaises(TypeError, d.items, None)
def test_len(self):
d = self._empty_mapping()
self.assertEqual(len(d), 0)
def test_getitem(self):
d = self.reference
self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0])
self.assertRaises(TypeError, d.__getitem__)
def test_update(self):
# mapping argument
d = self._empty_mapping()
d.update(self.other)
self.assertEqual(d.items(), self.other.items())
# No argument
d = self._empty_mapping()
d.update()
self.assertEqual(d, self._empty_mapping())
# item sequence
d = self._empty_mapping()
d.update(self.other.items())
self.assertEqual(d.items(), self.other.items())
# Iterator
d = self._empty_mapping()
d.update(self.other.iteritems())
self.assertEqual(d.items(), self.other.items())
# FIXME: Doesn't work with UserDict
# self.assertRaises((TypeError, AttributeError), d.update, None)
self.assertRaises((TypeError, AttributeError), d.update, 42)
outerself = self
class SimpleUserDict:
def __init__(self):
self.d = outerself.reference
def keys(self):
return self.d.keys()
def __getitem__(self, i):
return self.d[i]
d.clear()
d.update(SimpleUserDict())
i1 = d.items()
i2 = self.reference.items()
i1.sort()
i2.sort()
self.assertEqual(i1, i2)
class Exc(Exception): pass
d = self._empty_mapping()
class FailingUserDict:
def keys(self):
raise Exc
self.assertRaises(Exc, d.update, FailingUserDict())
d.clear()
class FailingUserDict:
def keys(self):
class BogonIter:
def __init__(self):
self.i = 1
def __iter__(self):
return self
def next(self):
if self.i:
self.i = 0
return 'a'
raise Exc
return BogonIter()
def __getitem__(self, key):
return key
self.assertRaises(Exc, d.update, FailingUserDict())
class FailingUserDict:
def keys(self):
class BogonIter:
def __init__(self):
self.i = ord('a')
def __iter__(self):
return self
def next(self):
if self.i <= ord('z'):
rtn = chr(self.i)
self.i += 1
return rtn
raise StopIteration
return BogonIter()
def __getitem__(self, key):
raise Exc
self.assertRaises(Exc, d.update, FailingUserDict())
d = self._empty_mapping()
class badseq(object):
def __iter__(self):
return self
def next(self):
raise Exc()
self.assertRaises(Exc, d.update, badseq())
self.assertRaises(ValueError, d.update, [(1, 2, 3)])
# no test_fromkeys or test_copy as both os.environ and selves don't support it
def test_get(self):
d = self._empty_mapping()
self.assert_(d.get(self.other.keys()[0]) is None)
self.assertEqual(d.get(self.other.keys()[0], 3), 3)
d = self.reference
self.assert_(d.get(self.other.keys()[0]) is None)
self.assertEqual(d.get(self.other.keys()[0], 3), 3)
self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0])
self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0])
self.assertRaises(TypeError, d.get)
self.assertRaises(TypeError, d.get, None, None, None)
def test_setdefault(self):
d = self._empty_mapping()
self.assertRaises(TypeError, d.setdefault)
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
self.assertRaises(TypeError, d.popitem, 42)
def test_pop(self):
d = self._empty_mapping()
k, v = self.inmapping.items()[0]
d[k] = v
self.assertRaises(KeyError, d.pop, self.other.keys()[0])
self.assertEqual(d.pop(k), v)
self.assertEqual(len(d), 0)
self.assertRaises(KeyError, d.pop, k)
class TestMappingProtocol(BasicTestMappingProtocol):
def test_constructor(self):
BasicTestMappingProtocol.test_constructor(self)
self.assert_(self._empty_mapping() is not self._empty_mapping())
self.assertEqual(self._tested_class(x=1, y=2), {"x": 1, "y": 2})
def test_bool(self):
BasicTestMappingProtocol.test_bool(self)
self.assert_(not self._empty_mapping())
self.assert_(self._full_mapping({"x": "y"}))
self.assert_(bool(self._empty_mapping()) is False)
self.assert_(bool(self._full_mapping({"x": "y"})) is True)
def test_keys(self):
BasicTestMappingProtocol.test_keys(self)
d = self._empty_mapping()
self.assertEqual(d.keys(), [])
d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys()
self.assert_('a' in k)
self.assert_('b' in k)
self.assert_('c' not in k)
def test_values(self):
BasicTestMappingProtocol.test_values(self)
d = self._full_mapping({1:2})
self.assertEqual(d.values(), [2])
def test_items(self):
BasicTestMappingProtocol.test_items(self)
d = self._full_mapping({1:2})
self.assertEqual(d.items(), [(1, 2)])
def test_has_key(self):
d = self._empty_mapping()
self.assert_(not d.has_key('a'))
d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys()
k.sort()
self.assertEqual(k, ['a', 'b'])
self.assertRaises(TypeError, d.has_key)
def test_contains(self):
d = self._empty_mapping()
self.assert_(not ('a' in d))
self.assert_('a' not in d)
d = self._full_mapping({'a': 1, 'b': 2})
self.assert_('a' in d)
self.assert_('b' in d)
self.assert_('c' not in d)
self.assertRaises(TypeError, d.__contains__)
def test_len(self):
BasicTestMappingProtocol.test_len(self)
d = self._full_mapping({'a': 1, 'b': 2})
self.assertEqual(len(d), 2)
def test_getitem(self):
BasicTestMappingProtocol.test_getitem(self)
d = self._full_mapping({'a': 1, 'b': 2})
self.assertEqual(d['a'], 1)
self.assertEqual(d['b'], 2)
d['c'] = 3
d['a'] = 4
self.assertEqual(d['c'], 3)
self.assertEqual(d['a'], 4)
del d['b']
self.assertEqual(d, {'a': 4, 'c': 3})
self.assertRaises(TypeError, d.__getitem__)
def test_clear(self):
d = self._full_mapping({1:1, 2:2, 3:3})
d.clear()
self.assertEqual(d, {})
self.assertRaises(TypeError, d.clear, None)
def test_update(self):
BasicTestMappingProtocol.test_update(self)
# mapping argument
d = self._empty_mapping()
d.update({1:100})
d.update({2:20})
d.update({1:1, 2:2, 3:3})
self.assertEqual(d, {1:1, 2:2, 3:3})
# no argument
d.update()
self.assertEqual(d, {1:1, 2:2, 3:3})
# keyword arguments
d = self._empty_mapping()
d.update(x=100)
d.update(y=20)
d.update(x=1, y=2, z=3)
self.assertEqual(d, {"x":1, "y":2, "z":3})
# item sequence
d = self._empty_mapping()
d.update([("x", 100), ("y", 20)])
self.assertEqual(d, {"x":100, "y":20})
# Both item sequence and keyword arguments
d = self._empty_mapping()
d.update([("x", 100), ("y", 20)], x=1, y=2)
self.assertEqual(d, {"x":1, "y":2})
# iterator
d = self._full_mapping({1:3, 2:4})
d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems())
self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
class SimpleUserDict:
def __init__(self):
self.d = {1:1, 2:2, 3:3}
def keys(self):
return self.d.keys()
def __getitem__(self, i):
return self.d[i]
d.clear()
d.update(SimpleUserDict())
self.assertEqual(d, {1:1, 2:2, 3:3})
def test_fromkeys(self):
self.assertEqual(self._tested_class.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = self._empty_mapping()
self.assert_(not(d.fromkeys('abc') is d))
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
self.assertEqual(d.fromkeys([]), {})
def g():
yield 1
self.assertEqual(d.fromkeys(g()), {1:None})
self.assertRaises(TypeError, {}.fromkeys, 3)
class dictlike(self._tested_class): pass
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
self.assert_(dictlike.fromkeys('a').__class__ is dictlike)
self.assert_(dictlike().fromkeys('a').__class__ is dictlike)
# FIXME: the following won't work with UserDict, because it's an old style class
# self.assert_(type(dictlike.fromkeys('a')) is dictlike)
class mydict(self._tested_class):
def __new__(cls):
return UserDict.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
# FIXME: the following won't work with UserDict, because it's an old style class
# self.assert_(isinstance(ud, UserDict.UserDict))
self.assertRaises(TypeError, dict.fromkeys)
class Exc(Exception): pass
class baddict1(self._tested_class):
def __init__(self):
raise Exc()
self.assertRaises(Exc, baddict1.fromkeys, [1])
class BadSeq(object):
def __iter__(self):
return self
def next(self):
raise Exc()
self.assertRaises(Exc, self._tested_class.fromkeys, BadSeq())
class baddict2(self._tested_class):
def __setitem__(self, key, value):
raise Exc()
self.assertRaises(Exc, baddict2.fromkeys, [1])
def test_copy(self):
d = self._full_mapping({1:1, 2:2, 3:3})
self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
d = self._empty_mapping()
self.assertEqual(d.copy(), d)
self.assert_(isinstance(d.copy(), d.__class__))
self.assertRaises(TypeError, d.copy, None)
def test_get(self):
BasicTestMappingProtocol.test_get(self)
d = self._empty_mapping()
self.assert_(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
d = self._full_mapping({'a' : 1, 'b' : 2})
self.assert_(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
self.assertEqual(d.get('a'), 1)
self.assertEqual(d.get('a', 3), 1)
def test_setdefault(self):
BasicTestMappingProtocol.test_setdefault(self)
d = self._empty_mapping()
self.assert_(d.setdefault('key0') is None)
d.setdefault('key0', [])
self.assert_(d.setdefault('key0') is None)
d.setdefault('key', []).append(3)
self.assertEqual(d['key'][0], 3)
d.setdefault('key', []).append(4)
self.assertEqual(len(d['key']), 2)
def test_popitem(self):
BasicTestMappingProtocol.test_popitem(self)
for copymode in -1, +1:
# -1: b has same structure as a
# +1: b is a.copy()
for log2size in range(12):
size = 2**log2size
a = self._empty_mapping()
b = self._empty_mapping()
for i in range(size):
a[repr(i)] = i
if copymode < 0:
b[repr(i)] = i
if copymode > 0:
b = a.copy()
for i in range(size):
ka, va = ta = a.popitem()
self.assertEqual(va, int(ka))
kb, vb = tb = b.popitem()
self.assertEqual(vb, int(kb))
self.assert_(not(copymode < 0 and ta != tb))
self.assert_(not a)
self.assert_(not b)
def test_pop(self):
BasicTestMappingProtocol.test_pop(self)
# Tests for pop with specified key
d = self._empty_mapping()
k, v = 'abc', 'def'
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
x = 4503599627370496L
y = 4503599627370496
h = self._full_mapping({x: 'anything', y: 'something else'})
self.assertEqual(h[x], h[y])
self.assertEqual(d.pop(k, v), v)
d[k] = v
self.assertEqual(d.pop(k, 1), v)
class TestHashMappingProtocol(TestMappingProtocol):
def test_getitem(self):
TestMappingProtocol.test_getitem(self)
class Exc(Exception): pass
class BadEq(object):
def __eq__(self, other):
raise Exc()
d = self._empty_mapping()
d[BadEq()] = 42
self.assertRaises(KeyError, d.__getitem__, 23)
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.__getitem__, x)
def test_fromkeys(self):
TestMappingProtocol.test_fromkeys(self)
class mydict(self._tested_class):
def __new__(cls):
return UserDict.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
self.assert_(isinstance(ud, UserDict.UserDict))
def test_pop(self):
TestMappingProtocol.test_pop(self)
class Exc(Exception): pass
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.pop, x)
def test_mutatingiteration(self):
d = self._empty_mapping()
d[1] = 1
try:
for i in d:
d[i+1] = 1
except RuntimeError:
pass
else:
self.fail("changing dict size during iteration doesn't raise Error")
def test_repr(self):
d = self._empty_mapping()
self.assertEqual(repr(d), '{}')
d[1] = 2
self.assertEqual(repr(d), '{1: 2}')
d = self._empty_mapping()
d[1] = d
self.assertEqual(repr(d), '{1: {...}}')
class Exc(Exception): pass
class BadRepr(object):
def __repr__(self):
raise Exc()
d = self._full_mapping({1: BadRepr()})
self.assertRaises(Exc, repr, d)
def test_le(self):
self.assert_(not (self._empty_mapping() < self._empty_mapping()))
self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L})))
class Exc(Exception): pass
class BadCmp(object):
def __eq__(self, other):
raise Exc()
d1 = self._full_mapping({BadCmp(): 1})
d2 = self._full_mapping({1: 1})
try:
d1 < d2
except Exc:
pass
else:
self.fail("< didn't raise Exc")
def test_setdefault(self):
TestMappingProtocol.test_setdefault(self)
class Exc(Exception): pass
class BadHash(object):
fail = False
def __hash__(self):
if self.fail:
raise Exc()
else:
return 42
d = self._empty_mapping()
x = BadHash()
d[x] = 42
x.fail = True
self.assertRaises(Exc, d.setdefault, x, [])
Index: test_os.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_os.py,v
retrieving revision 1.21
retrieving revision 1.22
diff -C2 -d -r1.21 -r1.22
*** test_os.py 18 Jan 2004 20:29:55 -0000 1.21
--- test_os.py 31 May 2004 16:29:04 -0000 1.22
***************
*** 206,212 ****
pass
! from test_userdict import TestMappingProtocol
! class EnvironTests(TestMappingProtocol):
"""check that os.environ object conform to mapping protocol"""
_tested_class = None
--- 206,212 ----
pass
! from test import mapping_tests
! class EnvironTests(mapping_tests.BasicTestMappingProtocol):
"""check that os.environ object conform to mapping protocol"""
_tested_class = None
Index: test_shelve.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_shelve.py,v
retrieving revision 1.6
retrieving revision 1.7
diff -C2 -d -r1.6 -r1.7
*** test_shelve.py 10 May 2003 07:36:55 -0000 1.6
--- test_shelve.py 31 May 2004 16:29:04 -0000 1.7
***************
*** 75,86 ****
! from test_userdict import TestMappingProtocol
! class TestShelveBase(TestMappingProtocol):
fn = "shelftemp.db"
counter = 0
def __init__(self, *args, **kw):
self._db = []
! TestMappingProtocol.__init__(self, *args, **kw)
_tested_class = shelve.Shelf
def _reference(self):
--- 75,86 ----
! from test import mapping_tests
! class TestShelveBase(mapping_tests.BasicTestMappingProtocol):
fn = "shelftemp.db"
counter = 0
def __init__(self, *args, **kw):
self._db = []
! mapping_tests.BasicTestMappingProtocol.__init__(self, *args, **kw)
_tested_class = shelve.Shelf
def _reference(self):
Index: test_types.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v
retrieving revision 1.59
retrieving revision 1.60
diff -C2 -d -r1.59 -r1.60
*** test_types.py 4 Mar 2004 08:25:44 -0000 1.59
--- test_types.py 31 May 2004 16:29:04 -0000 1.60
***************
*** 11,15 ****
if 0.0: raise TestFailed, '0.0 is true instead of false'
if '': raise TestFailed, '\'\' is true instead of false'
- if {}: raise TestFailed, '{} is true instead of false'
if not 1: raise TestFailed, '1 is false instead of true'
if not 1L: raise TestFailed, '1L is false instead of true'
--- 11,14 ----
***************
*** 216,446 ****
print '6.5.3 Lists [see test_list.py]'
- print '6.6 Mappings == Dictionaries'
- # calling built-in types without argument must return empty
- if dict() != {}: raise TestFailed,'dict() does not return {}'
- d = {}
- if d.keys() != []: raise TestFailed, '{}.keys()'
- if d.values() != []: raise TestFailed, '{}.values()'
- if d.items() != []: raise TestFailed, '{}.items()'
- if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
- if ('a' in d) != 0: raise TestFailed, "'a' in {}"
- if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
- if len(d) != 0: raise TestFailed, 'len({})'
- d = {'a': 1, 'b': 2}
- if len(d) != 2: raise TestFailed, 'len(dict)'
- k = d.keys()
- k.sort()
- if k != ['a', 'b']: raise TestFailed, 'dict keys()'
- if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
- else: raise TestFailed, 'dict keys()'
- if 'a' in d and 'b' in d and 'c' not in d: pass
- else: raise TestFailed, 'dict keys() # in/not in version'
- if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
- d['c'] = 3
- d['a'] = 4
- if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
- del d['b']
- if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
- # dict.clear()
- d = {1:1, 2:2, 3:3}
- d.clear()
- if d != {}: raise TestFailed, 'dict clear'
- # dict.update()
- d.update({1:100})
- d.update({2:20})
- d.update({1:1, 2:2, 3:3})
- if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
- d.clear()
- try: d.update(None)
- except (TypeError, AttributeError): pass
- else: raise TestFailed, 'dict.update(None), AttributeError expected'
- class SimpleUserDict:
- def __init__(self):
- self.d = {1:1, 2:2, 3:3}
- def keys(self):
- return self.d.keys()
- def __getitem__(self, i):
- return self.d[i]
- d.update(SimpleUserDict())
- if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
- d.clear()
- class FailingUserDict:
- def keys(self):
- raise ValueError
- try: d.update(FailingUserDict())
- except ValueError: pass
- else: raise TestFailed, 'dict.keys() expected ValueError'
- class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __iter__(self):
- raise ValueError
- return BogonIter()
- try: d.update(FailingUserDict())
- except ValueError: pass
- else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
- class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __init__(self):
- self.i = 1
- def __iter__(self):
- return self
- def next(self):
- if self.i:
- self.i = 0
- return 'a'
- raise ValueError
- return BogonIter()
- def __getitem__(self, key):
- return key
- try: d.update(FailingUserDict())
- except ValueError: pass
- else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
- class FailingUserDict:
- def keys(self):
- class BogonIter:
- def __init__(self):
- self.i = ord('a')
- def __iter__(self):
- return self
- def next(self):
- if self.i <= ord('z'):
- rtn = chr(self.i)
- self.i += 1
- return rtn
- raise StopIteration
- return BogonIter()
- def __getitem__(self, key):
- raise ValueError
- try: d.update(FailingUserDict())
- except ValueError: pass
- else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
- # dict.fromkeys()
- if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
- raise TestFailed, 'dict.fromkeys did not work as a class method'
- d = {}
- if d.fromkeys('abc') is d:
- raise TestFailed, 'dict.fromkeys did not return a new dict'
- if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
- raise TestFailed, 'dict.fromkeys failed with default value'
- if d.fromkeys((4,5),0) != {4:0, 5:0}:
- raise TestFailed, 'dict.fromkeys failed with specified value'
- if d.fromkeys([]) != {}:
- raise TestFailed, 'dict.fromkeys failed with null sequence'
- def g():
- yield 1
- if d.fromkeys(g()) != {1:None}:
- raise TestFailed, 'dict.fromkeys failed with a generator'
- try: {}.fromkeys(3)
- except TypeError: pass
- else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
- class dictlike(dict): pass
- if dictlike.fromkeys('a') != {'a':None}:
- raise TestFailed, 'dictsubclass.fromkeys did not inherit'
- if dictlike().fromkeys('a') != {'a':None}:
- raise TestFailed, 'dictsubclass.fromkeys did not inherit'
- if type(dictlike.fromkeys('a')) is not dictlike:
- raise TestFailed, 'dictsubclass.fromkeys created wrong type'
- if type(dictlike().fromkeys('a')) is not dictlike:
- raise TestFailed, 'dictsubclass.fromkeys created wrong type'
- from UserDict import UserDict
- class mydict(dict):
- def __new__(cls):
- return UserDict()
- ud = mydict.fromkeys('ab')
- if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
- raise TestFailed, 'fromkeys did not instantiate using __new__'
- # dict.copy()
- d = {1:1, 2:2, 3:3}
- if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
- if {}.copy() != {}: raise TestFailed, 'empty dict copy'
- # dict.get()
- d = {}
- if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
- if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
- d = {'a' : 1, 'b' : 2}
- if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
- if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
- if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
- if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
- # dict.setdefault()
- d = {}
- if d.setdefault('key0') is not None:
- raise TestFailed, 'missing {} setdefault, no 2nd arg'
- if d.setdefault('key0') is not None:
- raise TestFailed, 'present {} setdefault, no 2nd arg'
- d.setdefault('key', []).append(3)
- if d['key'][0] != 3:
- raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
- d.setdefault('key', []).append(4)
- if len(d['key']) != 2:
- raise TestFailed, 'present {} setdefault, w/ 2nd arg'
- # dict.popitem()
- for copymode in -1, +1:
- # -1: b has same structure as a
- # +1: b is a.copy()
- for log2size in range(12):
- size = 2**log2size
- a = {}
- b = {}
- for i in range(size):
- a[repr(i)] = i
- if copymode < 0:
- b[repr(i)] = i
- if copymode > 0:
- b = a.copy()
- for i in range(size):
- ka, va = ta = a.popitem()
- if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
- kb, vb = tb = b.popitem()
- if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
- if copymode < 0 and ta != tb:
- raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
- str(ta), str(tb))
- if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
- if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
-
- d.clear()
- try: d.popitem()
- except KeyError: pass
- else: raise TestFailed, "{}.popitem doesn't raise KeyError"
-
- # Tests for pop with specified key
- d.clear()
- k, v = 'abc', 'def'
- d[k] = v
- try: d.pop('ghi')
- except KeyError: pass
- else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
-
- if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
- if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
-
- try: d.pop(k)
- except KeyError: pass
- else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
-
- # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
- # see SF bug #689659
- x = 4503599627370496L
- y = 4503599627370496
- h = {x: 'anything', y: 'something else'}
- if h[x] != h[y]:
- raise TestFailed, "long/int key should match"
-
- if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
- d[k] = v
- if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
-
- d[1] = 1
- try:
- for i in d:
- d[i+1] = 1
- except RuntimeError:
- pass
- else:
- raise TestFailed, "changing dict size during iteration doesn't raise Error"
try: type(1, 2)
--- 215,220 ----
print '6.5.3 Lists [see test_list.py]'
+ print '6.6 Mappings == Dictionaries [see test_dict.py]'
try: type(1, 2)
Index: test_userdict.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_userdict.py,v
retrieving revision 1.18
retrieving revision 1.19
diff -C2 -d -r1.18 -r1.19
*** test_userdict.py 4 Mar 2004 08:25:44 -0000 1.18
--- test_userdict.py 31 May 2004 16:29:04 -0000 1.19
***************
*** 1,125 ****
# Check every path through every method of UserDict
! import test.test_support, unittest
import UserDict
- class TestMappingProtocol(unittest.TestCase):
- # This base class can be used to check that an object conforms to the
- # mapping protocol
-
- # Functions that can be useful to override to adapt to dictionary
- # semantics
- _tested_class = dict # which class is being tested
-
- def _reference(self):
- """Return a dictionary of values which are invariant by storage
- in the object under test."""
- return {1:2, "key1":"value1", "key2":(1,2,3)}
- def _empty_mapping(self):
- """Return an empty mapping object"""
- return self._tested_class()
- def _full_mapping(self, data):
- """Return a mapping object with the value contained in data
- dictionary"""
- x = self._empty_mapping()
- for key, value in data.items():
- x[key] = value
- return x
-
- def __init__(self, *args, **kw):
- unittest.TestCase.__init__(self, *args, **kw)
- self.reference = self._reference().copy()
- key, value = self.reference.popitem()
- self.other = {key:value}
-
- def test_read(self):
- # Test for read only operations on mapping
- p = self._empty_mapping()
- p1 = dict(p) #workaround for singleton objects
- d = self._full_mapping(self.reference)
- if d is p:
- p = p1
- #Indexing
- for key, value in self.reference.items():
- self.assertEqual(d[key], value)
- knownkey = self.other.keys()[0]
- self.failUnlessRaises(KeyError, lambda:d[knownkey])
- #len
- self.assertEqual(len(p), 0)
- self.assertEqual(len(d), len(self.reference))
- #has_key
- for k in self.reference:
- self.assert_(d.has_key(k))
- self.assert_(k in d)
- for k in self.other:
- self.failIf(d.has_key(k))
- self.failIf(k in d)
- #cmp
- self.assertEqual(cmp(p,p), 0)
- self.assertEqual(cmp(d,d), 0)
- self.assertEqual(cmp(p,d), -1)
- self.assertEqual(cmp(d,p), 1)
- #__non__zero__
- if p: self.fail("Empty mapping must compare to False")
- if not d: self.fail("Full mapping must compare to True")
- # keys(), items(), iterkeys() ...
- def check_iterandlist(iter, lst, ref):
- self.assert_(hasattr(iter, 'next'))
- self.assert_(hasattr(iter, '__iter__'))
- x = list(iter)
- self.assert_(set(x)==set(lst)==set(ref))
- check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys())
- check_iterandlist(iter(d), d.keys(), self.reference.keys())
- check_iterandlist(d.itervalues(), d.values(), self.reference.values())
- check_iterandlist(d.iteritems(), d.items(), self.reference.items())
- #get
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
- self.assertEqual(d.get(key, knownvalue), value)
- self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
- self.failIf(knownkey in d)
-
- def test_write(self):
- # Test for write operations on mapping
- p = self._empty_mapping()
- #Indexing
- for key, value in self.reference.items():
- p[key] = value
- self.assertEqual(p[key], value)
- for key in self.reference.keys():
- del p[key]
- self.failUnlessRaises(KeyError, lambda:p[key])
- p = self._empty_mapping()
- #update
- p.update(self.reference)
- self.assertEqual(dict(p), self.reference)
- items = p.items()
- p = self._empty_mapping()
- p.update(items)
- self.assertEqual(dict(p), self.reference)
- d = self._full_mapping(self.reference)
- #setdefault
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
- self.assertEqual(d.setdefault(key, knownvalue), value)
- self.assertEqual(d[key], value)
- self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
- self.assertEqual(d[knownkey], knownvalue)
- #pop
- self.assertEqual(d.pop(knownkey), knownvalue)
- self.failIf(knownkey in d)
- self.assertRaises(KeyError, d.pop, knownkey)
- default = 909
- d[knownkey] = knownvalue
- self.assertEqual(d.pop(knownkey, default), knownvalue)
- self.failIf(knownkey in d)
- self.assertEqual(d.pop(knownkey, default), default)
- #popitem
- key, value = d.popitem()
- self.failIf(key in d)
- self.assertEqual(value, self.reference[key])
- p=self._empty_mapping()
- self.assertRaises(KeyError, p.popitem)
-
d0 = {}
d1 = {"one": 1}
--- 1,8 ----
# Check every path through every method of UserDict
! import unittest
! from test import test_support, mapping_tests
import UserDict
d0 = {}
d1 = {"one": 1}
***************
*** 129,133 ****
d5 = {"one": 1, "two": 1}
! class UserDictTest(TestMappingProtocol):
_tested_class = UserDict.IterableUserDict
--- 12,16 ----
d5 = {"one": 1, "two": 1}
! class UserDictTest(mapping_tests.TestHashMappingProtocol):
_tested_class = UserDict.IterableUserDict
***************
*** 274,280 ****
Used to test and demonstrate DictMixin
"""
! def __init__(self):
self.keylist = []
self.valuelist = []
def __getitem__(self, key):
try:
--- 157,168 ----
Used to test and demonstrate DictMixin
"""
! def __init__(self, other=None, **kwargs):
self.keylist = []
self.valuelist = []
+ if other is not None:
+ for (key, value) in other:
+ self[key] = value
+ for (key, value) in kwargs.iteritems():
+ self[key] = value
def __getitem__(self, key):
try:
***************
*** 299,304 ****
def keys(self):
return list(self.keylist)
! class UserDictMixinTest(TestMappingProtocol):
_tested_class = SeqDict
--- 187,203 ----
def keys(self):
return list(self.keylist)
+ def copy(self):
+ d = self.__class__()
+ for key, value in self.iteritems():
+ d[key] = value
+ return d
+ def fromkeys(cls, keys, value=None):
+ d = cls()
+ for key in keys:
+ d[key] = value
+ return d
+ fromkeys = classmethod(fromkeys)
! class UserDictMixinTest(mapping_tests.TestMappingProtocol):
_tested_class = SeqDict
***************
*** 394,399 ****
def test_main():
! test.test_support.run_unittest(
! TestMappingProtocol,
UserDictTest,
UserDictMixinTest
--- 293,297 ----
def test_main():
! test_support.run_unittest(
UserDictTest,
UserDictMixinTest
Index: test_weakref.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/test/test_weakref.py,v
retrieving revision 1.38
retrieving revision 1.39
diff -C2 -d -r1.38 -r1.39
*** test_weakref.py 13 Feb 2004 19:21:57 -0000 1.38
--- test_weakref.py 31 May 2004 16:29:04 -0000 1.39
***************
*** 913,919 ****
self.assertEqual(count, 2)
! from test_userdict import TestMappingProtocol
! class WeakValueDictionaryTestCase(TestMappingProtocol):
"""Check that WeakValueDictionary conforms to the mapping protocol"""
__ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
--- 913,919 ----
self.assertEqual(count, 2)
! from test import mapping_tests
! class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
"""Check that WeakValueDictionary conforms to the mapping protocol"""
__ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
***************
*** 922,926 ****
return self.__ref.copy()
! class WeakKeyDictionaryTestCase(TestMappingProtocol):
"""Check that WeakKeyDictionary conforms to the mapping protocol"""
__ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
--- 922,926 ----
return self.__ref.copy()
! class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
"""Check that WeakKeyDictionary conforms to the mapping protocol"""
__ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
[View Less]
1
0

python/dist/src/Lib/test/output test_types, 1.3, 1.4
by doerwalter@users.sourceforge.net May 31, 2004
by doerwalter@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Lib/test/output
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv3029/Lib/test/output
Modified Files:
test_types
Log Message:
Port the dictionary tests from test_types.py to unittest. Collect as much
mapping tests as possible in mapping_test.py and reuse the tests in
test_dict.py, test_userdict.py, test_weakref.py, test_os.py and test_shelve.py.
>From SF patch #736962.
Index: test_types
=======================================================…
[View More]============
RCS file: /cvsroot/python/python/dist/src/Lib/test/output/test_types,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** test_types 8 Dec 2003 11:38:45 -0000 1.3
--- test_types 31 May 2004 16:29:04 -0000 1.4
***************
*** 12,15 ****
6.5.2 Tuples [see test_tuple.py]
6.5.3 Lists [see test_list.py]
! 6.6 Mappings == Dictionaries
Buffers
--- 12,15 ----
6.5.2 Tuples [see test_tuple.py]
6.5.3 Lists [see test_list.py]
! 6.6 Mappings == Dictionaries [see test_dict.py]
Buffers
[View Less]
1
0

python/dist/src/Lib/distutils filelist.py, 1.15, 1.16
by doerwalter@users.sourceforge.net May 31, 2004
by doerwalter@users.sourceforge.net May 31, 2004
May 31, 2004
Update of /cvsroot/python/python/dist/src/Lib/distutils
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21393/Lib/distutils
Modified Files:
filelist.py
Log Message:
Fix typo (from SF bug #962602)
Index: filelist.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/distutils/filelist.py,v
retrieving revision 1.15
retrieving revision 1.16
diff -C2 -d -r1.15 -r1.16
*** filelist.py 19 Nov 2002 13:12:27 -0000 1.15
--- …
[View More]filelist.py 31 May 2004 15:12:27 -0000 1.16
***************
*** 167,171 ****
for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir):
! log.warn(("warngin: no files found matching '%s' " +
"under directory '%s'"),
pattern, dir)
--- 167,171 ----
for pattern in patterns:
if not self.include_pattern(pattern, prefix=dir):
! log.warn(("warning: no files found matching '%s' " +
"under directory '%s'"),
pattern, dir)
[View Less]
1
0

May 31, 2004
1
0

[Python-checkins] python/dist/src/Doc/whatsnew whatsnew24.tex, 1.47, 1.48
by rhettinger@users.sourceforge.net May 30, 2004
by rhettinger@users.sourceforge.net May 30, 2004
May 30, 2004
Update of /cvsroot/python/python/dist/src/Doc/whatsnew
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1425
Modified Files:
whatsnew24.tex
Log Message:
Add weakref support to sockets and re pattern objects.
Index: whatsnew24.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew24.tex,v
retrieving revision 1.47
retrieving revision 1.48
diff -C2 -d -r1.47 -r1.48
*** whatsnew24.tex 20 May 2004 22:59:26 -…
[View More]0000 1.47
--- whatsnew24.tex 31 May 2004 03:15:02 -0000 1.48
***************
*** 559,562 ****
--- 559,566 ----
regular expression pattern \var{A} will be tested against the string; if
the group didn't match, the pattern \var{B} will be used instead.
+
+ \item The \module{weakref} module now supports a wider variety of objects
+ including Python functions, class instances, sets, frozensets, deques,
+ arrays, files, sockets, and regular expression pattern objects.
\end{itemize}
[View Less]
1
0

May 30, 2004
Update of /cvsroot/python/python/dist/src/Lib
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv432/Lib
Modified Files:
socket.py
Log Message:
Add weakref support to sockets and re pattern objects.
Index: socket.py
===================================================================
RCS file: /cvsroot/python/python/dist/src/Lib/socket.py,v
retrieving revision 1.43
retrieving revision 1.44
diff -C2 -d -r1.43 -r1.44
*** socket.py 28 Mar 2004 02:20:44 -0000 1.43
--- socket.py 31 May 2004 …
[View More]03:09:22 -0000 1.44
***************
*** 148,152 ****
__doc__ = _realsocket.__doc__
! __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom"]
def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
--- 148,153 ----
__doc__ = _realsocket.__doc__
! __slots__ = ["_sock", "send", "recv", "sendto", "recvfrom",
! "__weakref__"]
def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _sock=None):
[View Less]
1
0