PK£žC8Ûè;; nose/case.pyc;ò è’*Fc@sjdZdkZdkZdklZeieƒZdeifd„ƒYZ deifd„ƒYZ dS(sÞnose unittest.TestCase subclasses. It is not necessary to subclass these classes when writing tests; they are used internally by nose.loader.TestLoader to create test cases from test functions and methods in test classes. N(stry_runsFunctionTestCasecBsetZdZhZeeeed„Zd„Zd„Zd„Zd„Z d„Z e Z d„Z RS(s$TestCase wrapper for functional tests. Don't use this class directly; it is used internally in nose to create test cases for functional tests. This class is very similar to unittest.FunctionTestCase, with a few extensions: * The test descriptions are disambiguated by including the full module path when a test with a similar name has been seen in the test run. * It allows setup and teardown functions to be defined as attributes of the test function. A convenient way to set this up is via the provided with_setup decorator: def setup_func(): # ... def teardown_func(): # ... @with_setup(setup_func, teardown_func) def test_something(): # ... cCsA||_||_||_||_||_ti i |ƒdS(N( stestFuncsselfssetUps setUpFuncstearDowns tearDownFuncs descriptions fromDirectorysunittestsTestCases__init__(sselfstestFuncssetUpstearDowns descriptions fromDirectory((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pys__init__'s      cCst|ƒSdS(N(sstrsself(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysid0scCs|iƒdS(N(sselfstestFunc(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysrunTest3scCs;|io|iƒn dddf}t|i|ƒdS(s=Run any setup function attached to the test function ssetupssetUps setUpFuncN(sselfs setUpFuncsnamesstry_runstestFunc(sselfsnames((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pyssetUp6s  cCs;|io|iƒn dddf}t|i|ƒdS(s@Run any teardown function attached to the test function steardownstearDowns tearDownFuncN(sselfs tearDownFuncsnamesstry_runstestFunc(sselfsnames((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pystearDown?s  cCs”t|idƒo|ii}n |ii}d|ii|f}|ii|ƒo |i t j od|i |f}nt |i|<|SdS(Nscompat_func_names%s.%ss%s: %s( shasattrsselfstestFuncscompat_func_namesnames__name__s __module__s_seenshas_keys fromDirectorysNonesTrue(sselfsname((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pys__str__Hs # cCsdS(N((sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysshortDescriptionWs( s__name__s __module__s__doc__s_seensNones__init__sidsrunTestssetUpstearDowns__str__s__repr__sshortDescription(((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysFunctionTestCase s    sMethodTestCasecBs\tZdZeed„Zd„Zd„Zd„Zd„Zd„Z d„Z d„Z RS( s5Test case that wraps one method in a test class. cGs||_||_||_|iƒ|_|tjot|i|ƒ|_n ||_||_ t i d|i|i ƒt i i|ƒdS(NsTest case: %s%s(sclssselfsmethods method_descs testInstancescasesNonesgetattrstestCasesargslogsdebugsunittestsTestCases__init__(sselfsclssmethods method_descscasesarg((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pys__init__^s      cCs|iƒSdS(N(sselfsid(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pys__str__kscCsO|itj o |i}n |i}|iod||if}n|SdS(Ns%s:%s(sselfs method_descsNonesdescsmethodsarg(sselfsdesc((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysdescns    cCs'd|ii|ii|iƒfSdS(Ns%s.%s.%s(sselfsclss __module__s__name__sdesc(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysidwscCs ddf}t|i|ƒdS(s]Run any setup method declared in the test class to which this method belongs ssetupssetUpN(snamesstry_runsselfs testInstance(sselfsnames((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pyssetUp|s cCs|i|iŒdS(N(sselfstestCasesarg(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysrunTestƒscCs4|itj o ddf}t|i|ƒndS(s`Run any teardown method declared in the test class to which this method belongs steardownstearDownN(sselfs testInstancesNonesnamesstry_run(sselfsnames((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pystearDown†s cCsB|iitj o'd|ii|ii|iifSntSdS(Ns (%s.%s) "%s"(sselfstestCases__doc__sNonesclss __module__s__name__(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysshortDescriptionŽs'( s__name__s __module__s__doc__sNones__init__s__str__sdescsidssetUpsrunTeststearDownsshortDescription(((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pysMethodTestCase[s      ( s__doc__sloggingsunittests nose.utilstry_runs getLoggers__name__slogsTestCasesFunctionTestCasesMethodTestCase(sloggingslogsunittestsFunctionTestCasesMethodTestCasestry_run((s-build/bdist.darwin-8.0.1-x86/egg/nose/case.pys?s    PPK£žC8`8¨}}nose/importer.pyc;ò è’*Fc@sdZdklZdkZdkZdkZdklZlZl Z l Z ei e ƒZ hZd„Zd„Zd„ZdS(s:Implements an importer that looks only in specific path (ignoring sys.path), and uses a per-path cache in addition to sys.modules. This is necessary because test modules in different directories frequently have the same names, which means that the first loaded would mask the rest when using the builtin importer. (s generatorsN(s find_modules load_modules acquire_locks release_lockcCs¦tid|ƒ| odSntii|ƒ}|otiitii|dƒƒot|ƒn9|t ij o'tid|ƒt ii d|ƒndS(skEnsure that the path, or the root of the current package (if path is in a package) is in sys.path. s Add path %sNs __init__.pysinsert %s into sys.pathi( slogsdebugspathsossdirnamesparentsexistssjoinsadd_pathssyssinsert(spathsparent((s1build/bdist.darwin-8.0.1-x86/egg/nose/importer.pysadd_paths)cCsHtid|||iƒ|djoti|Sn|iox|D]}t |ƒqFWngi }|D]!}|t j o||ƒqlql~}t idi|ƒhƒ}|i|ƒo ||Sn|idƒ} d}t } } }xM| D]E}|djo |}nd||f}|i|ƒo||} n½zœtƒtid|||ƒt||ƒ\}}}tii|ƒ}|ot|dƒo#t ii!|i"d ƒ} t }nZt|d ƒo1t ii!|i%ƒ}t ii'|ƒ\} }nt t t f\} }}t ii!|ƒ}t ii'|ƒ\}} | |jo1tid || ||| ƒ|||<} w÷q•ti|=ntid ||ƒt+||||ƒ} tid ||| ƒ| ||> assert 2 == 4, "assert 2 is 4" Please note that dotted names are not expanded, and callables are not called in the expansion. Setuptools integration ====================== nose may be used with the setuptools_ test command. Simply specify nose.collector as the test suite in your setup file:: setup ( # ... test_suite = 'nose.collector' ) Then to find and run tests, you can run:: python setup.py test When running under setuptools, you can configure nose settings via the environment variables detailed in the nosetests script usage message. Please note that when run under the setuptools test command, some plugins will not be available, including the builtin coverage, profiler, and missed test plugins. nose also includes its own setuptools command, `nosetests`, that provides support for all plugins and command line options, as well as configuration using the setup.cfg file. See nose.commands_ for more information about the `nosetests` command. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _nose.commands: #commands .. _Writing plugins: http://code.google.com/p/python-nose/wiki/WritingPlugins Writing tests ------------- As with py.test, nose tests need not be subclasses of `unittest.TestCase`. Any function or class that matches the configured testMatch regular expression (`(?:^|[\\b_\\.-])[Tt]est)` by default) and lives in a module that also matches that expression will be run as a test. For the sake of compatibility with legacy unittest test cases, nose will also load tests from `unittest.TestCase` subclasses just like unittest does. Like py.test, functional tests will be run in the order in which they appear in the module file. TestCase derived tests and other test classes are run in alphabetical order. Fixtures ======== nose supports fixtures (setup and teardown methods) at the package, module, and test level. As with py.test or unittest fixtures, setup always runs before any test (or collection of tests for test packages and modules); teardown runs if setup has completed successfully, whether or not the test or tests pass. For more detail on fixtures at each level, see below. Test packages ============= nose allows tests to be grouped into test packages. This allows package-level setup; for instance, if you need to create a test database or other data fixture for your tests, you may create it in package setup and remove it in package teardown once per test run, rather than having to create and tear it down once per test module or test case. To create package-level setup and teardown methods, define setup and/or teardown functions in the `__init__.py` of a test package. Setup methods may be named `setup`, `setup_package`, `setUp`, or `setUpPackage`; teardown may be named `teardown`, `teardown_package`, `tearDown` or `tearDownPackage`. Execution of tests in a test package begins as soon as the first test module is loaded from the test package. Test modules ============ A test module is a python module that matches the testMatch regular expression. Test modules offer module-level setup and teardown; define the method `setup`, `setup_module`, `setUp` or `setUpModule` for setup, `teardown`, `teardown_module`, or `tearDownModule` for teardown. Execution of tests in a test module begins after all tests are collected. Test classes ============ A test class is a class defined in a test module that is either a subclass of `unittest.TestCase`, or matches testMatch. Test classes that don't descend from `unittest.TestCase` are run in the same way as those that do: methods in the class that match testMatch are discovered, and a test case constructed to run each with a fresh instance of the test class. Like `unittest.TestCase` subclasses, other test classes may define setUp and tearDown methods that will be run before and after each test method. Test functions ============== Any function in a test module that matches testMatch will be wrapped in a `FunctionTestCase` and run as a test. The simplest possible failing test is therefore:: def test(): assert False And the simplest passing test:: def test(): pass Test functions may define setup and/or teardown attributes, which will be run before and after the test function, respectively. A convenient way to do this, especially when several test functions in the same module need the same setup, is to use the provided with_setup decorator:: def setup_func(): # ... def teardown_func(): # ... @with_setup(setup_func, teardown_func) def test(): # ... For python 2.3, add the attributes by calling the decorator function like so:: def test(): # ... test = with_setup(setup_func, teardown_func)(test) or by direct assignment:: test.setup = setup_func test.teardown = teardown_func Please note that `with_setup` is useful *only* for test functions, not for test methods in TestCase subclasses or other test classes. For those cases, define `setUp` and `tearDown` methods in the class. Test generators =============== nose supports test functions and methods that are generators. A simple example from nose's selftest suite is probably the best explanation:: def test_evens(): for i in range(0, 5): yield check_even, i, i*3 def check_even(n, nn): assert n % 2 == 0 or nn % 2 == 0 This will result in 4 tests. nose will iterate the generator, creating a function test case wrapper for each tuple it yields. As in the example, test generators must yield tuples, the first element of which must be a callable and the remaining elements the arguments to be passed to the callable. Setup and teardown functions may be used with test generators. The setup and teardown attributes must be attached to the generator function:: @with_setup(setup_func, teardown_func) def test_generator(): ... yield func, arg, arg ... The setup and teardown functions will be executed for each test that the generator returns. For generator methods, the setUp and tearDown methods of the class (if any) will be run before and after each generated test case. Please note that method generators *are not* supported in `unittest.TestCase` subclasses. Finding and running tests ------------------------- nose, by default, follows a few simple rules for test discovery. * If it looks like a test, it's a test. Names of directories, modules, classes and functions are compared against the testMatch regular expression, and those that match are considered tests. Any class that is a `unittest.TestCase` subclass is also collected, so long as it is inside of a module that looks like a test. * Directories that don't look like tests and aren't packages are not inspected. * Packages are always inspected, but they are only collected if they look like tests. This means that you can include your tests inside of your packages (somepackage/tests) and nose will collect the tests without running package code inappropriately. * When a project appears to have library and test code organized into separate directories, library directories are examined first. * When nose imports a module, it adds that module's directory to sys.path; when the module is inside of a package, like package.module, it will be loaded as package.module and the directory of *package* will be added to sys.path. Be aware that plugins and command line options can change any of those rules. Testing tools ------------- The nose.tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in `unittest.TestCase` (only spelled in pep08 fashion, so assert_equal rather than assertEqual). See `nose.tools`_ for a complete list. .. _nose.tools: http://code.google.com/p/python-nose/wiki/TestingTools About the name -------------- * nose is the least silly short synonym for discover in the dictionary.com thesaurus that does not contain the word 'spy'. * Pythons have noses * The nose knows where to find your tests * Nose Obviates Suite Employment Contact the author ------------------ You can email me at jpellerin+nose at gmail dot com. To report bugs, ask questions, or request features, please use the *issues* tab at the Google code site: http://code.google.com/p/python-nose/issues/list. Patches are welcome! Similar test runners -------------------- nose was inspired mainly by py.test_, which is a great test runner, but formerly was not all that easy to install, and is not based on unittest. Test suites written for use with nose should work equally well with py.test, and vice versa, except for the differences in output capture and command line arguments for the respective tools. .. _py.test: http://codespeak.net/py/current/doc/test.html License and copyright --------------------- nose is copyright Jason Pellerin 2005-2007 This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ from nose.core import TestCollector, collector, configure, main, run, \ run_exit, runmodule from nose.exc import SkipTest, DeprecatedTest from nose.loader import TestLoader from nose.suite import LazySuite from nose.result import TextTestResult from nose.tools import with_setup # backwards compatibility from nose.util import file_like, split_test_name, test_address __author__ = 'Jason Pellerin' __versioninfo__ = (0, 9, 3) __version__ = '.'.join(map(str, __versioninfo__)) __all__ = [ 'TextTestResult', 'LazySuite', 'SkipTest', 'DeprecatedTest', 'TestCollector', 'TestLoader', 'collector', 'configure', 'main', 'run', 'run_exit', 'runmodule', 'with_setup', 'file_like', 'split_test_name', 'test_address' ] PK••6 ]Ø9nose/inspector.py"""Simple traceback introspection. Used to add additional information to AssertionErrors in tests, so that failure messages may be more informative. """ import exceptions import inspect import logging import re import sys import textwrap import tokenize import traceback try: from cStringIO import StringIO except ImportError: from StringIO import StringIO log = logging.getLogger(__name__) def inspect_traceback(tb): """Inspect a traceback and its frame, returning source for the expression where the exception was raised, with simple variable replacement performed and the line on which the exception was raised marked with '>>' """ log.debug('inspect traceback %s', tb) # we only want the innermost frame, where the exception was raised while tb.tb_next: tb = tb.tb_next frame = tb.tb_frame lines, exc_line = tbsource(tb) # figure out the set of lines to grab. inspect_lines, mark_line = find_inspectable_lines(lines, exc_line) src = StringIO(textwrap.dedent(''.join(inspect_lines))) exp = Expander(frame.f_locals, frame.f_globals) while inspect_lines: try: tokenize.tokenize(src.readline, exp) except tokenize.TokenError, e: # this can happen if our inspectable region happens to butt up # against the end of a construct like a docstring with the closing # """ on separate line log.debug("Tokenizer error: %s", e) inspect_lines.pop(0) mark_line -= 1 src = StringIO(textwrap.dedent(''.join(inspect_lines))) exp = Expander(frame.f_locals, frame.f_globals) continue break padded = [] if exp.expanded_source: exp_lines = exp.expanded_source.split('\n') ep = 0 for line in exp_lines: if ep == mark_line: padded.append('>> ' + line) else: padded.append(' ' + line) ep += 1 return '\n'.join(padded) def tbsource(tb, context=6): """Get source from a traceback object. A tuple of two things is returned: a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line. NOTE: This is adapted from inspect.py in the python 2.4 standard library, since a bug in the 2.3 version of inspect prevents it from correctly locating source lines in a traceback frame. """ lineno = tb.tb_lineno frame = tb.tb_frame if context > 0: start = lineno - 1 - context//2 log.debug("lineno: %s start: %s", lineno, start) try: lines, dummy = inspect.findsource(frame) except IOError: lines = index = None else: all_lines = lines start = max(start, 1) start = max(0, min(start, len(lines) - context)) lines = lines[start:start+context] index = lineno - 1 - start # python 2.5 compat: if previous line ends in a continuation, # decrement start by 1 to match 2.4 behavior if sys.version_info >= (2, 5) and index > 0: while lines[index-1].strip().endswith('\\'): start -= 1 lines = all_lines[start:start+context] else: lines = index = None log.debug("tbsource lines '''%s''' around index %s", lines, index) return (lines, index) def find_inspectable_lines(lines, pos): """Find lines in home that are inspectable. Walk back from the err line up to 3 lines, but don't walk back over changes in indent level. Walk forward up to 3 lines, counting \ separated lines as 1. Don't walk over changes in indent level (unless part of an extended line) """ cnt = re.compile(r'\\[\s\n]*$') df = re.compile(r':[\s\n]*$') ind = re.compile(r'^(\s*)') toinspect = [] home = lines[pos] home_indent = ind.match(home).groups()[0] before = lines[max(pos-3, 0):pos] before.reverse() after = lines[pos+1:min(pos+4, len(lines))] for line in before: if ind.match(line).groups()[0] == home_indent: toinspect.append(line) else: break toinspect.reverse() toinspect.append(home) home_pos = len(toinspect)-1 continued = cnt.search(home) for line in after: if ((continued or ind.match(line).groups()[0] == home_indent) and not df.search(line)): toinspect.append(line) continued = cnt.search(line) else: break log.debug("Inspecting lines '''%s''' around %s", toinspect, home_pos) return toinspect, home_pos class Expander: """Simple expression expander. Uses tokenize to find the names and expands any that can be looked up in the frame. """ def __init__(self, locals, globals): self.locals = locals self.globals = globals self.lpos = None self.expanded_source = '' def __call__(self, ttype, tok, start, end, line): # TODO # deal with unicode properly # TODO # Dealing with instance members # always keep the last thing seen # if the current token is a dot, # get ready to getattr(lastthing, this thing) on the # next call. if self.lpos is not None and start[1] >= self.lpos: self.expanded_source += ' ' * (start[1]-self.lpos) elif start[1] < self.lpos: # newline, indent correctly self.expanded_source += ' ' * start[1] self.lpos = end[1] if ttype == tokenize.INDENT: pass elif ttype == tokenize.NAME: # Clean this junk up try: val = self.locals[tok] if callable(val): val = tok else: val = repr(val) except KeyError: try: val = self.globals[tok] if callable(val): val = tok else: val = repr(val) except KeyError: val = tok # FIXME... not sure how to handle things like funcs, classes # FIXME this is broken for some unicode strings self.expanded_source += val else: self.expanded_source += tok # if this is the end of the line and the line ends with # \, then tack a \ and newline onto the output # print line[end[1]:] if re.match(r'\s+\\\n', line[end[1]:]): self.expanded_source += ' \\\n' PK¤žC8niá á nose/config.pyc;ò è’*Fc@s5dkZdkZdkZdefd„ƒYZdS(NsConfigcBs‰tZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z e eee d ƒZe eee d ƒZRS( s/nose configuration. For internal use only. cKsÿtidtiƒ|_t|_t|_t |_ t |_ t |_ t |_tidj|_tidƒtidƒtidƒg|_t |_g|_ddg|_t |_g|_d|_t |_t |_|i|ƒ|iiƒ|_dS( Ns(?:^|[\b_\.%s-])[Tt]estswin32s^\.s^_s ^setup\.py$slibssrci( srescompilesosssepsselfs testMatchsTruesaddPathsscapturesFalsesdetailedErrorss debugErrorss debugFailuressNonesexcludessyssplatforms includeExes ignoreFilessincludespluginsssrcDirss stopOnErrorstestss verbositys_wheres _working_dirsupdateskws__dict__scopys_orig(sselfskw((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pys__init__ s&      -        cCs |iSdS(N(sselfs_where(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pys get_where!scCs||_t|_dS(N(svalsselfs_wheresNones _working_dir(sselfsval((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pys set_where$s cCsp|i}|tjoRt|itƒpt|itƒo|id}|_qh|i}|_n|SdS(Ni(sselfs _working_dirsvalsNones isinstanceswheresliststuple(sselfsval((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pysget_working_dir(s   &cCs ||_dS(N(svalsselfs _working_dir(sselfsval((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pysset_working_dir1scCst|iƒSdS(N(sreprsselfs__dict__(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pys__str__4scCs|ii|iƒdS(N(sselfs__dict__supdates_orig(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pysreset8scCs|iiƒSdS(N(sselfs__dict__scopy(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pystodict;scCs|ii|ƒdS(N(sselfs__dict__supdatesd(sselfsd((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pysupdate>ss6The list of directories where tests will be discoveredsKThe current working directory (the root directory of the current test run).(s__name__s __module__s__doc__s__init__s get_wheres set_wheresget_working_dirsset_working_dirs__str__sresetstodictsupdatespropertysNoneswheres working_dir(((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pysConfigs            (sossressyssobjectsConfig(ssyssresossConfig((s/build/bdist.darwin-8.0.1-x86/egg/nose/config.pys?s   PK••6ÇD={ nose/exc.py"""Exceptions for marking tests as skipped or deprecated. """ class DeprecatedTest(Exception): """Raise this exception to mark a test as deprecated. """ pass class SkipTest(Exception): """Raise this exception to mark a test as skipped. """ pass PK••6Z*Ѝ¨W¨W nose/core.py"""Implements nose test program and collector. """ from __future__ import generators import logging import os import re import sys import types import unittest from optparse import OptionParser from warnings import warn import ConfigParser from nose.plugins import load_plugins, call_plugins from nose.result import start_capture, end_capture, TextTestResult from nose.config import Config from nose.loader import defaultTestLoader from nose.proxy import ResultProxySuite from nose.result import Result from nose.suite import LazySuite, TestModule from nose.util import absdir, tolist from nose.importer import add_path log = logging.getLogger('nose.core') compat_24 = sys.version_info >= (2, 4) class TestCollector(LazySuite): """Main nose test collector. Uses a test loader to load tests from the directory given in conf (conf.path). Uses the default test loader from nose.loader by default. Any other loader may be used so long as it implements loadTestsFromDir(). """ def __init__(self, conf, loader=None): if loader is None: loader = defaultTestLoader(conf) self.conf = conf self.loader = loader self.path = conf.where def loadtests(self): for path in tolist(self.path): for test in self.loader.loadTestsFromDir(path): yield test def __repr__(self): return "collector in %s" % self.path __str__ = __repr__ defaultTestCollector = TestCollector def collector(): """TestSuite replacement entry point. Use anywhere you might use a unittest.TestSuite. Note: Except with testoob; currently (nose 0.9) testoob's test loading is not compatible with nose's collector implementation. Returns a TestCollector configured to use a TestLoader that returns ResultProxySuite test suites, which use a proxy result object to enable output capture and assert introspection. """ # plugins that implement any of these methods are disabled, since # we don't control the test runner and won't be able to run them setuptools_incompat = ( 'finalize', 'prepareTest', 'report', 'setOutputStream') conf = configure(argv=[], env=os.environ, disable_plugins=setuptools_incompat) Result.conf = conf loader = defaultTestLoader(conf) loader.suiteClass = ResultProxySuite return TestCollector(conf, loader) class TextTestRunner(unittest.TextTestRunner): """Test runner that uses nose's TextTestResult to enable output capture and assert introspection, as well as providing hooks for plugins to override or replace the test output stream, results, and the test case itself. """ def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1, conf=None): unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) self.conf = conf def _makeResult(self): return TextTestResult(self.stream, self.descriptions, self.verbosity, self.conf) def run(self, test): wrapper = call_plugins(self.conf.plugins, 'prepareTest', test) if wrapper is not None: test = wrapper # plugins can decorate or capture the output stream wrapped = call_plugins(self.conf.plugins, 'setOutputStream', self.stream) if wrapped is not None: self.stream = wrapped result = unittest.TextTestRunner.run(self, test) call_plugins(self.conf.plugins, 'finalize', result) return result class TestProgram(unittest.TestProgram): r"""usage: %prog [options] [names] nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to magic. nose collects tests automatically from python source files, directories and packages found in its working directory (which defaults to the current working directory). Any python source file, directory or package that matches the testMatch regular expression (by default: (?:^|[\b_\.-])[Tt]est) will be collected as a test (or source for collection of tests). In addition, all other packages found in the working directory are examined for python source files or directories that match testMatch. Package discovery descends all the way down the tree, so package.tests and package.sub.tests and package.sub.sub2.tests will all be collected. Within a test directory or package, any python source file matching testMatch will be examined for test cases. Within a test file, functions and classes whose names match testMatch and TestCase subclasses with any name will be loaded and executed as tests. Tests may use the assert keyword or raise AssertionErrors to indicate test failure. TestCase subclasses may do the same or use the various TestCase methods available. Tests may raise nose.SkipTest to indicate that they should be skipped or nose.DeprecatedTest to indicate that they are deprecated. Skipped and deprecated tests do not count as failures, but details on them are printed at the end of the test run along with any failures and errors. Selecting Tests --------------- To specify which tests to run, pass test names on the command line: %prog only_test_this.py Test names specified may be file or module names, and may optionally indicate the test case to run by separating the module or file name from the test case name with a colon. Filenames may be relative or absolute. Examples: %prog test.module %prog another.test:TestCase.test_method %prog a.test:TestCase %prog /path/to/test/file.py:test_function Note however that specifying a test name will *not* cause nose to run a test that it does not discover. Test names specified are compared against tests discovered, and only the requested tests are run. Setup and teardown methods are run at all stages. That means that if you run: %prog some.tests.test_module:test_function And have defined setup or teardown methods in tests and test_module, those setup methods will run before the test_function test, and teardown after, just as if you were running all tests. You may also change the working directory where nose looks for tests, use the -w switch: %prog -w /path/to/tests Further customization of test selection and loading is possible through the use of plugins. Test result output is identical to that of unittest, except for the additional features (output capture, assert introspection, and any plugins that control or produce output) detailed in the options below. Configuration ------------- In addition to passing command-line options, you may also put configuration options in a .noserc or nose.cfg file in your home directory. These are standard .ini-style config files. Put your nosetests configuration in a [nosetests] section, with the -- prefix removed: [nosetests] verbosity=3 with-doctest All configuration files that are found will be loaded and their options combined. """ verbosity = 1 userConfigFiles = [ # Linux users will prefer this "~/.noserc", # Windows users will prefer this "~/nose.cfg", ] def __init__(self, module=None, defaultTest=defaultTestCollector, argv=None, testRunner=None, testLoader=None, env=None, stream=sys.stderr): self.testRunner = testRunner self.testCollector = defaultTest self.testLoader = testLoader self.stream = stream self.success = False self.module = module if not callable(self.testCollector): raise ValueError("TestProgram argument defaultTest must be " "a callable with the same signature as " "nose.TestCollector") if argv is None: argv = sys.argv if env is None: env = os.environ okFiles = self.parseUserConfig(argv, map(os.path.expanduser, self.userConfigFiles)) self.parseArgs(argv, env) # Log after logging was configured (in self.parseArgs) if okFiles: log.info("Configuration was read from the following files: %s", ", ".join(okFiles)) elif compat_24: log.info("No user configuration found") self.createTests() self.runTests() def parseArgs(self, argv, env): """Parse argv and env and configure running environment. """ self.conf = configure(argv, env) # append the requested module to the list of tests to run if self.module: try: self.conf.tests.append(self.module.__name__) except AttributeError: self.conf.tests.append(str(self.module)) def parseUserConfig(self, argv, confFiles): """Parse user configuration from supplied confFiles. Found configuration options are inserted at the beginning of argv. Returns the list of successful config files. """ # XXX Can't do it at top because of recursive imports. # These utility functions should be moved to another module however. from nose.commands import flag, _bool, option_blacklist c = ConfigParser.ConfigParser() try: okFiles = c.read(confFiles) except ConfigParser.Error, e: # log not configured yet warn("Error in configuration file: \n%s" % e, RuntimeWarning) return [] if compat_24 and not okFiles: return [] sectionName = "nosetests" if sectionName not in c.sections(): # log not configured yet warn("Configuration files lack a 'nosetests' section", RuntimeWarning) return [] confArgv = [] for optionName in c.options(sectionName): if optionName in option_blacklist: continue value = c.get(sectionName, optionName) if value: if flag(value): if _bool(value): confArgv.append('--' + optionName) else: confArgv.append('--' + optionName) confArgv.append(value) # Insert in-place, after the program name but before other options argv[1:1] = confArgv return okFiles def createTests(self): """Create the tests to run. Default behavior is to discover tests using TestCollector using nose.loader.TestLoader as the test loader. """ self.test = self.testCollector(self.conf, self.testLoader) def runTests(self): """Run Tests. Returns true on success, false on failure, and sets self.success to the same value. """ if self.testRunner is None: self.testRunner = TextTestRunner(stream=self.stream, verbosity=self.conf.verbosity, conf=self.conf) result = self.testRunner.run(self.test) self.success = result.wasSuccessful() return self.success def get_parser(env=None, builtin_only=False, doc=None): if doc is None: doc = TestProgram.__doc__ parser = OptionParser(doc) parser.add_option("-V","--version",action="store_true", dest="version",default=False, help="Output nose version and exit") parser.add_option("-v", "--verbose", action="count", dest="verbosity", default=int(env.get('NOSE_VERBOSE', 1)), help="Be more verbose. [NOSE_VERBOSE]") parser.add_option("--verbosity", action="store", dest="verbosity", type="int", help="Set verbosity; --verbosity=2 is " "the same as -vv") parser.add_option("-l", "--debug", action="store", dest="debug", default=env.get('NOSE_DEBUG'), help="Activate debug logging for one or more systems. " "Available debug loggers: nose, nose.importer, " "nose.inspector, nose.plugins, nose.result and " "nose.selector. Separate multiple names with a comma.") parser.add_option("--debug-log", dest="debug_log", action="store", default=env.get('NOSE_DEBUG_LOG'), help="Log debug messages to this file " "(default: sys.stderr)") parser.add_option("-q", "--quiet", action="store_const", const=0, dest="verbosity") parser.add_option("-w", "--where", action="append", dest="where", help="Look for tests in this directory [NOSE_WHERE]") parser.add_option("-e", "--exclude", action="append", dest="exclude", help="Don't run tests that match regular " "expression [NOSE_EXCLUDE]") parser.add_option("-i", "--include", action="append", dest="include", help="Also run tests that match regular " "expression [NOSE_INCLUDE]") parser.add_option("-m", "--match", "--testmatch", action="store", dest="test_match", help="Use this regular expression to " "find tests [NOSE_TESTMATCH]", default=env.get('NOSE_TESTMATCH')) parser.add_option("-s", "--nocapture", action="store_false", default=not env.get('NOSE_NOCAPTURE'), dest="capture", help="Don't capture stdout (any stdout output " "will be printed immediately) [NOSE_NOCAPTURE]") parser.add_option("-d", "--detailed-errors", action="store_true", default=env.get('NOSE_DETAILED_ERRORS'), dest="detailedErrors", help="Add detail to error" " output by attempting to evaluate failed" " asserts [NOSE_DETAILED_ERRORS]") parser.add_option("--pdb", action="store_true", dest="debugErrors", default=env.get('NOSE_PDB'), help="Drop into debugger " "on errors") parser.add_option("--pdb-failures", action="store_true", dest="debugFailures", default=env.get('NOSE_PDB_FAILURES'), help="Drop into debugger on failures") parser.add_option("-x", "--stop", action="store_true", dest="stopOnError", default=env.get('NOSE_STOP'), help="Stop running tests after the first error or " "failure") parser.add_option("-P", "--no-path-adjustment", action="store_false", dest="addPaths", default=not env.get('NOSE_NOPATH'), help="Don't make any changes to sys.path when " "loading tests [NOSE_NOPATH]") parser.add_option("--exe", action="store_true", dest="includeExe", default=env.get('NOSE_INCLUDE_EXE', sys.platform=='win32'), help="Look for tests in python modules that are " "executable. Normal behavior is to exclude executable " "modules, since they may not be import-safe " "[NOSE_INCLUDE_EXE]") parser.add_option("--noexe", action="store_false", dest="includeExe", help="DO NOT look for tests in python modules that are " "executable. (The default on the windows platform is to " "do so.)") # add opts from plugins all_plugins = [] # when generating the help message, load only builtin plugins for plugcls in load_plugins(others=not builtin_only): plug = plugcls() try: plug.add_options(parser, env) except AttributeError: pass return parser def configure(argv=None, env=None, help=False, disable_plugins=None): """Configure the nose running environment. Execute configure before collecting tests with nose.TestCollector to enable output capture and other features. """ if argv is None: argv = sys.argv if env is None: env = os.environ conf = Config() parser = get_parser(env=env, builtin_only=help) options, args = parser.parse_args(argv) if help: return parser.format_help() try: log.debug('Adding %s to tests to run' % args[1:]) conf.tests.extend(args[1:]) except IndexError: pass if options.version: from nose import __version__ print "%s version %s" % (os.path.basename(sys.argv[0]), __version__) sys.exit(0) # where is an append action, so it can't have a default value # in the parser, or that default will always be in the list if not options.where: options.where = env.get('NOSE_WHERE', os.getcwd()) # include and exclude also if not options.include: options.include = env.get('NOSE_INCLUDE', []) if not options.exclude: options.exclude = env.get('NOSE_EXCLUDE', []) configure_logging(options) # hand options to plugins all_plugins = [plug() for plug in load_plugins()] for plug in all_plugins: plug.configure(options, conf) if plug.enabled and disable_plugins: for meth in disable_plugins: if hasattr(plug, meth): plug.enabled = False log.warning("Plugin %s disabled: not all methods " "supported in this environment" % plug.name) conf.addPaths = options.addPaths conf.capture = options.capture conf.detailedErrors = options.detailedErrors conf.debugErrors = options.debugErrors conf.debugFailures = options.debugFailures conf.plugins = [ plug for plug in all_plugins if plug.enabled ] conf.stopOnError = options.stopOnError conf.verbosity = options.verbosity conf.includeExe = options.includeExe if options.where is not None: conf.where = [] for path in tolist(options.where): log.debug('Adding %s as nose working directory', path) abs_path = absdir(path) if abs_path is None: raise ValueError("Working directory %s not found, or " "not a directory" % path) conf.where.append(abs_path) log.info("Looking for tests in %s", abs_path) if conf.addPaths and \ os.path.exists(os.path.join(abs_path, '__init__.py')): log.info("Working directory %s is inside of a package; " "adding package root to sys.path" % abs_path) add_path(abs_path) if options.include: conf.include = map(re.compile, tolist(options.include)) log.info("Including tests matching %s", options.include) if options.exclude: conf.exclude = map(re.compile, tolist(options.exclude)) log.info("Excluding tests matching %s", options.exclude) if options.test_match: conf.testMatch = re.compile(options.test_match) log.info("Test match regular expression: %s", options.test_match) if conf.capture: start_capture() try: # give plugins a chance to start call_plugins(conf.plugins, 'begin') except: if conf.capture: end_capture() raise return conf def configure_logging(options): """Configure logging for nose, or optionally other packages. Any logger name may be set with the debug option, and that logger will be set to debug level and be assigned the same handler as the nose loggers, unless it already has a handler. """ format = logging.Formatter('%(name)s: %(levelname)s: %(message)s') if options.debug_log: handler = logging.FileHandler(options.debug_log) else: handler = logging.StreamHandler(sys.stderr) # FIXME handler.setFormatter(format) logger = logging.getLogger('nose') logger.propagate = 0 # only add our default handler if there isn't already one there # this avoids annoying duplicate log messages. if not logger.handlers: logger.addHandler(handler) # default level lvl = logging.WARNING if options.verbosity >= 5: lvl = 1 elif options.verbosity >= 4: lvl = logging.DEBUG elif options.verbosity >= 3: lvl = logging.INFO logger.setLevel(lvl) # individual overrides if options.debug: # no blanks debug_loggers = [ name for name in options.debug.split(',') if name ] for logger_name in debug_loggers: l = logging.getLogger(logger_name) l.setLevel(logging.DEBUG) if not l.handlers and not logger_name.startswith('nose'): l.addHandler(handler) def main(*arg, **kw): """Run and exit with 0 on success or 1 on failure. """ return sys.exit(not run(*arg, **kw)) # backwards compatibility run_exit = main def run(*arg, **kw): """Collect and run test, returning success or failure """ result = TestProgram(*arg, **kw).success end_capture() return result def runmodule(name='__main__'): """Collect and run tests in a single module only. Defaults to running tests in __main__. """ conf = configure() testLoader = defaultTestLoader(conf) def collector(conf, loader): return TestModule(loader.loadTestsFromModule, conf, name) main(defaultTest=collector, testLoader=testLoader) if __name__ == '__main__': main() PK£žC8°üÛûÿ]ÿ] nose/core.pyc;ò è’*Fc@sêdZdklZdkZdkZdkZdkZdkZdkZdk l Z dk l Z dk Z dklZlZdklZlZlZdklZdklZd klZd klZd klZlZd kl Z l!Z!d k"l#Z#ei$dƒZ%ei&ddfjZ'defd„ƒYZ(e(Z)d„Z*dei+fd„ƒYZ+dei,fd„ƒYZ,e-e.e-d„Z/e-e-e.e-d„Z0d„Z1d„Z2e2Z3d„Z4dd„Z5e6djo e2ƒndS(s,Implements nose test program and collector. (s generatorsN(s OptionParser(swarn(s load_pluginss call_plugins(s start_captures end_capturesTextTestResult(sConfig(sdefaultTestLoader(sResultProxySuite(sResult(s LazySuites TestModule(sabsdirstolist(sadd_paths nose.coreiis TestCollectorcBs2tZdZed„Zd„Zd„ZeZRS(sMain nose test collector. Uses a test loader to load tests from the directory given in conf (conf.path). Uses the default test loader from nose.loader by default. Any other loader may be used so long as it implements loadTestsFromDir(). cCs?|tjot|ƒ}n||_||_|i|_dS(N(sloadersNonesdefaultTestLoadersconfsselfswherespath(sselfsconfsloader((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys__init__$s    ccs?x8t|iƒD]'}x|ii|ƒD] }|Vq)WqWdS(N(stolistsselfspathsloadersloadTestsFromDirstest(sselfstestspath((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys loadtests+s cCsd|iSdS(Nscollector in %s(sselfspath(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys__repr__0s(s__name__s __module__s__doc__sNones__init__s loadtestss__repr__s__str__(((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys TestCollectors    cCs_ddddf}tdgdtid|ƒ}|t_t|ƒ}t|_ t ||ƒSdS( s¥TestSuite replacement entry point. Use anywhere you might use a unittest.TestSuite. Note: Except with testoob; currently (nose 0.9) testoob's test loading is not compatible with nose's collector implementation. Returns a TestCollector configured to use a TestLoader that returns ResultProxySuite test suites, which use a proxy result object to enable output capture and assert introspection. sfinalizes prepareTestsreportssetOutputStreamsargvsenvsdisable_pluginsN( ssetuptools_incompats configuresossenvironsconfsResultsdefaultTestLoadersloadersResultProxySuites suiteClasss TestCollector(ssetuptools_incompatsloadersconf((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys collector7s     sTextTestRunnercBs8tZdZeidded„Zd„Zd„ZRS(sèTest runner that uses nose's TextTestResult to enable output capture and assert introspection, as well as providing hooks for plugins to override or replace the test output stream, results, and the test case itself. icCs&tii||||ƒ||_dS(N(sunittestsTextTestRunners__init__sselfsstreams descriptionss verbositysconf(sselfsstreams descriptionss verbositysconf((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys__init__TscCs#t|i|i|i|iƒSdS(N(sTextTestResultsselfsstreams descriptionss verbositysconf(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys _makeResultYs cCs—t|iid|ƒ}|tj o |}nt|iid|iƒ}|tj o ||_nt i i ||ƒ}t|iid|ƒ|SdS(Ns prepareTestssetOutputStreamsfinalize( s call_pluginssselfsconfspluginsstestswrappersNonesstreamswrappedsunittestsTextTestRunnersrunsresult(sselfstestswrapperswrappedsresult((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysrun_s     ( s__name__s __module__s__doc__ssyssstderrsNones__init__s _makeResultsrun(((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysTextTestRunnerNs  s TestProgramcBsetZdZdZddgZeeeeeeeid„Z d„Z d„Z d„Z d„Z RS( syusage: %prog [options] [names] nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to magic. nose collects tests automatically from python source files, directories and packages found in its working directory (which defaults to the current working directory). Any python source file, directory or package that matches the testMatch regular expression (by default: (?:^|[\b_\.-])[Tt]est) will be collected as a test (or source for collection of tests). In addition, all other packages found in the working directory are examined for python source files or directories that match testMatch. Package discovery descends all the way down the tree, so package.tests and package.sub.tests and package.sub.sub2.tests will all be collected. Within a test directory or package, any python source file matching testMatch will be examined for test cases. Within a test file, functions and classes whose names match testMatch and TestCase subclasses with any name will be loaded and executed as tests. Tests may use the assert keyword or raise AssertionErrors to indicate test failure. TestCase subclasses may do the same or use the various TestCase methods available. Tests may raise nose.SkipTest to indicate that they should be skipped or nose.DeprecatedTest to indicate that they are deprecated. Skipped and deprecated tests do not count as failures, but details on them are printed at the end of the test run along with any failures and errors. Selecting Tests --------------- To specify which tests to run, pass test names on the command line: %prog only_test_this.py Test names specified may be file or module names, and may optionally indicate the test case to run by separating the module or file name from the test case name with a colon. Filenames may be relative or absolute. Examples: %prog test.module %prog another.test:TestCase.test_method %prog a.test:TestCase %prog /path/to/test/file.py:test_function Note however that specifying a test name will *not* cause nose to run a test that it does not discover. Test names specified are compared against tests discovered, and only the requested tests are run. Setup and teardown methods are run at all stages. That means that if you run: %prog some.tests.test_module:test_function And have defined setup or teardown methods in tests and test_module, those setup methods will run before the test_function test, and teardown after, just as if you were running all tests. You may also change the working directory where nose looks for tests, use the -w switch: %prog -w /path/to/tests Further customization of test selection and loading is possible through the use of plugins. Test result output is identical to that of unittest, except for the additional features (output capture, assert introspection, and any plugins that control or produce output) detailed in the options below. Configuration ------------- In addition to passing command-line options, you may also put configuration options in a .noserc or nose.cfg file in your home directory. These are standard .ini-style config files. Put your nosetests configuration in a [nosetests] section, with the -- prefix removed: [nosetests] verbosity=3 with-doctest All configuration files that are found will be loaded and their options combined. is ~/.nosercs ~/nose.cfgc Cs||_||_||_||_t|_||_t |iƒ ot dƒ‚n|t jo t i }n|t jo ti}n|i|ttii|iƒƒ}|i||ƒ|otiddi|ƒƒntotidƒn|iƒ|iƒdS(NsaTestProgram argument defaultTest must be a callable with the same signature as nose.TestCollectors3Configuration was read from the following files: %ss, sNo user configuration found(s testRunnersselfs defaultTests testCollectors testLoadersstreamsFalsessuccesssmodulescallables ValueErrorsargvsNonessyssenvsossenvironsparseUserConfigsmapspaths expandusersuserConfigFilessokFiless parseArgsslogsinfosjoins compat_24s createTestssrunTests( sselfsmodules defaultTestsargvs testRunners testLoadersenvsstreamsokFiles((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys__init__Ïs,             cCsst||ƒ|_|ioSy|iii|iiƒWqot j o#|iiit |iƒƒqoXndS(s>Parse argv and env and configure running environment. N( s configuresargvsenvsselfsconfsmodulestestssappends__name__sAttributeErrorsstr(sselfsargvsenv((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys parseArgsîs c Csddkl} l}l}tiƒ}y|i|ƒ}Wn-ti j o}t d|t ƒgSnXt o| ogSnd}||iƒjot dt ƒgSng} x™|i|ƒD]ˆ} | |joqÃn|i|| ƒ} | oU| | ƒo&|| ƒo| id| ƒqGqK| id| ƒ| i| ƒqÃqÃW| |dd+|SdS(sºParse user configuration from supplied confFiles. Found configuration options are inserted at the beginning of argv. Returns the list of successful config files. (sflags_boolsoption_blacklists Error in configuration file: %ss nosetestss.Configuration files lack a 'nosetests' sections--iN(s nose.commandssflags_boolsoption_blacklists ConfigParserscsreads confFilessokFilessErrorseswarnsRuntimeWarnings compat_24s sectionNamessectionssconfArgvsoptionss optionNamesgetsvaluesappendsargv( sselfsargvs confFilessokFiless_boolsoption_blacklistses sectionNamescsflagsvaluesconfArgvs optionName((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysparseUserConfigùs<       cCs|i|i|iƒ|_dS(sœCreate the tests to run. Default behavior is to discover tests using TestCollector using nose.loader.TestLoader as the test loader. N(sselfs testCollectorsconfs testLoaderstest(sself((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys createTests!scCsm|itjo.td|id|iid|iƒ|_n|ii|iƒ}|i ƒ|_ |i SdS(soRun Tests. Returns true on success, false on failure, and sets self.success to the same value. sstreams verbositysconfN( sselfs testRunnersNonesTextTestRunnersstreamsconfs verbositysrunstestsresults wasSuccessfulssuccess(sselfsresult((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysrunTests(s  (s__name__s __module__s__doc__s verbositysuserConfigFilessNonesdefaultTestCollectorssyssstderrs__init__s parseArgssparseUserConfigs createTestssrunTests(((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys TestProgramos W ! ( c CsŸ|tjo ti}nt|ƒ}|idddddddtdd ƒ|id d dd dd dt|i ddƒƒddƒ|iddddd ddddƒ|iddddddd|i dƒddƒ|idddddd|i dƒddƒ|idd dd!d"d#dd ƒ|id$d%dd&dd'dd(ƒ|id)d*dd&dd+dd,ƒ|id-d.dd&dd/dd0ƒ|id1d2d3dddd4dd5d|i d6ƒƒ|id7d8dd9d|i d:ƒ dd;dd<ƒ|id=d>ddd|i d?ƒdd@ddAƒ|idBddddCd|i dDƒddEƒ|idFddddGd|i dHƒddIƒ|idJdKddddLd|i dMƒddNƒ|idOdPdd9ddQd|i dRƒ ddSƒ|idTddddUd|i dVt i dWjƒddXƒ|idYdd9ddUddZƒg}xKtd[| ƒD]9}|ƒ}y|i||ƒWqZtj oqZXqZW|SdS(\Ns-Vs --versionsactions store_truesdestsversionsdefaultshelpsOutput nose version and exits-vs --verbosescounts verbositys NOSE_VERBOSEisBe more verbose. [NOSE_VERBOSE]s --verbositysstorestypesints/Set verbosity; --verbosity=2 is the same as -vvs-ls--debugsdebugs NOSE_DEBUGsÀActivate debug logging for one or more systems. Available debug loggers: nose, nose.importer, nose.inspector, nose.plugins, nose.result and nose.selector. Separate multiple names with a comma.s --debug-logs debug_logsNOSE_DEBUG_LOGs5Log debug messages to this file (default: sys.stderr)s-qs--quiets store_constsconstis-ws--wheresappendswheres-Look for tests in this directory [NOSE_WHERE]s-es --excludesexcludes<Don't run tests that match regular expression [NOSE_EXCLUDE]s-is --includesincludes;Also run tests that match regular expression [NOSE_INCLUDE]s-ms--matchs --testmatchs test_matchs:Use this regular expression to find tests [NOSE_TESTMATCH]sNOSE_TESTMATCHs-ss --nocaptures store_falsesNOSE_NOCAPTUREscapturesUDon't capture stdout (any stdout output will be printed immediately) [NOSE_NOCAPTURE]s-ds--detailed-errorssNOSE_DETAILED_ERRORSsdetailedErrorssZAdd detail to error output by attempting to evaluate failed asserts [NOSE_DETAILED_ERRORS]s--pdbs debugErrorssNOSE_PDBsDrop into debugger on errorss--pdb-failuress debugFailuressNOSE_PDB_FAILURESsDrop into debugger on failuress-xs--stops stopOnErrors NOSE_STOPs3Stop running tests after the first error or failures-Ps--no-path-adjustmentsaddPathss NOSE_NOPATHsCDon't make any changes to sys.path when loading tests [NOSE_NOPATH]s--exes includeExesNOSE_INCLUDE_EXEswin32sœLook for tests in python modules that are executable. Normal behavior is to exclude executable modules, since they may not be import-safe [NOSE_INCLUDE_EXE]s--noexesoDO NOT look for tests in python modules that are executable. (The default on the windows platform is to do so.)sothers(sdocsNones TestPrograms__doc__s OptionParsersparsers add_optionsFalsesintsenvsgetssyssplatforms all_pluginss load_pluginss builtin_onlysplugclssplugs add_optionssAttributeError(senvs builtin_onlysdocsplugsparsersplugclss all_plugins((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys get_parser4s~                       cCs¨|tjo ti}n|tjo ti}ntƒ}td|d|ƒ}|i |ƒ\}} |o|iƒSny-tid| dƒ|ii| dƒWntj onX|io@dkl}dtiitidƒ|fGHtidƒn|i o|idtiƒƒ|_n|i o|id gƒ|_n|i o|id gƒ|_nt|ƒgi } t"ƒD]} | | ƒƒq–~ } xu| D]m} | i%||ƒ| i&o|oFxC|D]7}t)| |ƒo!t*| _&ti+d | i,ƒqçqçWq¹q¹W|i-|_-|i.|_.|i/|_/|i0|_0|i1|_1gi } | D]} | i&o| | ƒqtqt~ |_2|i3|_3|i4|_4|i5|_5|itj oÏg|_xÃt6|iƒD]®}tid |ƒt7|ƒ} | tjot9d |ƒ‚n|ii | ƒti:d| ƒ|i-otii;tii<| dƒƒoti:d| ƒt=| ƒqëqëWn|io5t>t?i@t6|iƒƒ|_ti:d|iƒn|io5t>t?i@t6|iƒƒ|_ti:d|iƒn|iAo,t?i@|iAƒ|_Bti:d|iAƒn|i.o tCƒnytD|i2dƒWn|i.o tEƒn‚nX|SdS(s£Configure the nose running environment. Execute configure before collecting tests with nose.TestCollector to enable output capture and other features. senvs builtin_onlysAdding %s to tests to runi(s __version__s %s version %sis NOSE_WHEREs NOSE_INCLUDEs NOSE_EXCLUDEsAPlugin %s disabled: not all methods supported in this environments#Adding %s as nose working directorys2Working directory %s not found, or not a directorysLooking for tests in %ss __init__.pysLWorking directory %s is inside of a package; adding package root to sys.pathsIncluding tests matching %ssExcluding tests matching %ss!Test match regular expression: %ssbeginN(FsargvsNonessyssenvsossenvironsConfigsconfs get_parsershelpsparsers parse_argssoptionssargss format_helpslogsdebugstestssextends IndexErrorsversionsnoses __version__spathsbasenamesexitswheresgetsgetcwdsincludesexcludesconfigure_loggingsappends_[1]s load_pluginssplugs all_pluginss configuresenabledsdisable_pluginssmethshasattrsFalseswarningsnamesaddPathsscapturesdetailedErrorss debugErrorss debugFailuresspluginss stopOnErrors verbositys includeExestolistsabsdirsabs_paths ValueErrorsinfosexistssjoinsadd_pathsmapsrescompiles test_matchs testMatchs start_captures call_pluginss end_capture(sargvsenvshelpsdisable_pluginssparsersconfspathsmeths __version__s all_pluginssargssplugsabs_paths_[1]soptions((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys configure‹s˜       "    - $     8      ,       c Cs™tidƒ}|ioti|iƒ}ntiti ƒ}|i |ƒti dƒ} d| _ | i o| i|ƒnti}|idjo d}n;|idjo ti}n|idjo ti}n| i|ƒ|ioŸgi}|iidƒD]}|o||ƒqq~}x^|D]R}ti |ƒ}|itiƒ|i o|idƒ o|i|ƒq;q;Wnd S( sþConfigure logging for nose, or optionally other packages. Any logger name may be set with the debug option, and that logger will be set to debug level and be assigned the same handler as the nose loggers, unless it already has a handler. s$%(name)s: %(levelname)s: %(message)ssnoseiiiiis,N(sloggings Formattersformatsoptionss debug_logs FileHandlershandlers StreamHandlerssyssstderrs setFormatters getLoggersloggers propagateshandlerss addHandlersWARNINGslvls verbositysDEBUGsINFOssetLevelsdebugsappends_[1]ssplitsnames debug_loggerss logger_namesls startswith( soptionss_[1]snamesformatsls debug_loggersshandlers logger_nameslvlslogger((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysconfigure_loggingðs4          >cOstit||Ž ƒSdS(s4Run and exit with 0 on success or 1 on failure. N(ssyssexitsrunsargskw(sargskw((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysmainscOs!t||Ži}tƒ|SdS(s7Collect and run test, returning success or failure N(s TestProgramsargskwssuccesssresults end_capture(sargskwsresult((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pysrun"ss__main__cs8tƒ}t|ƒ}‡d†}td|d|ƒdS(s^Collect and run tests in a single module only. Defaults to running tests in __main__. cst|i|ˆƒSdS(N(s TestModulesloadersloadTestsFromModulesconfsname(sconfsloader(sname(s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys collector/ss defaultTests testLoaderN(s configuresconfsdefaultTestLoaders testLoaders collectorsmain(snamesconfs testLoaders collector((snames-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys runmodule)s    (7s__doc__s __future__s generatorssloggingsossressysstypessunittestsoptparses OptionParserswarningsswarns ConfigParsers nose.pluginss load_pluginss call_pluginss nose.results start_captures end_capturesTextTestResults nose.configsConfigs nose.loadersdefaultTestLoaders nose.proxysResultProxySuitesResults nose.suites LazySuites TestModules nose.utilsabsdirstolists nose.importersadd_paths getLoggerslogs version_infos compat_24s TestCollectorsdefaultTestCollectors collectorsTextTestRunners TestProgramsNonesFalses get_parsers configuresconfigure_loggingsmainsrun_exitsruns runmodules__name__(&s load_pluginssadd_pathsunittestsTextTestRunnersResultProxySuitesConfigsTextTestResults compat_24slogs collectorsabsdirs TestModulesres generatorss runmodules TestCollectors ConfigParsers start_captures OptionParserstolistsruns configures get_parsers TestProgramswarnsconfigure_loggingsdefaultTestCollectorstypessdefaultTestLoaderssyssmainsloggingsrun_exits end_captures LazySuitesResultsoss call_plugins((s-build/bdist.darwin-8.0.1-x86/egg/nose/core.pys?sF                !ÅWe *   PK••6£9ÇÉii nose/util.py"""Utility functions and classes used by nose internally. """ import inspect import logging import os import re import sys import types import unittest from compiler.consts import CO_GENERATOR try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from nose.config import Config log = logging.getLogger('nose') def absdir(path): """Return absolute, normalized path to directory, if it exists; None otherwise. """ if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), path))) if path is None or not os.path.isdir(path): return None return path def absfile(path, where=None): """Return absolute, normalized path to file (optionally in directory where), or None if the file can't be found either in where or the current working directory. """ orig = path if where is None: where = os.getcwd() if isinstance(where, list) or isinstance(where, tuple): for maybe_path in where: maybe_abs = absfile(path, maybe_path) if maybe_abs is not None: return maybe_abs return None if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(where, path))) if path is None or not os.path.exists(path): if where != os.getcwd(): # try the cwd instead path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), orig))) if path is None or not os.path.exists(path): return None if os.path.isdir(path): # might want an __init__.py from pacakge init = os.path.join(path,'__init__.py') if os.path.isfile(init): return init elif os.path.isfile(path): return path return None def anyp(predicate, iterable): for item in iterable: if predicate(item): return True return False def file_like(name): return os.path.dirname(name) or name.endswith('.py') def func_lineno(func): """Get the line number of a function. First looks for compat_co_firstlineno, then func_code.co_first_lineno. """ try: return func.compat_co_firstlineno except AttributeError: return func.func_code.co_firstlineno def is_generator(func): try: return func.func_code.co_flags & CO_GENERATOR != 0 except AttributeError: return False def split_test_name(test): """Split a test name into a 3-tuple containing file, module, and callable names, any of which (but not all) may be blank. Test names are in the form: file_or_module:callable Either side of the : may be dotted. To change the splitting behavior, you can alter nose.util.split_test_re. """ parts = test.split(':') num = len(parts) if num == 1: # only a file or mod part if file_like(test): return (test, None, None) else: return (None, test, None) elif num >= 3: # definitely popped off a windows driveletter file_or_mod = ':'.join(parts[0:-1]) fn = parts[-1] else: # only a file or mod part, or a test part, or # we mistakenly split off a windows driveletter file_or_mod, fn = parts if len(file_or_mod) == 1: # windows drive letter: must be a file if not file_like(fn): raise ValueError("Test name '%s' is ambiguous; can't tell " "if ':%s' refers to a module or callable" % (test, fn)) return (test, None, None) if file_or_mod: if file_like(file_or_mod): return (file_or_mod, None, fn) else: return (None, file_or_mod, fn) else: return (None, None, fn) def test_address(test): """Find the test address for a test, which may be a module, filename, class, method or function. """ # type-based polymorphism sucks in general, but I believe is # appropriate here t = type(test) if t == types.ModuleType: return (os.path.abspath(test.__file__), test.__name__) if t == types.FunctionType: m = sys.modules[test.__module__] return (os.path.abspath(m.__file__), test.__module__, test.__name__) if t in (type, types.ClassType): m = sys.modules[test.__module__] return (os.path.abspath(m.__file__), test.__module__, test.__name__) if t == types.InstanceType: return test_address(test.__class__) if t == types.MethodType: cls_adr = test_address(test.im_class) return (cls_adr[0], cls_adr[1], "%s.%s" % (cls_adr[2], test.__name__)) # handle unittest.TestCase instances if isinstance(test, unittest.TestCase): if hasattr(test, 'testFunc'): # nose FunctionTestCase return test_address(test.testFunc) if hasattr(test, '_FunctionTestCase__testFunc'): # unittest FunctionTestCase return test_address(test._FunctionTestCase__testFunc) if hasattr(test, 'testCase'): # nose MethodTestCase return test_address(test.testCase) # regular unittest.TestCase cls_adr = test_address(test.__class__) # 2.5 compat: __testMethodName changed to _testMethodName try: method_name = test._TestCase__testMethodName except AttributeError: method_name = test._testMethodName return (cls_adr[0], cls_adr[1], "%s.%s" % (cls_adr[2], method_name)) raise TypeError("I don't know what %s is (%s)" % (test, t)) def try_run(obj, names): """Given a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests. """ for name in names: func = getattr(obj, name, None) if func is not None: if type(obj) == types.ModuleType: # py.test compatibility try: args, varargs, varkw, defaults = inspect.getargspec(func) except TypeError: # Not a function. If it's callable, call it anyway if hasattr(func, '__call__'): func = func.__call__ try: args, varargs, varkw, defaults = \ inspect.getargspec(func) args.pop(0) # pop the self off except TypeError: raise TypeError("Attribute %s of %r is not a python " "function. Only functions or callables" " may be used as fixtures." % (name, obj)) if len(args): log.debug("call fixture %s.%s(%s)", obj, name, obj) return func(obj) log.debug("call fixture %s.%s", obj, name) return func() def tolist(val): """Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. """ if val is None: return None try: # might already be a list val.extend([]) return val except AttributeError: pass # might be a string try: return re.split(r'\s*,\s*', val) except TypeError: # who knows... return list(val) PK¤žC8“êÏ2ÿDÿDnose/selector.pyc;ò è’*Fc@s•dkZdkZdkZdkZdklZdklZdkl Z l Z l Z l Z ei eƒZdefd„ƒYZeZd„ZdS(N(sConfig(s call_plugins(sabsfiles file_likessplit_test_names test_addresssSelectorcBs­tZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z e d „Z d „Zd „Zed „Zd„Zd„Zd„Zd„ZRS(s¥Core test selector. Examines test candidates and determines whether, given the specified configuration, the test candidate should be selected as a test. cCs||_|i|ƒdS(N(sconfsselfs configure(sselfsconf((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys__init__s cCs™|i otSntid|iƒgi}tt|iƒD]}|||Œƒq@~}tid|ƒt d„|ƒ}tid|ƒ|SdS(sCheck func against all tests. Funcs should return None if they don't apply, False if they apply but don't match, True if they apply and match. Example: a func that wants tests based on what file they are in should return None for a test address that doesn't contain a file part. It should return true if a test address contains a file part that matches the comparison file, and False if a test address contains a file part that does not match the comparison file. stests to check: %ssanytest matches: %scCs |tj S(N(sxsFalse(sx((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys&ssanytest result: %sN(sselfstestssTrueslogsdebugsappends_[1]smapssplit_test_names test_tuplesfuncsmatchessfiltersres(sselfsfuncsmatchessress_[1]s test_tuple((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysanytests  9cCs|d„}|i|ƒSdS(NcCsm|tjotSny|idƒ\}}Wn+ttfj o|tf\}}nX|i|jSdS(Ns.( sfuncnamesNonessplitsclsnsdummys ValueErrorsAttributeErrorsclss__name__(sfilenamesmodnamesfuncnamesclssdummysclsn((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatch+s (sclssmatchsselfsanytest(sselfsclssmatch((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys classInTests*s cCsL|i|_|i|_|i|_|i|_|i|_|i|_dS(N( sconfsexcludesselfs ignoreFilessincludespluginss testMatchsmatchstests(sselfsconf((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys configure5s      cs«|}tii|ƒ o,t|ˆiiƒ}t i d||ƒn|t jo+t i d|ƒˆi ot SntSnt i dƒ|‡d†}ˆi|ƒSdS(Nsabs file %s is %ssFile %s does not existsCheck file in testscsˆi||||ƒSdS(N(sselfs filematchsfilenamesmodnamesfuncnamesfile(sfilenamesmodnamesfuncnamesfile(sself(s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatchHs(sfilesorigsosspathsisabssabsfilesselfsconfs working_dirslogsdebugsNonestestssFalsesTruesmatchsanytest(sselfsfilesorigsmatch((sselfs1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys fileInTests=s   cCstid||||ƒ|tjoc|tjotSntii i |i dƒƒ}tid||ƒ||jotSq‰t Sntii|ƒ o)t||iiƒ}tid|ƒn|tjot Sn|idƒotii|ƒ}n$tii|ƒo |}nt}tid||jƒtid|ƒ|tj ogtid|i|ƒƒy'tid |t|ƒtii ƒWq¾tj otid ƒq¾Xn||jp7|tj o*|i|ƒo|t|ƒtii jSdS( NsFilematch (%s, %s, %s, %s)s.sIs module path %s in file %s?sAbs match file: %ss __init__.pysFiles are same: %ss Dirname: %ssFile startswith dirname: %ss(File has sep at end of dirname: %s == %ssFile is not within dir(slogsdebugsfilenamesmodnamesfuncnamesfilesNonesosspathssepsjoinssplitsmpathsFalsesisabssabsfilesselfsconfs working_dirsendswithsdirnamesisdirs startswithslens IndexError(sselfsfilenamesmodnamesfuncnamesfilesdirnamesmpath((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys filematchLs<        cCs|d„}|i|ƒSdS(NcCs&|tjotSn|i|jSdS(N(sfuncnamesNonesfuncs__name__(sfilenamesmodnamesfuncnamesfunc((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatch}s (sfuncsmatchsselfsanytest(sselfsfuncsmatch((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys funcInTests|s cCs¤|ii|ƒpD|io:ttgi}|iD]}||i|ƒƒq4~ƒoF|i p;ttgi}|i D]}||i|ƒƒq|~ƒ SdS(sœDoes the name match my requirements? To match, a name must match conf.testMatch OR conf.include and it must not match conf.exclude N( sselfsmatchssearchsnamesincludesfiltersNonesappends_[1]sincsexcludesexc(sselfsnames_[1]sexcsinc((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatchesƒs#HcCs|d„}|i|ƒSdS(sDetermine if a method is listed in the requested tests. To be consideed a match, the method's class must be in the class part of the test address, and the function part of the test address must match the method name or be None. cCs™|tjotSn|ii}|i}y|idƒ\}}Wn+t t fj o|tf\}}nX||jo||jp |tjSdS(Ns.( sfuncnamesNonesmethodsim_classs__name__smclssmnamessplitsclssfuncs ValueErrorsAttributeError(sfilenamesmodnamesfuncnamesmethodsmnamesfuncsmclsscls((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatch˜s   N(smethodsmatchsselfsanytest(sselfsmethodsmatch((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys methodInTests’s cs<||‡d†}ˆi|ƒ}tid||ƒ|SdS(Ncsütid|i|||ƒ|tjo€|tjotSn|i }|i dƒp |i dƒo|d d}ntid||ƒˆi |||d|ƒSn|i}t||ƒp|o t||ƒ}tid|i|||ƒ|SdS( Ns-Checking module %s in test %s:%s (either: %s)s.pycs.pyoiýÿÿÿspys+Checking module file %s against filename %ssfiles)Module %s match %s (either: %s) result %s(slogsdebugsmodules__name__smodnamesfuncnameseithersNonesfilenames__file__smod_filesendswithsselfs filematchsmnames subpackage_ofsresult(sfilenamesmodnamesfuncnamesmoduleseithersresultsmnamesmod_file(sself(s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysmatch¥s"        & sModule %s in tests result: %s(smoduleseithersmatchsselfsanytestsresslogsdebug(sselfsmoduleseithersressmatch((sselfs1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys moduleInTests¤scCs¶tid|ƒ|iidƒ o&t|tiƒp|i i |iƒ}tid||ƒt |i d|ƒ}|tj otid||ƒ|}n|o |i|ƒSdS(säIs the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. If self.tests is defined, the class must match something in self.tests: sLoad tests from class %s?s_s%s is wanted? %ss wantClasss$Plugin setting selection of %s to %sN(slogsdebugsclss__name__s startswiths issubclasssunittestsTestCasesselfsmatchssearchswanteds call_pluginsspluginss plug_wantssNones classInTests(sselfsclss plug_wantsswanted((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys wantClass¼s<  cCsétii|dƒ}tii|ƒ}tii|ƒoL|i p;t t gi }|i D]}||i|ƒƒq\~ƒ }n0|i|ƒp|iio||iij}t|id|ƒ}|t j o |}n|SdS(s¼Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. s __init__.pys wantDirectoryN(sosspathsjoinsdirnamesinitsbasenamestailsexistssselfsexcludesfiltersNonesappends_[1]sexcssearchswantedsmatchessconfssrcDirss call_pluginsspluginss plug_wants(sselfsdirnames_[1]swantedsexcsinits plug_wantsstail((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys wantDirectoryÑs;/    c CsStii|ƒ} gi}|iD]$}|i | ƒo||ƒq#q#~}|ot i d| ƒtSn|ii oti|tiƒot id|ƒtSn|i|ƒ}| otSntii| ƒ\}} | dj} | o |i| ƒ} t|id||ƒ}|t j o |} n| p| o|i!o|SdS(s<Is the file a wanted test file? If self.tests is defined, the file must match the file part of a test address in self.tests. The default implementation ignores the package setting, but it is passed in case plugins need to distinguish package from non-package files. s'%s matches ignoreFiles pattern; skippeds%s is executable; skippeds.pyswantFileN("sosspathsbasenamesfilesbasesappends_[1]sselfs ignoreFiless ignore_thisssearchsignore_matchesslogsdebugsFalsesconfs includeExesaccesssX_OKsinfos fileInTestssin_testsssplitextsdummysextspysrcsmatchesswanteds call_pluginsspluginsspackages plug_wantssNonestests( sselfsfilespackagesdummysignore_matchess ignore_thiss plug_wantssin_testss_[1]sextsbasespysrcswanted((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pyswantFileés* > $     cCs·y*t|dƒo |i}n |i}Wntj o tSnX|i|ƒ}| otSn|i dƒ o |i |ƒ}t |id|ƒ}|tj o |}n|SdS(sËIs the function a test function? If conf.function_only is defined, the function name must match function_only. Otherwise, the function name must match test requirements. scompat_func_names_s wantFunctionN(shasattrsfunctionscompat_func_namesfuncnames__name__sAttributeErrorsFalsesselfs funcInTestssin_testss startswithsmatchesswanteds call_pluginsspluginss plug_wantssNone(sselfsfunctionswantedsfuncnames plug_wantssin_tests((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys wantFunction s      cCs¡y |i}Wntj o tSnX|idƒotSn|i|ƒ}| otSn|i |ƒ}t |i d|ƒ}|tj o |}n|SdS(sñIs the method a test method? If conf.function_only is defined, the qualified method name (class.method) must match function_only. Otherwise, the base method name must match test requirements. s_s wantMethodN(smethods__name__s method_namesAttributeErrorsFalses startswithsselfs methodInTestssin_testssmatchesswanteds call_pluginsspluginss plug_wantssNone(sselfsmethodsin_testss method_names plug_wantsswanted((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys wantMethod%s    cCs‰|i|dtƒ}| otSn|i|iidƒdƒ}t |i d|ƒ}|t j o |}n|p|io|SdS(s€Is the module a test module? The tail of the module name must match test requirements. If a module is wanted, it means that the module should be loaded, and its setup/teardown fixtures run -- if any. It does not mean that tests will be collected from the module; tests are only collected from modules where wantModuleTests() is true. seithers.iÿÿÿÿs wantModuleN(sselfs moduleInTestssmodulesTruesin_testssFalsesmatchess__name__ssplitswanteds call_pluginsspluginss plug_wantssNonestests(sselfsmodulesin_testss plug_wantsswanted((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys wantModule=s   cCs“|i|ƒ}| otSn|i|iidƒdƒp |idj}t |i d|ƒ}|t j o |}n|p|i o|SdS(sÍCollect tests from this module? The tail of the module name must match test requirements. If the modules tests are wanted, they will be collected by the standard test collector. If your plugin wants to collect tests from a module in some other way, it MUST NOT return true for wantModuleTests; that would not allow the plugin to collect tests, but instead cause the standard collector to collect tests. s.iÿÿÿÿs__main__swantModuleTestsN(sselfs moduleInTestssmodulesin_testssFalsesmatchess__name__ssplitswanteds call_pluginsspluginss plug_wantssNonestests(sselfsmodulesin_testss plug_wantsswanted((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pyswantModuleTestsPs /    (s__name__s __module__s__doc__s__init__sanytests classInTestss configures fileInTestss filematchs funcInTestssmatchess methodInTestssFalses moduleInTestss wantClasss wantDirectorysNoneswantFiles wantFunctions wantMethods wantModuleswantModuleTests(((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pysSelector s$      0       $   cCs tid||ƒ|i|ƒ otid||ƒtSnt|ƒt|ƒjotidƒtSn|idƒ}|idƒ}yLxE|D]=}|i dƒ}tid||ƒ||jotSq•q•WWn*t j otid||ƒtSnXtSdS( s*Is module modname a subpackage of package?ssubpackage_of(%s,%s)snot %s startswith %ss!package name longer than mod names.ischeck part %s vs part %ss%package %s more parts than modname %sN(slogsdebugsmodnamespackages startswithsFalseslenssplits mod_partss pkg_partsspspopspps IndexErrorsTrue(smodnamespackages pkg_partssppsps mod_parts((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys subpackage_ofls*   (sloggingsosssyssunittests nose.configsConfigs nose.pluginss call_pluginss nose.utilsabsfiles file_likessplit_test_names test_addresss getLoggers__name__slogsobjectsSelectorsdefaultSelectors subpackage_of(s file_likesdefaultSelectorsloggingsabsfiles subpackage_ofsConfigsunittestsSelectorssysssplit_test_names test_addresssoss call_pluginsslog((s1build/bdist.darwin-8.0.1-x86/egg/nose/selector.pys?s      ÿ^PK••6\©&kknose/importer.py"""Implements an importer that looks only in specific path (ignoring sys.path), and uses a per-path cache in addition to sys.modules. This is necessary because test modules in different directories frequently have the same names, which means that the first loaded would mask the rest when using the builtin importer. """ from __future__ import generators import logging import os import sys from imp import find_module, load_module, acquire_lock, release_lock log = logging.getLogger(__name__) _modules = {} def add_path(path): """Ensure that the path, or the root of the current package (if path is in a package) is in sys.path. """ log.debug('Add path %s' % path) if not path: return parent = os.path.dirname(path) if (parent and os.path.exists(os.path.join(path, '__init__.py'))): add_path(parent) elif not path in sys.path: log.debug("insert %s into sys.path", path) sys.path.insert(0, path) def _import(name, path, conf): """Import a module *only* from path, ignoring sys.path and reloading if the version in sys.modules is not the one we want. """ log.debug("Import %s from %s (addpaths: %s)", name, path, conf.addPaths) # special case for __main__ if name == '__main__': return sys.modules[name] # make sure we're doing an absolute import # name, path = make_absolute(name, path) if conf.addPaths: for p in path: add_path(p) path = [ p for p in path if p is not None ] cache = _modules.setdefault(':'.join(path), {}) # quick exit for fully cached names if cache.has_key(name): return cache[name] parts = name.split('.') fqname = '' mod = parent = fh = None for part in parts: if fqname == '': fqname = part else: fqname = "%s.%s" % (fqname, part) if cache.has_key(fqname): mod = cache[fqname] else: try: acquire_lock() log.debug("find module part %s (%s) at %s", part, fqname, path) fh, filename, desc = find_module(part, path) old = sys.modules.get(fqname) if old: # test modules frequently have name overlap; make sure # we get a fresh copy of anything we are trying to load # from a new path if hasattr(old,'__path__'): old_path = os.path.normpath(old.__path__[0]) old_ext = None elif hasattr(old, '__file__'): old_norm = os.path.normpath(old.__file__) old_path, old_ext = os.path.splitext(old_norm) else: # builtin or other module-like object that # doesn't have __file__ old_path, old_ext, old_norm = None, None, None new_norm = os.path.normpath(filename) new_path, new_ext = os.path.splitext(new_norm) if old_path == new_path: log.debug("module %s already loaded " "old: %s %s new: %s %s", fqname, old_path, old_ext, new_path, new_ext) cache[fqname] = mod = old continue else: del sys.modules[fqname] log.debug("Loading %s from %s", fqname, filename) mod = load_module(fqname, fh, filename, desc) log.debug("%s from %s yields %s", fqname, filename, mod) cache[fqname] = mod finally: if fh: fh.close() release_lock() if parent: setattr(parent, part, mod) if hasattr(mod, '__path__'): path = mod.__path__ parent = mod return mod def make_absolute(name, path): """Given a module name and the path at which it is found, back up to find the parent of the module, popping directories off of the path so long as they contain __init__.py files. """ if not os.path.exists(os.path.join(path, '__init__.py')): return (name, path) path, parent = os.path.split(path) name = "%s.%s" % (parent, path) return make_absolute(name, path) PK¤žC8ÝA·^^nose/commands.pyc;ò è’*Fc@sdZdkZdklZdklZlZedhƒZddgZd„Z defd „ƒYZ d „Z d „Z dS( sš nosetests setuptools command ---------------------------- You can run tests using the `nosetests` setuptools command:: python setup.py nosetests This command has a few benefits over the standard `test` command: all nose plugins are supported, and you can configure the test run with both command line arguments and settings in your setup.cfg file. To configure the `nosetests` command, add a [nosetests] section to your setup.cfg. The [nosetests] section can contain any command line arguments that nosetests supports. The differences between issuing an option on the command line and adding it to setup.cfg are: * In setup.cfg, the -- prefix must be excluded * In setup.cfg, command line flags that take no arguments must be given an argument flag (1, T or TRUE for active, 0, F or FALSE for inactive) Here's an example [nosetests] setup.cfg section:: [nosetests] verbosity=1 detailed-errors with-coverage=1 cover-package=nose debug=nose.loader pdb=1 pdb-failures=1 If you commonly run nosetests with a large number of options, using the nosetests setuptools command and configuring with setup.cfg can make running your tests much less tedious. N(sCommand(s get_parsersmainsenvshelpsverbosecCsµg}x¤tiD]™}|iddtjoqn|idd}|idjo|d}nt}|i o|i dd}n|i |||i pdfƒqW|SdS(sAconvert a optparse option list into a distutils option tuple listiis store_trues=isN( sopt_listsparsers option_listsopts _long_optssoption_blacklists long_namesactionsNones short_names _short_optssappendshelp(sopts short_names long_namesopt_list((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pysget_user_options.s  $s nosetestscBs2tZdZeƒZd„Zd„Zd„ZRS(NsRun unit tests using nosetestscCsjh|_xQtiD]F}|idd}|iddƒ}||i|create the member variables, but change hyphens to underscoresiis-s_N( sselfsoption_to_cmdssparsers option_listsopts _long_optsscmd_namesreplaces option_namessetattrsNonesattr(sselfsopts option_namescmd_name((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pysinitialize_optionsFs   cCsdS(snothing to do hereN((sself((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pysfinalize_optionsPscCs|idƒ|idddƒ|idƒ|iio|ii|iiƒng}x¢|iiƒD]‘\}}|t joqjnt ||ƒ}|tj oUt|ƒo&t|ƒo|id|ƒq÷qû|id|ƒ|i|ƒqjqjWtd|dtiƒdS( sdensure tests are capable of being run, then run nose.main with a reconstructed argument listsegg_infos build_extsinplaceis--sargvsenvN(sselfs run_commandsreinitialize_commands distributions tests_requiresfetch_build_eggssargvsoption_to_cmdssitemss option_namescmd_namesoption_blacklistsgetattrsvaluesNonesflags_boolsappendsmainsossenviron(sselfs option_namesvaluesargvscmd_name((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pysrunTs&        (s__name__s __module__s descriptionsget_user_optionss user_optionssinitialize_optionssfinalize_optionssrun(((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pys nosetestsBs   c Cspt|ƒtdƒjot|ƒ}nt|ƒdjotSn|iƒddddddd d fjSd S( s(Does the value look like an on/off flag?iis1s0sFsTsTRUEsFALSEsONsOFFN(stypesvalsstrslensFalsesupper(sval((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pysflagns cCsCt|ƒtjot|ƒ}n|iƒddddfjSdS(Ns1sTsTRUEsON(stypesvalsstrsupper(sval((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pys_boolvs( s__doc__soss setuptoolssCommands nose.cores get_parsersmainsparsersoption_blacklistsget_user_optionss nosetestssflags_bool( s_boolsoption_blacklistsget_user_optionss get_parsersparsers nosetestssflagsCommandsmainsos((s1build/bdist.darwin-8.0.1-x86/egg/nose/commands.pys?$s    , PK£žC8÷œ»Ä..nose/suite.pyc;ò è’*Fc@sædZdklZdkZdkZdkZdklZdkl Z dk l Z dk l Z eidƒZdeifd „ƒYZd efd „ƒYZd efd „ƒYZdefd„ƒYZdefd„ƒYZdS(sŸnose TestSuite subclasses that implement lazy test collection for modules, classes and directories, and provide suite-level fixtures (setUp/tearDown methods). (s generatorsN(sMethodTestCase(sConfig(s_import(stry_runs nose.suites LazySuitecBs}tZdZeiiZed„Zd„Zd„Z e d„eedƒZ d„Z d„Z d„Zd „Zd „ZRS( s¸Generator-based test suite. Pass a callable that returns an iterable of tests, and a nose.config.Config. Also provides hooks (setUp and tearDown) for suite-level fixtures. cCs0||_|tjo tƒ}n||_dS(N(s loadtestssselfs _loadtestssconfsNonesConfig(sselfs loadtestssconf((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__init__s   cCst|iƒSdS(N(sitersselfs_tests(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__iter__ sccsx|iƒD] }|Vq WdS(N(sselfs _loadtestsstest(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys loadtests#s cCs |iƒS(N(sselfs loadtests(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys(ssTests in this suite (iter)cOs|i||ŽdS(N(sselfsrunsargskw(sselfsargskw((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__call__,scCsñ|i|ƒzÏy|iƒWn6tj o ‚n"|i|tiƒƒdSnXx:|iD]/}t i d|ƒ|i oPn||ƒqaWy|i ƒWn2tj o ‚n|i|tiƒƒnX|SWd|i|ƒXdS(Nsrunning test %s(sresults startTestsselfssetUpsKeyboardInterruptsaddErrorssyssexc_infos_testsstestslogsdebugs shouldStopstearDownsstopTest(sselfsresultstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pysrun/s0   cCsdS(N((sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pyssetUpHscCst|ƒSdS(N(sstrsself(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pysshortDescriptionKscCsdS(N((sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pystearDownNs(s__name__s __module__s__doc__sunittestsTestCasesfailureExceptionsNones__init__s__iter__s loadtestsspropertys_testss__call__srunssetUpsshortDescriptionstearDown(((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys LazySuites           sGeneratorMethodTestSuitecBs tZdZd„Zd„ZRS(s5Test suite for test methods that are generators. cCs||_||_dS(N(sclssselfsmethod(sselfsclssmethod((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__init__Us ccsÞ|iƒ}t||iƒ}x¹|ƒD]®}y|d|df\}}Wn,t j o |dt ƒf\}}nXt i d||ƒt }t|ƒo|i}|}n|}t|i||i||ŒVq(WdS(Niistest_method: %s, arg: %s(sselfsclssinstsgetattrsmethodssuitestests test_methodsargs ValueErrorstupleslogsdebugsNonescasescallables__name__snamesMethodTestCase(sselfscasesargsinsts test_methodstestssuitesname((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys loadtestsYs     (s__name__s __module__s__doc__s__init__s loadtests(((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pysGeneratorMethodTestSuiteRs  s TestClasscBs2tZdZd„Zd„Zd„Zd„ZRS(s1Lazy suite that collects tests from a class. cCs ||_ti|||ƒdS(N(sclssselfs LazySuites__init__s loadtestssconf(sselfs loadtestssconfscls((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__init__ps cCs|iƒSdS(N(sselfs__repr__(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__str__tscCsd|iSdS(Ns test class %s(sselfscls(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__repr__wsccs%x|i|iƒD] }|VqWdS(N(sselfs _loadtestssclsstest(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys loadtestszs(s__name__s __module__s__doc__s__init__s__str__s__repr__s loadtests(((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys TestClassms    sTestDircBs5tZdZeed„Zd„ZeZd„ZRS(s5Lazy suite that collects tests from a directory. cCs2||_||_||_ti|||ƒdS(N(spathsselfsmodules importPaths LazySuites__init__s loadtestssconf(sselfs loadtestssconfspathsmodules importPath((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__init__‚s   cCsd|i|ifSdS(Nstest directory %s in %s(sselfspathsmodule(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__repr__ˆsccs1x*|i|i|i|iƒD] }|VqWdS(N(sselfs _loadtestsspathsmodules importPathstest(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys loadtestsŒs (s__name__s __module__s__doc__sNones__init__s__repr__s__str__s loadtests(((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pysTestDirs  s TestModulecBsYtZdZeZeeed„Zd„ZeZd„Zd„Z d„Z d„Z RS(sñLazy suite that collects tests from modules and packages. This suite collects module members that match the testMatch regular expression. For packages, it also collects any modules or packages found in the package __path__ that match testMatch. For modules that themselves do not match testMatch, the collector collects doctests instead of test functions. Before returning the first collected test, any defined setup method will be run. Packages may define setup, setUp, setup_package or setUpPackage, modules setup, setUp, setup_module, setupModule or setUpModule. Likewise, teardown will be run if defined and if setup ran successfully; teardown methods follow the same naming rules as setup methods. cCsV||_||_||_|o |tjo|i|_nti|||ƒdS(N( s moduleNamesselfspathsmodulesNones__name__s LazySuites__init__s loadtestssconf(sselfs loadtestssconfs moduleNamespathsmodule((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__init__¤s    cCsd|i|ifSdS(Nstest module %s in %s(sselfs moduleNamespath(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys__repr__­sccsc|i|i|iƒ}yx|D] }|Vq"WWn+tj ox|iD] }|VqLWnXdS(N(sselfs _loadtestssmodulespathstestsstests TypeErrors_tests(sselfsteststests((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys loadtests±s  cCs|iƒSdS(N(sselfs__str__(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pysid»scCsºtidƒ|itjoDt|i|ig|iƒ|_tid|i|i|iƒnt |idƒodddg}nddd g}|d d g7}t |i|ƒd S( sªRun any package or module setup function found. For packages, setup functions may be named 'setupPackage', 'setup_package', 'setUp', or 'setup'. For modules, setup functions may be named 'setupModule', 'setup_module', 'setUp', or 'setup'. The setup function may optionally accept a single argument; in that case, the test package or module will be passed to the setup function. sTestModule.setUpsImported %s from %s on %ss__path__s setupPackages setUpPackages setup_packages setupModules setUpModules setup_modulessetUpssetupN( slogsdebugsselfsmodulesNones_imports moduleNamespathsconfshasattrsnamesstry_run(sselfsnames((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pyssetUp¾s !cCsSt|idƒoddg}n ddg}|ddg7}t|i|ƒdS( s7Run any package or module teardown function found. For packages, teardown functions may be named 'teardownPackage', 'teardown_package' or 'teardown'. For modules, teardown functions may be named 'teardownModule', 'teardown_module' or 'teardown'. The teardown function may optionally accept a single argument; in that case, the test package or module will be passed to the teardown function. The teardown function will be run only if any package or module setup function completed successfully. s__path__steardownPackagesteardown_packagesteardownModulesteardown_modulestearDownsteardownN(shasattrsselfsmodulesnamesstry_run(sselfsnames((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pystearDownÒs  ( s__name__s __module__s__doc__sNones fromDirectorys__init__s__repr__s__str__s loadtestssidssetUpstearDown(((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys TestModule’s    (s__doc__s __future__s generatorssloggingssyssunittests nose.casesMethodTestCases nose.configsConfigs nose.importers_imports nose.utilstry_runs getLoggerslogs TestSuites LazySuitesGeneratorMethodTestSuites TestClasssTestDirs TestModule(s LazySuitesloggingslogsGeneratorMethodTestSuitesunittests TestClasss TestModulessyssMethodTestCases_imports generatorsstry_runsConfigsTestDir((s.build/bdist.darwin-8.0.1-x86/egg/nose/suite.pys?s        @PK¤žC8­¯{ëSSnose/tools.pyc;ò è’*Fc@s^dZdkZdkZdkZdddddddgZeid ƒZd „Zd eifd „ƒYZ e d ƒZ x†gi Z e e ƒD]2Zeidƒo dej oe eƒqq[ D]5ZeeƒZee eƒeƒes(scapsssubsname(sname((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pyspep8ssDummycBstZd„ZRS(NcCsdS(N((((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysnops(s__name__s __module__snop(((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysDummyssnopsasserts_cBstZRS(N(s__name__s __module__(((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pys TimeExpired&scCs|p t|‚dS(s4Shorthand for assert. Saves 3 whole characters! N(sexprsAssertionErrorsmsg(sexprsmsg((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysok_*scCs,||jpt|pd||f‚dS(s6Shorthand for 'assert a == b, "%r != %r" % (a, b) s%r != %rN(sasbsAssertionErrorsmsg(sasbsmsg((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pyseq_0scs‡d†}|SdS(s¨ Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose's additional stuff (namely, setup and teardown). cs¢tˆdƒo ˆi}n ˆi}ˆi|_ˆi|_ˆi|_t|dƒ oˆi i |_ ny ||_Wnt j o||_nX|SdS(Nscompat_func_namescompat_co_firstlineno( shasattrsfuncscompat_func_namesnames__name__s__dict__snewfuncs__doc__s __module__s func_codesco_firstlinenoscompat_co_firstlinenos TypeError(snewfuncsname(sfunc(s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysdecorate<s      N(sdecorate(sfuncsdecorate((sfuncs.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysmake_decorator6s csJdigi}ˆD]}||iƒq~ƒ‰‡‡d†}|SdS(sTest must raise one of expected exceptions to pass. Example use:: @raises(TypeError, ValueError) def test_raises_type_error(): raise TypeError("This test passes") @raises(Exception): def test_that_fails_by_passing(): pass s or cs8ˆi‰‡‡‡‡d†}tˆƒ|ƒ}|SdS(NcsPyˆ||ŽWnˆj on'‚nXdˆˆf}t|ƒ‚dS(Ns%s() did not raise %s(sfuncsargskws exceptionssnamesvalidsmessagesAssertionError(sargskwsmessage(snamesvalidsfuncs exceptions(s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysnewfunc]s(sfuncs__name__snamesnewfuncsmake_decorator(sfuncsnamesnewfunc(svalids exceptions(sfuncsnames.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysdecorate[s  N(sjoinsappends_[1]s exceptionsses__name__svalidsdecorate(s exceptionss_[1]svalidsesdecorate((s exceptionssvalids.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysraisesOs 3cs‡d†}|SdS(sTest must finish within specified time limit to pass. Example use:: @timed(.1) def test_that_fails(): time.sleep(.2) cs)‡‡d†}tˆƒ|ƒ}|SdS(NcsNtiƒ}ˆ||Žtiƒ}||ˆjotdˆƒ‚ndS(NsTime limit (%s) exceeded(stimesstartsfuncsargskwsendslimits TimeExpired(sargskwsendsstart(sfuncslimit(s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysnewfuncts    (snewfuncsmake_decoratorsfunc(sfuncsnewfunc(slimit(sfuncs.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysdecoratessN(sdecorate(slimitsdecorate((slimits.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pystimedls cCs||d„}|SdS(sDecorator to add setup and/or teardown methods to a test function:: @with_setup(setup, teardown) def test_something(): # ... Note that `with_setup` is useful *only* for test functions, not for test methods or inside of TestCase subclasses. cCs0|o ||_n|o ||_n|SdS(N(ssetupsfuncsteardown(sfuncssetupsteardown((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pysdecorate‰s   N(ssetupsteardownsdecorate(ssetupsteardownsdecorate((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pys with_setups (s__doc__srestimesunittests__all__scompilescapsspep8sTestCasesDummys_tsappends_[1]sdirsats startswithspepdsgetattrsvarssAssertionErrors TimeExpiredsNonesok_seq_smake_decoratorsraisesstimeds with_setup(sunittestsatsmake_decoratorseq_s__all__s_tspepdsres with_setupsDummyscapss TimeExpiredsok_s_[1]spep8stimestimedsraises((s.build/bdist.darwin-8.0.1-x86/egg/nose/tools.pys?s(     P      PK••6LM‡²² nose/case.py"""nose unittest.TestCase subclasses. It is not necessary to subclass these classes when writing tests; they are used internally by nose.loader.TestLoader to create test cases from test functions and methods in test classes. """ import logging import unittest from nose.util import try_run log = logging.getLogger(__name__) class FunctionTestCase(unittest.TestCase): """TestCase wrapper for functional tests. Don't use this class directly; it is used internally in nose to create test cases for functional tests. This class is very similar to unittest.FunctionTestCase, with a few extensions: * The test descriptions are disambiguated by including the full module path when a test with a similar name has been seen in the test run. * It allows setup and teardown functions to be defined as attributes of the test function. A convenient way to set this up is via the provided with_setup decorator: def setup_func(): # ... def teardown_func(): # ... @with_setup(setup_func, teardown_func) def test_something(): # ... """ _seen = {} def __init__(self, testFunc, setUp=None, tearDown=None, description=None, fromDirectory=None): self.testFunc = testFunc self.setUpFunc = setUp self.tearDownFunc = tearDown self.description = description self.fromDirectory = fromDirectory unittest.TestCase.__init__(self) def id(self): return str(self) def runTest(self): self.testFunc() def setUp(self): """Run any setup function attached to the test function """ if self.setUpFunc: self.setUpFunc() else: names = ('setup', 'setUp', 'setUpFunc') try_run(self.testFunc, names) def tearDown(self): """Run any teardown function attached to the test function """ if self.tearDownFunc: self.tearDownFunc() else: names = ('teardown', 'tearDown', 'tearDownFunc') try_run(self.testFunc, names) def __str__(self): if hasattr(self.testFunc, 'compat_func_name'): name = self.testFunc.compat_func_name else: name = self.testFunc.__name__ name = "%s.%s" % (self.testFunc.__module__, name) if self._seen.has_key(name) and self.fromDirectory is not None: # already seen this exact test name; put the # module dir in front to disambiguate the tests name = "%s: %s" % (self.fromDirectory, name) self._seen[name] = True return name __repr__ = __str__ def shortDescription(self): pass # FIXME class MethodTestCase(unittest.TestCase): """Test case that wraps one method in a test class. """ def __init__(self, cls, method, method_desc=None, case=None, *arg): self.cls = cls self.method = method self.method_desc = method_desc self.testInstance = self.cls() if case is None: self.testCase = getattr(self.testInstance, method) else: self.testCase = case self.arg = arg log.debug('Test case: %s%s', self.testCase, self.arg) unittest.TestCase.__init__(self) def __str__(self): return self.id() def desc(self): if self.method_desc is not None: desc = self.method_desc else: desc = self.method if self.arg: desc = "%s:%s" % (desc, self.arg) return desc def id(self): return "%s.%s.%s" % (self.cls.__module__, self.cls.__name__, self.desc()) def setUp(self): """Run any setup method declared in the test class to which this method belongs """ names = ('setup', 'setUp') try_run(self.testInstance, names) def runTest(self): self.testCase(*self.arg) def tearDown(self): """Run any teardown method declared in the test class to which this method belongs """ if self.testInstance is not None: names = ('teardown', 'tearDown') try_run(self.testInstance, names) def shortDescription(self): # FIXME ... diff output if is TestCase subclass, for back compat if self.testCase.__doc__ is not None: return '(%s.%s) "%s"' % (self.cls.__module__, self.cls.__name__, self.testCase.__doc__) return None PK••6fOÈÒÒ nose/suite.py"""nose TestSuite subclasses that implement lazy test collection for modules, classes and directories, and provide suite-level fixtures (setUp/tearDown methods). """ from __future__ import generators import logging import sys import unittest from nose.case import MethodTestCase from nose.config import Config from nose.importer import _import from nose.util import try_run log = logging.getLogger('nose.suite') class LazySuite(unittest.TestSuite): """Generator-based test suite. Pass a callable that returns an iterable of tests, and a nose.config.Config. Also provides hooks (setUp and tearDown) for suite-level fixtures. """ # _exc_info_to_string needs this property failureException = unittest.TestCase.failureException def __init__(self, loadtests, conf=None): self._loadtests = loadtests if conf is None: conf = Config() self.conf = conf def __iter__(self): return iter(self._tests) def loadtests(self): for test in self._loadtests(): yield test # lazy property so subclasses can override loadtests() _tests = property(lambda self: self.loadtests(), None, None, 'Tests in this suite (iter)') def __call__(self, *arg, **kw): self.run(*arg, **kw) def run(self, result): result.startTest(self) try: try: self.setUp() except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) return for test in self._tests: log.debug("running test %s", test) if result.shouldStop: break test(result) try: self.tearDown() except KeyboardInterrupt: raise except: result.addError(self, sys.exc_info()) return result finally: result.stopTest(self) def setUp(self): pass def shortDescription(self): return str(self) # FIXME def tearDown(self): pass class GeneratorMethodTestSuite(LazySuite): """Test suite for test methods that are generators. """ def __init__(self, cls, method): self.cls = cls self.method = method def loadtests(self): inst = self.cls() suite = getattr(inst, self.method) for test in suite(): try: test_method, arg = (test[0], test[1:]) except ValueError: test_method, arg = test[0], tuple() log.debug('test_method: %s, arg: %s', test_method, arg) case = None if callable(test_method): name = test_method.__name__ case = test_method else: name = test_method yield MethodTestCase( self.cls, name, self.method, case, *arg) class TestClass(LazySuite): """Lazy suite that collects tests from a class. """ def __init__(self, loadtests, conf, cls): self.cls = cls LazySuite.__init__(self, loadtests, conf) def __str__(self): return self.__repr__() def __repr__(self): return 'test class %s' % self.cls def loadtests(self): for test in self._loadtests(self.cls): yield test class TestDir(LazySuite): """Lazy suite that collects tests from a directory. """ def __init__(self, loadtests, conf, path, module=None, importPath=None): self.path = path self.module = module self.importPath = importPath LazySuite.__init__(self, loadtests, conf) def __repr__(self): return "test directory %s in %s" % (self.path, self.module) __str__ = __repr__ def loadtests(self): for test in self._loadtests(self.path, self.module, self.importPath): yield test class TestModule(LazySuite): """Lazy suite that collects tests from modules and packages. This suite collects module members that match the testMatch regular expression. For packages, it also collects any modules or packages found in the package __path__ that match testMatch. For modules that themselves do not match testMatch, the collector collects doctests instead of test functions. Before returning the first collected test, any defined setup method will be run. Packages may define setup, setUp, setup_package or setUpPackage, modules setup, setUp, setup_module, setupModule or setUpModule. Likewise, teardown will be run if defined and if setup ran successfully; teardown methods follow the same naming rules as setup methods. """ fromDirectory = None def __init__(self, loadtests, conf, moduleName=None, path=None, module=None): self.moduleName = moduleName self.path = path self.module = module if module and moduleName is None: self.moduleName = module.__name__ LazySuite.__init__(self, loadtests, conf) def __repr__(self): return "test module %s in %s" % (self.moduleName, self.path) __str__ = __repr__ def loadtests(self): tests = self._loadtests(self.module, self.path) try: for test in tests: yield test except TypeError: # python 2.3: TestSuite not iterable for test in tests._tests: yield test def id(self): return self.__str__() def setUp(self): """Run any package or module setup function found. For packages, setup functions may be named 'setupPackage', 'setup_package', 'setUp', or 'setup'. For modules, setup functions may be named 'setupModule', 'setup_module', 'setUp', or 'setup'. The setup function may optionally accept a single argument; in that case, the test package or module will be passed to the setup function. """ log.debug('TestModule.setUp') if self.module is None: self.module = _import(self.moduleName, [self.path], self.conf) log.debug('Imported %s from %s on %s', self.module, self.moduleName, self.path) if hasattr(self.module, '__path__'): names = ['setupPackage', 'setUpPackage', 'setup_package'] else: names = ['setupModule', 'setUpModule', 'setup_module'] names += ['setUp', 'setup'] try_run(self.module, names) def tearDown(self): """Run any package or module teardown function found. For packages, teardown functions may be named 'teardownPackage', 'teardown_package' or 'teardown'. For modules, teardown functions may be named 'teardownModule', 'teardown_module' or 'teardown'. The teardown function may optionally accept a single argument; in that case, the test package or module will be passed to the teardown function. The teardown function will be run only if any package or module setup function completed successfully. """ if hasattr(self.module, '__path__'): names = ['teardownPackage', 'teardown_package'] else: names = ['teardownModule', 'teardown_module'] names += ['tearDown', 'teardown'] try_run(self.module, names) PK¤žC8Ç©6 ""nose/twistedtools.pyc;ò è’*Fc@sodZdkZdklZlZdklZlZddddgZea d„Z e ƒZ ed „Z dS( sl Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted event loop. You must import this module *before* importing anything from Twisted itself! Example: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): return reactor.resolve("nose.python-hosting.com") Or, more realistically: @deferred(timeout=5.0) def test_resolve(): d = reactor.resolve("nose.python-hosting.com") def check_ip(ip): assert ip == "67.15.36.43" d.addCallback(check_ip) return d N(sQueuesEmpty(smake_decorators TimeExpiredsthreaded_reactorsreactorsdeferreds TimeExpiredcsgdkl‰t oJdkl}dkl}|d‡d†ƒatitƒti ƒnˆSdS(s³ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done. (sreactor(s threadable(sThreadstargetcsˆidtƒS(NsinstallSignalHandlers(sreactorsrunsFalse((sreactor(s5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pys3sN( stwisted.internetsreactors_twisted_threadstwisted.pythons threadables threadingsThreads setDaemonsTruesstart(s threadablesThreadsreactor((sreactors5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pysthreaded_reactor(s    cs[tƒ‰yˆtjpˆdWntj otdƒ‚nX‡‡d†}|SdS(s By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with timed() is that timed() will still wait for the test to end, while deferred() will stop the test when its timeout has expired. The latter is more desireable when dealing with network tests, because the result may actually never arrive. If the callback is triggered, the test has passed. If the errback is triggered or the timeout expires, the test has failed. Example: @deferred(timeout=5.0) def test_resolve(): return reactor.resolve("nose.python-hosting.com") Attention! If you combine this decorator with other decorators (like "raises"), deferred() must be called *first*! In other words, this is good: @raises(DNSLookupError) @deferred() def test_error(): return reactor.resolve("xxxjhjhj.biz") and this is bad: @deferred() @raises(DNSLookupError) def test_error(): return reactor.resolve("xxxjhjhj.biz") is+'timeout' argument must be a number or Nonecs,‡‡‡d†}tˆƒ|ƒ}|SdS(Nc sµtƒ‰‡d†‰‡d†‰‡‡‡‡‡‡d†}ˆi|ƒyˆidˆƒ}Wn#t j ot dˆƒ‚nX|t j o|\}}}|||‚ndS(NcsˆitƒdS(N(sqsputsNone(svalue(sq(s5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pyscallbackmscs/y|iƒWnˆitiƒƒnXdS(N(sfailuresraiseExceptionsqsputssyssexc_info(sfailure(sq(s5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pyserrbackoscsjyIˆˆˆŽ}y|iˆˆƒWntj otdƒ‚nXWnˆi t i ƒƒnXdS(Ns7you must return a twisted Deferred from your test case!( sfuncsargsskargssds addCallbacksscallbackserrbacksAttributeErrors TypeErrorsqsputssyssexc_info(sd(skargssargssqscallbacksfuncserrback(s5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pysgusstimeouts*timeout expired before end of test (%f s.)(sQueuesqscallbackserrbacksgsreactorscallFromThreadsgetstimeoutserrorsEmptys TimeExpiredsNonesexc_types exc_valuestb( sargsskargssgstbs exc_valuesqscallbackserrorsexc_typeserrback(sfuncstimeoutsreactor(sargsskargssqscallbackserrbacks5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pyswrapperks     (swrappersmake_decoratorsfunc(sfuncswrapper(stimeoutsreactor(sfuncs5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pysdecoratejs"N(sthreaded_reactorsreactorstimeoutsNones TypeErrorsdecorate(stimeoutsreactorsdecorate((stimeoutsreactors5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pysdeferred=s" %( s__doc__ssyssQueuesEmptys nose.toolssmake_decorators TimeExpireds__all__sNones_twisted_threadsthreaded_reactorsreactorsdeferred( sQueuesreactors__all__s TimeExpiredssyssdeferredsEmptysthreaded_reactorsmake_decorator((s5build/bdist.darwin-8.0.1-x86/egg/nose/twistedtools.pys?s   PK••6Y·yáánose/result.py"""Test result handlers. Base class (Result) implements plugin handling, output capture, and assert introspection, and handles deprecated and skipped tests. TextTestResult is a drop-in replacement for unittest._TextTestResult that uses the capabilities in Result. """ import inspect import logging import pdb import sys import tokenize from unittest import _TextTestResult, TestSuite try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from nose.inspector import inspect_traceback from nose.exc import DeprecatedTest, SkipTest from nose.plugins import call_plugins # buffer = StringIO() stdout = [] log = logging.getLogger('nose.result') class Result(object): """Base class for results handlers. """ capt = None conf = None tbinfo = None shouldStop = False def addDeprecated(self, test): self.resetBuffer() call_plugins(self.conf.plugins, 'addDeprecated', test) def addError(self, test, err): if self.isDeprecated(err): self.addDeprecated(test) elif self.isSkip(err): self.addSkip(test) else: self.capt = self.getBuffer() if self.conf.debugErrors: if self.conf.capture: end_capture() pdb.post_mortem(err[2]) if self.conf.capture: start_capture() self.resetBuffer() call_plugins(self.conf.plugins, 'addError', test, err, self.capt) if self.conf.stopOnError: self.shouldStop = True def addFailure(self, test, err): self.capt = self.getBuffer() if self.conf.debugFailures: if self.conf.capture: end_capture() pdb.post_mortem(err[2]) if self.conf.capture: start_capture() if self.conf.detailedErrors: try: self.tbinfo = inspect_traceback(err[2]) except tokenize.TokenError: self.tbinfo = "ERR: unable to inspect traceback" else: self.tbinfo = '' self.resetBuffer() call_plugins(self.conf.plugins, 'addFailure', test, err, self.capt, self.tbinfo) if self.conf.stopOnError: self.shouldStop = True def addSkip(self, test): self.resetBuffer() call_plugins(self.conf.plugins, 'addSkip', test) def addSuccess(self, test): self.capt = self.getBuffer() self.resetBuffer() call_plugins(self.conf.plugins, 'addSuccess', test, self.capt) def getBuffer(self): if stdout: try: return sys.stdout.getvalue() except AttributeError: pass # capture is probably off return '' def isDeprecated(self, err): if err[0] is DeprecatedTest or isinstance(err[0], DeprecatedTest): return True return False def isSkip(self, err): if err[0] is SkipTest or isinstance(err[0], SkipTest): return True return False def resetBuffer(self): if stdout: sys.stdout.truncate(0) sys.stdout.seek(0) def startTest(self, test): if self.conf.capture: self.resetBuffer() self.capt = None self.tbinfo = None call_plugins(self.conf.plugins, 'startTest', test) def stopTest(self, test): if self.conf.capture: self.resetBuffer() self.capt = None self.tbinfo = None call_plugins(self.conf.plugins, 'stopTest', test) class TextTestResult(Result, _TextTestResult): """Text test result that extends unittest's default test result with several optional features: - output capture Capture stdout while tests are running, and print captured output with errors and failures. - debug on error/fail Drop into pdb on error or failure, in the frame where the exception was raised. - deprecated or skipped tests raise DeprecatedTest or SkipTest to indicated that a test is deprecated or has been skipped. Deprecated or skipped tests will be printed with errors and failures, but don't cause the test run as a whole to be considered non-successful. """ def __init__(self, stream, descriptions, verbosity, conf): self.deprecated = [] self.skip = [] self.conf = conf self.capture = conf.capture _TextTestResult.__init__(self, stream, descriptions, verbosity) def addDeprecated(self, test): Result.addDeprecated(self, test) self.deprecated.append((test, '', '')) self.writeRes('DEPRECATED','D') def addError(self, test, err): Result.addError(self, test, err) if not self.isDeprecated(err) and not self.isSkip(err): self.errors.append((test, self._exc_info_to_string(err, test), self.capt)) self.writeRes('ERROR','E') def addFailure(self, test, err): Result.addFailure(self, test, err) self.failures.append((test, self._exc_info_to_string(err, test) + self.tbinfo, self.capt)) self.writeRes('FAIL','F') def addSkip(self, test): Result.addSkip(self, test) self.skip.append((test, '', '')) self.writeRes('SKIP','S') def addSuccess(self, test): Result.addSuccess(self, test) self.writeRes('ok', '.') def printErrors(self): log.debug('printErrors called') _TextTestResult.printErrors(self) self.printErrorList('DEPRECATED', self.deprecated) self.printErrorList('SKIPPED', self.skip) log.debug('calling plugin reports') call_plugins(self.conf.plugins, 'report', self.stream) def printErrorList(self, flavor, errors): for test, err, capt in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavor,self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln("%s" % err) if capt is not None and len(capt): self.stream.writeln(ln('>> begin captured stdout <<')) self.stream.writeln(capt) self.stream.writeln(ln('>> end captured stdout <<')) def startTest(self, test): Result.startTest(self, test) if not isinstance(test, TestSuite): _TextTestResult.startTest(self, test) def stopTest(self, test): Result.stopTest(self, test) if not isinstance(test, TestSuite): _TextTestResult.stopTest(self, test) def writeRes(self, long, short): if self.showAll: self.stream.writeln(long) else: self.stream.write(short) def _exc_info_to_string(self, err, test): try: return _TextTestResult._exc_info_to_string(self, err, test) except TypeError: # 2.3: does not take test arg return _TextTestResult._exc_info_to_string(self, err) def start_capture(): """Start capturing output to stdout. DOES NOT reset the buffer. """ log.debug('start capture from %r' % sys.stdout) stdout.append(sys.stdout) sys.stdout = StringIO() log.debug('sys.stdout is now %r' % sys.stdout) def end_capture(): """Stop capturing output to stdout. DOES NOT reset the buffer.x """ if stdout: sys.stdout = stdout.pop() log.debug('capture ended, sys.stdout is now %r' % sys.stdout) def ln(label): label_len = len(label) + 2 chunk = (70 - label_len) / 2 out = '%s %s %s' % ('-' * chunk, label, '-' * chunk) pad = 70 - len(out) if pad > 0: out = out + ('-' * pad) return out PK••6ÿ<£‹ÏÏ nose/tools.py""" Tools for testing ----------------- nose.tools provides a few convenience functions to make writing tests easier. You don't have to use them; nothing in the rest of nose depends on any of these methods. """ import re import time import unittest __all__ = ['ok_', 'eq_', 'make_decorator', 'raises', 'timed', 'with_setup', 'TimeExpired'] # # Expose assert* from unittest.TestCase # - give them pep8 style names # caps = re.compile('([A-Z])') def pep8(name): return caps.sub(lambda m: '_' + m.groups()[0].lower(), name) class Dummy(unittest.TestCase): def nop(): pass _t = Dummy('nop') for at in [ at for at in dir(_t) if at.startswith('assert') and not '_' in at ]: pepd = pep8(at) vars()[pepd] = getattr(_t, at) __all__.append(pepd) class TimeExpired(AssertionError): pass def ok_(expr, msg=None): """Shorthand for assert. Saves 3 whole characters! """ assert expr, msg def eq_(a, b, msg=None): """Shorthand for 'assert a == b, "%r != %r" % (a, b) """ assert a == b, msg or "%r != %r" % (a, b) def make_decorator(func): """ Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose's additional stuff (namely, setup and teardown). """ def decorate(newfunc): if hasattr(func, 'compat_func_name'): name = func.compat_func_name else: name = func.__name__ newfunc.__dict__ = func.__dict__ newfunc.__doc__ = func.__doc__ newfunc.__module__ = func.__module__ if not hasattr(newfunc, 'compat_co_firstlineno'): newfunc.compat_co_firstlineno = func.func_code.co_firstlineno try: newfunc.__name__ = name except TypeError: # can't set func name in 2.3 newfunc.compat_func_name = name return newfunc return decorate def raises(*exceptions): """Test must raise one of expected exceptions to pass. Example use:: @raises(TypeError, ValueError) def test_raises_type_error(): raise TypeError("This test passes") @raises(Exception): def test_that_fails_by_passing(): pass """ valid = ' or '.join([e.__name__ for e in exceptions]) def decorate(func): name = func.__name__ def newfunc(*arg, **kw): try: func(*arg, **kw) except exceptions: pass except: raise else: message = "%s() did not raise %s" % (name, valid) raise AssertionError(message) newfunc = make_decorator(func)(newfunc) return newfunc return decorate def timed(limit): """Test must finish within specified time limit to pass. Example use:: @timed(.1) def test_that_fails(): time.sleep(.2) """ def decorate(func): def newfunc(*arg, **kw): start = time.time() func(*arg, **kw) end = time.time() if end - start > limit: raise TimeExpired("Time limit (%s) exceeded" % limit) newfunc = make_decorator(func)(newfunc) return newfunc return decorate def with_setup(setup=None, teardown=None): """Decorator to add setup and/or teardown methods to a test function:: @with_setup(setup, teardown) def test_something(): # ... Note that `with_setup` is useful *only* for test functions, not for test methods or inside of TestCase subclasses. """ def decorate(func, setup=setup, teardown=teardown): if setup: func.setup = setup if teardown: func.teardown = teardown return func return decorate PK£žC8Áçèúúnose/inspector.pyc;ò è’*Fc@sÆdZdkZdkZdkZdkZdkZdkZdkZdkZydk l Z Wn e j odk l Z nXei e ƒZd„Zdd„Zd„Zdfd„ƒYZdS( s’Simple traceback introspection. Used to add additional information to AssertionErrors in tests, so that failure messages may be more informative. N(sStringIOc Cs¸tid|ƒx|io |i}qW|i}t|ƒ\}}t ||ƒ\} }t t idi| ƒƒƒ}t|i|iƒ} xœ| o”yti|i| ƒWnutij of}tid|ƒ| idƒ|d8}t t idi| ƒƒƒ}t|i|iƒ} q‘nXPq‘Wg} | ioj| iidƒ}d}xO|D]C} ||jo| i d| ƒn| i d| ƒ|d7}q\Wndi| ƒSd S( sÞInspect a traceback and its frame, returning source for the expression where the exception was raised, with simple variable replacement performed and the line on which the exception was raised marked with '>>' sinspect traceback %sssTokenizer error: %siis s>> s N(!slogsdebugstbstb_nextstb_framesframestbsourceslinessexc_linesfind_inspectable_liness inspect_liness mark_linesStringIOstextwrapsdedentsjoinssrcsExpandersf_localss f_globalssexpstokenizesreadlines TokenErrorsespopspaddedsexpanded_sourcessplits exp_linessepslinesappend( stbs exp_liness mark_linesessrcsepsframeslinessexc_linespaddeds inspect_linessexpsline((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pysinspect_tracebacksB      ic Csj|i}|i}|djo |d|d}tid||ƒyt i |ƒ\}}Wnt j ot}}qIX|}t|dƒ}tdt|t|ƒ|ƒƒ}||||!}|d|}tiddfjo |djoExB||diƒidƒo|d8}||||!}qùWqIn t}}tid||ƒ||fSdS( sGet source from a traceback object. A tuple of two things is returned: a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line. NOTE: This is adapted from inspect.py in the python 2.4 standard library, since a bug in the 2.3 version of inspect prevents it from correctly locating source lines in a traceback frame. iiislineno: %s start: %sis\s'tbsource lines '''%s''' around index %sN(stbs tb_linenoslinenostb_framesframescontextsstartslogsdebugsinspects findsourceslinessdummysIOErrorsNonesindexs all_linessmaxsminslenssyss version_infosstripsendswith( stbscontextsdummysindexs all_linessframeslinessstartslineno((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pystbsourceBs.    "#  c Cs¢tidƒ}tidƒ}tidƒ}g}||}|i |ƒi ƒd}|t |ddƒ|!} | iƒ||dt|dt|ƒƒ!}x@| D]8} |i | ƒi ƒd|jo|i| ƒq¥Pq¥W|iƒ|i|ƒt|ƒd} |i|ƒ} xg|D]_} | p|i | ƒi ƒd|jo|i| ƒ o |i| ƒ|i| ƒ} qPqWtid|| ƒ|| fSd S( s'Find lines in home that are inspectable. Walk back from the err line up to 3 lines, but don't walk back over changes in indent level. Walk forward up to 3 lines, counting \ separated lines as 1. Don't walk over changes in indent level (unless part of an extended line) s \\[\s\n]*$s :[\s\n]*$s^(\s*)iiiis#Inspecting lines '''%s''' around %sN(srescompilescntsdfsinds toinspectslinessposshomesmatchsgroupss home_indentsmaxsbeforesreversesminslensafterslinesappendshome_posssearchs continuedslogsdebug( slinessposscnts home_indentsdfsafters toinspectsindshomeslines continuedshome_possbefore((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pysfind_inspectable_linesps6  $   8 sExpandercBs tZdZd„Zd„ZRS(sxSimple expression expander. Uses tokenize to find the names and expands any that can be looked up in the frame. cCs(||_||_t|_d|_dS(Ns(slocalssselfsglobalssNoneslpossexpanded_source(sselfslocalssglobals((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pys__init__œs   cCs”|itj o|d|ijo"|id|d|i7_n0|d|ijo|id|d7_n|d|_|tijonÍ|ti jo­y4|i |}t |ƒo |}n t|ƒ}Wnctj oWy4|i|}t |ƒo |}n t|ƒ}Wq@tj o |}q@XnX|i|7_n|i|7_tid||dƒo|id7_ndS(Nis s\s+\\\ns \ (sselfslpossNonesstartsexpanded_sourcesendsttypestokenizesINDENTsNAMEslocalsstoksvalscallablesreprsKeyErrorsglobalssresmatchsline(sselfsttypestoksstartsendslinesval((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pys__call__¢s2 $"       (s__name__s __module__s__doc__s__init__s__call__(((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pysExpander˜s  (s__doc__s exceptionssinspectsloggingsressysstextwrapstokenizes tracebacks cStringIOsStringIOs ImportErrors getLoggers__name__slogsinspect_tracebackstbsourcesfind_inspectable_linessExpander(s tracebacksloggingslogsStringIOsinspect_tracebacksinspectstextwrapssyssresfind_inspectable_linesstokenizes exceptionssExpanderstbsource((s2build/bdist.darwin-8.0.1-x86/egg/nose/inspector.pys?s"         . . (PK••6`ë#%55nose/config.pyimport os import re import sys class Config(object): """nose configuration. For internal use only. """ def __init__(self, **kw): self.testMatch = re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep) self.addPaths = True self.capture = True self.detailedErrors = False self.debugErrors = False self.debugFailures = False self.exclude = None self.includeExe = sys.platform=='win32' self.ignoreFiles = [ re.compile(r'^\.'), re.compile(r'^_'), re.compile(r'^setup\.py$') ] self.include = None self.plugins = [] self.srcDirs = ['lib', 'src'] self.stopOnError = False self.tests = [] self.verbosity = 1 self._where = None self._working_dir = None self.update(kw) self._orig = self.__dict__.copy() def get_where(self): return self._where def set_where(self, val): self._where = val self._working_dir = None def get_working_dir(self): val = self._working_dir if val is None: if isinstance(self.where, list) or isinstance(self.where, tuple): val = self._working_dir = self.where[0] else: val = self._working_dir = self.where return val def set_working_dir(self, val): self._working_dir = val def __str__(self): # FIXME -- in alpha order return repr(self.__dict__) def reset(self): self.__dict__.update(self._orig) def todict(self): return self.__dict__.copy() def update(self, d): self.__dict__.update(d) # properties where = property(get_where, set_where, None, "The list of directories where tests will be discovered") working_dir = property(get_working_dir, set_working_dir, None, "The current working directory (the root " "directory of the current test run).") PK¢žC8>g‡i<<nose/loader.pyc;ò è’*Fc@s dZdklZdkZdkZdkZdkZdkZdkl Z l Z dk Tdk l Z dklZdklZdklZd klZlZlZlZlZd klZlZlZlZeie ƒZ!d ei"fd „ƒYZ"e"Z#d „Z$dS(sDiscovery-based test loader. (s generatorsN(s isfunctionsismethod(s*(sConfig(sadd_path(s call_plugins(sdefaultSelector(s LazySuites TestClasssTestDirs TestModulesGeneratorMethodTestSuite(s func_linenos is_generatorssplit_test_namestry_runs TestLoadercBs˜tZdZeed„Zeed„Zed„Zeed„Zeed„Zed„Z eed„Z d„Z ed „Z d „Z d „ZRS( s±Default nose test loader. Methods that shadow those in unittest.TestLoader are compatible with the usage in the base class. Others may be generators or interpret 'module' as the module prefix of the thing to be loaded, not the module to be examined, for example. Integrates closely with nose.selector.Selector to determine what is a test, and classes in nose.suite to defer loading as long as possible. cCs\|tjo tƒ}n||_|tjot|ƒ}n||_|ii|_dS(N(sconfsNonesConfigsselfsselectorsdefaultSelectorsplugins(sselfsconfsselector((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys__init__"s     c cstid|||ƒ|tjodSntii|ƒ ot d|ƒ‚n||i _ |i i ot |ƒn|i id„} ti|ƒ}|i| ƒxf|D]^}t}tid||ƒtii||ƒ}x'|i|d|d|ƒD] }|VqÿWq¯WdS(s¾Find tests in a directory. Each item in the directory is tested against self.selector, wantFile or wantDirectory as appropriate. Those that are wanted are returned. s%s load tests in %s [%s]Ns2Dir paths must be specified as absolute paths (%s)cCsc|i|ƒo|i|ƒ odSn*|i|ƒo|i|ƒ odSnt||ƒSdS(Niiÿÿÿÿ(smssearchsasbscmp(sasbsm((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys test_last@s !!scandidate %s in %ssmodules importPath(slogsinfosselfsdirnamesmodulesNonesosspathsisabss ValueErrorsconfs working_dirsaddPathssadd_paths testMatchs test_lastslistdirsentriesssortsitemstestssdebugsjoinsloadTestsFromNames importPathstest( sselfsdirnamesmodules importPathstestssitemsentriesstestspaths test_last((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromDir+s,      cCs<tid||ƒg}|ii|ƒoAtid|iƒx+|i ||ƒD]}|i |ƒqRWnxh|i i D]Z}t|dƒoDtid|i|iƒx(|i|ƒD]}|i |ƒq¹WqzqzWt|dƒo|io9|id}|i t|i|i ||i|ƒƒn|i|ƒSdS(s:Load tests from module at (optional) import path. sload from module %s (%s)sload tests from %ssloadTestsFromModules"collect tests in %s with plugin %ss__path__iN(slogsdebugsmodules importPathstestssselfsselectorswantModuleTestss__name__s testsInModulestestsappendsconfspluginssplugshasattrsnamesloadTestsFromModules__path__spathsTestDirsloadTestsFromDirs suiteClass(sselfsmodules importPathsplugstestsstestspath((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromModuleRs*   ccs[|tj od||f}n|tjo|ii}nt|i|i||ƒVdS(s›Load tests from module_name. Specifiy module (name) to load module from that module. Specify import path to import from that path. s%s.%sN( spackagesNones module_names importPathsselfsconfs working_dirs TestModulesloadTestsFromModule(sselfs module_namespackages importPath((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromModuleNameos   c csy |i}Wntj onXt}t|ƒ\} }} t i d|| || fƒ| ot ii | ƒoIt i d| ƒ|ii||ƒo|i| d|d|ƒ}qbq£t ii| ƒot i d| ƒ|ii| ƒoZt ii| dƒ}t ii|ƒo|i| d|d|ƒ}qN|i| ƒ}qbq£t id| ƒn>|o|i|d|d|ƒ}n|otd ƒ‚n|ox|D] }|Vq±WnxI|iD]>}t|d ƒo(x%|i |||ƒD] }|VqùWqÍqÍWd S( sÔLoad tests from test name. Name may be a file, directory or module. Specify module (or module) as name to load from a particular module. Specify importPath to load from that path. s8test name %s resolves to path %s, module %s, callable %ss %s is a filesmodules importPaths%s is a directorys __init__.pys%s is neither file nor pathspackages(No module or file specified in test namesloadTestsFromNameN(!smodules__name__sAttributeErrorsNonestestsssplit_test_namesnamespathsmod_namesfnslogsdebugsossisfilesselfsselectorswantFilesloadTestsFromPaths importPathsisdirs wantDirectorysjoinsinitsexistssloadTestsFromDirswarningsloadTestsFromModuleNames ValueErrorstestspluginssplugshasattrsloadTestsFromName( sselfsnamesmodules importPathsplugstestsstestsinitsmod_namespathsfn((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromName|sR      c Cs&d„}|oÇtid|ƒ|oD|iiigi }|D]}||||i ƒƒqB~ƒnyt ii|idƒ} Wn(tj ot ii|iƒ} nXt|i|id|d| ƒSn?g}x5|D]-}x$|i|ƒD]}|i |ƒqúWqäW|i|ƒSdS(sDLoad tests from names. Behavior is compatible with unittest: if module is specified, all names are translated to be relative to that module; the tests are appended to conf.tests, and loadTestsFromModule() is called. Otherwise, the names are loaded one by one using loadTestsFromName. cCs1|idƒ od|}nd||fSdS(Ns:s%s%s(snames startswithsmod(snamesmod((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysrel»ssload tests from module %rismodulespathN(srelsmoduleslogsdebugsnamessselfsconfstestssextendsappends_[1]sns__name__sosspathsdirnames__path__smpathsAttributeErrors__file__s TestModulesloadTestsFromModulesnamesloadTestsFromNamestests suiteClass( sselfsnamessmodulestestssnamesns_[1]srelstestsmpath((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromNames´s* D ccsHtii|ƒ\}}|tjo |}ntid|||ƒt }tii |ƒo(|i dƒo|d }q³t }n.tiitii|dƒƒ o t }n|o>|tj od||f}nt|i|i||ƒVnxI|iD]>}t|dƒo(x%|i|||ƒD] }|Vq.WqqWdS(s3Load tests from file or directory at path. spath %s is %s in %ss.pyiýÿÿÿs __init__.pys%s.%ssloadTestsFromPathN(sosspathssplitsheadstests importPathsNoneslogsdebugsTruesispymodsisfilesendswithsFalsesexistssjoinsmodules TestModulesselfsloadTestsFromModulesconfspluginssplugshasattrsloadTestsFromPath(sselfspathsmodules importPathsplugsheadsispymodstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromPathØs.   #    cCswtid|ƒ|i|ƒ}|io|i|iƒnt|t i ƒo |}n t |ƒ}t ||ƒSdS(Nscollect tests in class %s(slogsdebugsclssselfstestsInTestCases collectedssortTestMethodsUsingssorts issubclasssunittestsTestCasesmaketestsmethod_test_casesmap(sselfsclssmaketests collected((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysloadTestsFromTestCaseôs   c Cs™d„}t|ƒ}g}g}x|D]}tid|ƒt ||ƒ} t | t t ifƒoJtid| ƒ|ii| ƒo#|it|i|i| ƒƒq0q(t| ƒostid| ƒ|ii| ƒ oq(nt| ƒo*tid| ƒ|i|i| ƒƒq0|i| ƒq(q(W|i|ƒ|igi}|D]} |t| d|ƒƒqU~ƒtid||iƒ|SdS( s­Find functions and classes matching testMatch, as well as classes that descend from unittest.TestCase, return all found (properly wrapped) as tests. cCsGyt|ƒ}t|ƒ}Wntj o dSnXt||ƒSdS(s4Compare functions by their line numbers iN(s func_linenosasa_lnsbsb_lnsAttributeErrorscmp(sasbsa_lnsb_ln((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pyscmp_lines  smodule candidate %sscandidate %s is a classscandidate %s is a functionstest %s is a generators fromDirectorysLoaded tests %s from module %sN( scmp_linesdirsmodulesentriesstestss func_testssitemslogsdebugsgetattrstests isinstancestypestypess ClassTypesselfsselectors wantClasssappends TestClasssloadTestsFromTestCasesconfs isfunctions wantFunctions is_generatorsextends generateTestsssorts_[1]sFunctionTestCases importPaths__name__( sselfsmodules importPathscmp_linestestss func_testssitems_[1]sentriesstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys testsInModuleÿs4    :cCség}|ttfjo|Snxjt|ƒD]\}t||tƒ}t i d||ƒt |ƒo|i i|ƒo|i|ƒq.q.WxP|iD]E}|i|ƒ}x-|D]%}||j o|i|ƒq´q´Wq˜W|SdS(NsCheck if selector wants %s (%s)(s collectedsclssobjectstypesdirsitemsgetattrsNonesattrslogsdebugsismethodsselfsselectors wantMethodsappends __bases__sbasestestsInTestCases basetestsstest(sselfsclssattrstests basetestssitemsbases collected((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pystestsInTestCase,s"   cCs1g}x |ƒD]}|d„}|i|_yd|i|df|_Wn-tj o!d|i|df|_nXdddf}ddd f}x<|D]4}t ||ƒot ||t ||ƒƒPq¡q¡Wx<|D]4}t ||ƒot ||t ||ƒƒPqàqàW|i|ƒqW|Sd S( siGenerate tests from a test function that is a generator. Returns list of test functions. cCs|d|dŒdS(Nii(sexpr(sexpr((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysrunEss%s:%sissetupssetUps setUpFuncsteardownstearDowns tearDownFuncN(scasesstestsexprsruns __module__s__name__s TypeErrorscompat_func_namessetupsteardownsnameshasattrssetattrsgetattrsappend(sselfstestsrunsnamesteardownsexprscasesssetup((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys generateTests>s2     (s__name__s __module__s__doc__sNones__init__sloadTestsFromDirsloadTestsFromModulesloadTestsFromModuleNamesloadTestsFromNamesloadTestsFromNamessloadTestsFromPathsloadTestsFromTestCases testsInModulestestsInTestCases generateTests(((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys TestLoaders  '  8 $ - cs‡d†}|SdS(s4Return a method test case factory bound to cls. cs>tˆ|ƒ}t|ƒotˆ|ƒSntˆ|ƒSdS(sŒMethod test case factory. May return a method test case, or a generator method test suite, if the test case is a generator. N(sgetattrsclss test_namesattrs is_generatorsGeneratorMethodTestSuitesMethodTestCase(s test_namesattr(scls(s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysmake_test_caseas  N(smake_test_case(sclssmake_test_case((sclss/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pysmethod_test_case^s (%s__doc__s __future__s generatorssloggingsosssysstypessunittestsinspects isfunctionsismethods nose.cases nose.configsConfigs nose.importersadd_paths nose.pluginss call_pluginss nose.selectorsdefaultSelectors nose.suites LazySuites TestClasssTestDirs TestModulesGeneratorMethodTestSuites nose.utils func_linenos is_generatorssplit_test_namestry_runs getLoggers__name__slogs TestLoadersdefaultTestLoadersmethod_test_case(smethod_test_casesGeneratorMethodTestSuitesadd_pathsunittests TestClassstry_runssplit_test_names func_linenosConfigslogs is_generators TestModules generatorss isfunctionsTestDirs TestLoadersdefaultSelectorssysstypessdefaultTestLoadersloggings LazySuitesismethodsoss call_plugins((s/build/bdist.darwin-8.0.1-x86/egg/nose/loader.pys?s&          %ÿDPK••6ÞÊQXžž nose/proxy.py"""Compatibility shim for running under the setuptools test command. The ResultProxy wraps the actual TestResult passed to a test and implements output capture and plugin support. TestProxy wraps test cases and in those wrapped test cases, wraps the TestResult with a ResultProxy. To enable this functionality, use ResultProxySuite as the suiteClass in a TestLoader. """ import logging import unittest from nose.result import Result, ln log = logging.getLogger(__name__) class ResultProxy(Result): """Result proxy. Performs nose-specific result operations, such as handling output capture, inspecting assertions and calling plugins, then delegates to another result handler. """ def __init__(self, result): self.result = result def addError(self, test, err): log.debug('Proxy addError %s %s', test, err) Result.addError(self, test, err) # compose a new error object that includes captured output if self.capt is not None and len(self.capt): ec, ev, tb = err ev = '\n'.join([str(ev) , ln('>> begin captured stdout <<'), self.capt, ln('>> end captured stdout <<')]) err = (ec, ev, tb) self.result.addError(test, err) def addFailure(self, test, err): log.debug('Proxy addFailure %s %s', test, err) Result.addFailure(self, test, err) # compose a new error object that includes captured output # and assert introspection data ec, ev, tb = err if self.tbinfo is not None and len(self.tbinfo): ev = '\n'.join([str(ev), self.tbinfo]) if self.capt is not None and len(self.capt): ev = '\n'.join([str(ev) , ln('>> begin captured stdout <<'), self.capt, ln('>> end captured stdout <<')]) err = (ec, ev, tb) self.result.addFailure(test, err) def addSuccess(self, test): Result.addSuccess(self, test) self.result.addSuccess(test) def startTest(self, test): Result.startTest(self, test) self.result.startTest(test) def stopTest(self, test): Result.stopTest(self, test) self.result.stopTest(test) def _get_shouldStop(self): return self.result.shouldStop def _set_shouldStop(self, val): self.result.shouldStop = val shouldStop = property(_get_shouldStop, _set_shouldStop) class ResultProxySuite(unittest.TestSuite): """Test suite that supports output capture, etc, by wrapping each test in a TestProxy. """ def __iter__(self): # Needed for 2.3 compatibility return iter(self._tests) def addTest(self, test): """Add test, first wrapping in TestProxy""" self._tests.append(TestProxy(test)) class TestProxy(unittest.TestCase): """Test case that wraps the test result in a ResultProxy. """ resultProxy = ResultProxy def __init__(self, wrapped_test): self.wrapped_test = wrapped_test log.debug('%r.__init__', self) def __call__(self, *arg, **kw): log.debug('%r.__call__', self) self.run(*arg, **kw) def __repr__(self): return "TestProxy for: %r" % self.wrapped_test def __str__(self): return str(self.wrapped_test) def id(self): return self.wrapped_test.id() def run(self, result): log.debug('TestProxy run test %s in proxy %s for result %s', self, self.resultProxy, result) self.wrapped_test(self.resultProxy(result)) def shortDescription(self): return self.wrapped_test.shortDescription() PK£žC85ßòô¯¯ nose/util.pyc;ò è’*Fc@sdZdkZdkZdkZdkZdkZdkZdkZdkl Z ydk l Z Wn e j odk l Z nXdk lZeidƒZd„Zed„Zd„Zd „Zd „Zd „Zd „Zd „Zd„Zd„ZdS(s7Utility functions and classes used by nose internally. N(s CO_GENERATOR(sStringIO(sConfigsnosecCs|tii|ƒ o7tiitiitiitiƒ|ƒƒƒ}n|tjptii|ƒ otSn|SdS(sUReturn absolute, normalized path to directory, if it exists; None otherwise. N( sosspathsisabssnormpathsabspathsjoinsgetcwdsNonesisdir(spath((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pysabsdirs$!cCsÇ|}|tjotiƒ}nt|tƒp t|tƒo=x2|D]*}t ||ƒ}|tj o|SqJqJWtSntii |ƒ o1tii tiitii||ƒƒƒ}n|tjptii|ƒ oN|tiƒjo7tii tiitiitiƒ|ƒƒƒ}q4n|tjptii|ƒ otSntii|ƒo4tii|dƒ}tii|ƒo|Sq¿ntii|ƒo|SntSdS(s«Return absolute, normalized path to file (optionally in directory where), or None if the file can't be found either in where or the current working directory. s __init__.pyN(spathsorigswheresNonesossgetcwds isinstancesliststuples maybe_pathsabsfiles maybe_abssisabssnormpathsabspathsjoinsexistssisdirsinitsisfile(spathswheres maybe_abssinits maybe_pathsorig((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pysabsfile!s4    1!$! cCs.x#|D]}||ƒotSqqWtSdS(N(siterablesitems predicatesTruesFalse(s predicatesiterablesitem((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pysanypBs   cCs$tii|ƒp |idƒSdS(Ns.py(sosspathsdirnamesnamesendswith(sname((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pys file_likeIscCs/y |iSWntj o|iiSnXdS(srGet the line number of a function. First looks for compat_co_firstlineno, then func_code.co_first_lineno. N(sfuncscompat_co_firstlinenosAttributeErrors func_codesco_firstlineno(sfunc((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pys func_linenoMs  cCs6y|iit@djSWntj o tSnXdS(Ni(sfuncs func_codesco_flagss CO_GENERATORsAttributeErrorsFalse(sfunc((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pys is_generatorWscCs'|idƒ}t|ƒ}|djo/t|ƒo|ttfSqàt|tfSnŠ|djo$di|dd!ƒ}|d}nY|\}}t|ƒdjo9t|ƒ ot d||fƒ‚n|ttfSn|o/t|ƒo|t|fSq#t||fSntt|fSdS(s3Split a test name into a 3-tuple containing file, module, and callable names, any of which (but not all) may be blank. Test names are in the form: file_or_module:callable Either side of the : may be dotted. To change the splitting behavior, you can alter nose.util.split_test_re. s:iiiiÿÿÿÿsOTest name '%s' is ambiguous; can't tell if ':%s' refers to a module or callableN( stestssplitspartsslensnums file_likesNonesjoins file_or_modsfns ValueError(stestsnumspartss file_or_modsfn((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pyssplit_test_name^s(       cCs*t|ƒ}|tijo tii|iƒ|i fSn|ti jo6t i |i }tii|iƒ|i |i fSn|ttifjo6t i |i }tii|iƒ|i |i fSn|tijot|iƒSn|tijo9t|iƒ}|d|dd|d|i ffSnt|tiƒoÅt|dƒot|iƒSnt|dƒot|iƒSnt|dƒot|iƒSnt|iƒ}y |i}Wntj o|i }nX|d|dd|d|ffSnt!d||fƒ‚d S( sfFind the test address for a test, which may be a module, filename, class, method or function. iis%s.%sistestFuncs_FunctionTestCase__testFuncstestCasesI don't know what %s is (%s)N("stypestestststypess ModuleTypesosspathsabspaths__file__s__name__s FunctionTypessyssmoduless __module__sms ClassTypes InstanceTypes test_addresss __class__s MethodTypesim_classscls_adrs isinstancesunittestsTestCaseshasattrstestFuncs_FunctionTestCase__testFuncstestCases_TestCase__testMethodNames method_namesAttributeErrors_testMethodNames TypeError(stests method_namesmstscls_adr((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pys test_address‰s:  &&* 'cCsGx@|D]8}t||tƒ}|tj ot|ƒtijoßyt i |ƒ\}}}}Wnˆtj o|t|dƒo |i}ny,t i |ƒ\}}}}|idƒWqìtj otd||fƒ‚qìXnXt|ƒo$tid|||ƒ||ƒSq!ntid||ƒ|ƒSqqWdS(sËGiven a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests. s__call__isaAttribute %s of %r is not a python function. Only functions or callables may be used as fixtures.scall fixture %s.%s(%s)scall fixture %s.%sN(snamessnamesgetattrsobjsNonesfuncstypestypess ModuleTypesinspects getargspecsargssvarargssvarkwsdefaultss TypeErrorshasattrs__call__spopslenslogsdebug(sobjsnamessnamesvarkwsargssfuncsvarargssdefaults((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pystry_runµs*    cCsx|tjotSny|igƒ|SWntj onXytid|ƒSWntj ot|ƒSnXdS(s”Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. s\s*,\s*N(svalsNonesextendsAttributeErrorsressplits TypeErrorslist(sval((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pystolistÕs  (s__doc__sinspectsloggingsossressysstypessunittestscompiler.constss CO_GENERATORs cStringIOsStringIOs ImportErrors nose.configsConfigs getLoggerslogsabsdirsNonesabsfilesanyps file_likes func_linenos is_generatorssplit_test_names test_addressstry_runstolist(sabsfilesunitteststry_runssplit_test_names func_linenosConfigs file_likeslogs is_generatorsabsdirsanypsres test_addressstolistsinspectssysstypess CO_GENERATORsloggingsStringIOsos((s-build/bdist.darwin-8.0.1-x86/egg/nose/util.pys?s0          !    + , PK£žC8È&\G<G<nose/__init__.pyc;ò è’*Fc@sþdZdklZlZlZlZlZlZlZdk l Z l Z dk l Z dklZdklZdklZdklZlZlZdZd d d fZd ieeeƒƒZd dddddddddddddddgZdS(s¬5nose: a discovery-based unittest extension. nose provides an alternate test discovery and running process for unittest, one that is intended to mimic the behavior of py.test as much as is reasonably possible without resorting to too much magic. Basic usage ----------- Use the nosetests script (after installation by setuptools):: nosetests [options] [(optional) test files or directories] In addition to passing command-line options, you may also put configuration options in a .noserc or nose.cfg file in your home directory. These are standard .ini-style config files. Put your nosetests configuration in a [nosetests] section, with the -- prefix removed:: [nosetests] verbosity=3 with-doctest There are several other ways to use the nose test runner besides the `nosetests` script. You may use nose in a test script:: import nose nose.main() If you don't want the test script to exit with 0 on success and 1 on failure (like unittest.main), use nose.run() instead:: import nose result = nose.run() `result` will be true if the test run succeeded, or false if any test failed or raised an uncaught exception. Lastly, you can run nose.core directly, which will run nose.main():: python /path/to/nose/core.py Please see the usage message for the nosetests script for information about how to control which tests nose runs, which plugins are loaded, and the test output. Features -------- Writing tests is easier ======================= nose collects tests from `unittest.TestCase` subclasses, of course. But you can also write simple test functions, and test classes that are not subclasses of `unittest.TestCase`. nose also supplies a number of helpful functions for writing timed tests, testing for exceptions, and other common use cases. See `Writing tests`_ and `Testing tools`_ for more. Running tests is easier ======================= nose collects tests automatically, as long as you follow some simple guidelines for organizing your library and test code. There's no need to manually collect test cases into test suites. Running tests is also more responsive, since nose begins running tests as soon as the first test module is loaded. See `Finding and running tests`_ for more. Setting up your test environment is easier ========================================== nose supports fixtures at the package, module, and test case level, so expensive initialization can be done as infrequently as possible. See Fixtures_ for more. Doing what you want to do is easier =================================== nose has plugin hooks for loading, running, watching and reporting on tests and test runs. If you don't like the default collection scheme, or it doesn't suit the layout of your project, or you need reports in a format different from the unittest standard, or you need to collect some additional information about tests (like code coverage or profiling data), you can write a plugin to do so. See `Writing plugins`_ for more. Output capture ============== Unless called with the -s (--nocapture) switch, nose will capture stdout during each test run, and print the captured output only for tests that fail or have errors. The captured output is printed immediately following the error or failure output for the test. (Note that output in teardown methods is captured, but can't be output with failing tests, because teardown has not yet run at the time of the failure.) Assert introspection ==================== When run with the -d (--detailed-errors) switch, nose will try to output additional information about the assert expression that failed with each failing test. Currently, this means that names in the assert expression will be expanded into any values found for them in the locals or globals in the frame in which the expression executed. In other words if you have a test like:: def test_integers(): a = 2 assert a == 4, "assert 2 is 4" You will get output like:: File "/path/to/file.py", line XX, in test_integers: assert a == 4, "assert 2 is 4" AssertionError: assert 2 is 4 >> assert 2 == 4, "assert 2 is 4" Please note that dotted names are not expanded, and callables are not called in the expansion. Setuptools integration ====================== nose may be used with the setuptools_ test command. Simply specify nose.collector as the test suite in your setup file:: setup ( # ... test_suite = 'nose.collector' ) Then to find and run tests, you can run:: python setup.py test When running under setuptools, you can configure nose settings via the environment variables detailed in the nosetests script usage message. Please note that when run under the setuptools test command, some plugins will not be available, including the builtin coverage, profiler, and missed test plugins. nose also includes its own setuptools command, `nosetests`, that provides support for all plugins and command line options, as well as configuration using the setup.cfg file. See nose.commands_ for more information about the `nosetests` command. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _nose.commands: #commands .. _Writing plugins: http://code.google.com/p/python-nose/wiki/WritingPlugins Writing tests ------------- As with py.test, nose tests need not be subclasses of `unittest.TestCase`. Any function or class that matches the configured testMatch regular expression (`(?:^|[\b_\.-])[Tt]est)` by default) and lives in a module that also matches that expression will be run as a test. For the sake of compatibility with legacy unittest test cases, nose will also load tests from `unittest.TestCase` subclasses just like unittest does. Like py.test, functional tests will be run in the order in which they appear in the module file. TestCase derived tests and other test classes are run in alphabetical order. Fixtures ======== nose supports fixtures (setup and teardown methods) at the package, module, and test level. As with py.test or unittest fixtures, setup always runs before any test (or collection of tests for test packages and modules); teardown runs if setup has completed successfully, whether or not the test or tests pass. For more detail on fixtures at each level, see below. Test packages ============= nose allows tests to be grouped into test packages. This allows package-level setup; for instance, if you need to create a test database or other data fixture for your tests, you may create it in package setup and remove it in package teardown once per test run, rather than having to create and tear it down once per test module or test case. To create package-level setup and teardown methods, define setup and/or teardown functions in the `__init__.py` of a test package. Setup methods may be named `setup`, `setup_package`, `setUp`, or `setUpPackage`; teardown may be named `teardown`, `teardown_package`, `tearDown` or `tearDownPackage`. Execution of tests in a test package begins as soon as the first test module is loaded from the test package. Test modules ============ A test module is a python module that matches the testMatch regular expression. Test modules offer module-level setup and teardown; define the method `setup`, `setup_module`, `setUp` or `setUpModule` for setup, `teardown`, `teardown_module`, or `tearDownModule` for teardown. Execution of tests in a test module begins after all tests are collected. Test classes ============ A test class is a class defined in a test module that is either a subclass of `unittest.TestCase`, or matches testMatch. Test classes that don't descend from `unittest.TestCase` are run in the same way as those that do: methods in the class that match testMatch are discovered, and a test case constructed to run each with a fresh instance of the test class. Like `unittest.TestCase` subclasses, other test classes may define setUp and tearDown methods that will be run before and after each test method. Test functions ============== Any function in a test module that matches testMatch will be wrapped in a `FunctionTestCase` and run as a test. The simplest possible failing test is therefore:: def test(): assert False And the simplest passing test:: def test(): pass Test functions may define setup and/or teardown attributes, which will be run before and after the test function, respectively. A convenient way to do this, especially when several test functions in the same module need the same setup, is to use the provided with_setup decorator:: def setup_func(): # ... def teardown_func(): # ... @with_setup(setup_func, teardown_func) def test(): # ... For python 2.3, add the attributes by calling the decorator function like so:: def test(): # ... test = with_setup(setup_func, teardown_func)(test) or by direct assignment:: test.setup = setup_func test.teardown = teardown_func Please note that `with_setup` is useful *only* for test functions, not for test methods in TestCase subclasses or other test classes. For those cases, define `setUp` and `tearDown` methods in the class. Test generators =============== nose supports test functions and methods that are generators. A simple example from nose's selftest suite is probably the best explanation:: def test_evens(): for i in range(0, 5): yield check_even, i, i*3 def check_even(n, nn): assert n % 2 == 0 or nn % 2 == 0 This will result in 4 tests. nose will iterate the generator, creating a function test case wrapper for each tuple it yields. As in the example, test generators must yield tuples, the first element of which must be a callable and the remaining elements the arguments to be passed to the callable. Setup and teardown functions may be used with test generators. The setup and teardown attributes must be attached to the generator function:: @with_setup(setup_func, teardown_func) def test_generator(): ... yield func, arg, arg ... The setup and teardown functions will be executed for each test that the generator returns. For generator methods, the setUp and tearDown methods of the class (if any) will be run before and after each generated test case. Please note that method generators *are not* supported in `unittest.TestCase` subclasses. Finding and running tests ------------------------- nose, by default, follows a few simple rules for test discovery. * If it looks like a test, it's a test. Names of directories, modules, classes and functions are compared against the testMatch regular expression, and those that match are considered tests. Any class that is a `unittest.TestCase` subclass is also collected, so long as it is inside of a module that looks like a test. * Directories that don't look like tests and aren't packages are not inspected. * Packages are always inspected, but they are only collected if they look like tests. This means that you can include your tests inside of your packages (somepackage/tests) and nose will collect the tests without running package code inappropriately. * When a project appears to have library and test code organized into separate directories, library directories are examined first. * When nose imports a module, it adds that module's directory to sys.path; when the module is inside of a package, like package.module, it will be loaded as package.module and the directory of *package* will be added to sys.path. Be aware that plugins and command line options can change any of those rules. Testing tools ------------- The nose.tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in `unittest.TestCase` (only spelled in pep08 fashion, so assert_equal rather than assertEqual). See `nose.tools`_ for a complete list. .. _nose.tools: http://code.google.com/p/python-nose/wiki/TestingTools About the name -------------- * nose is the least silly short synonym for discover in the dictionary.com thesaurus that does not contain the word 'spy'. * Pythons have noses * The nose knows where to find your tests * Nose Obviates Suite Employment Contact the author ------------------ You can email me at jpellerin+nose at gmail dot com. To report bugs, ask questions, or request features, please use the *issues* tab at the Google code site: http://code.google.com/p/python-nose/issues/list. Patches are welcome! Similar test runners -------------------- nose was inspired mainly by py.test_, which is a great test runner, but formerly was not all that easy to install, and is not based on unittest. Test suites written for use with nose should work equally well with py.test, and vice versa, except for the differences in output capture and command line arguments for the respective tools. .. _py.test: http://codespeak.net/py/current/doc/test.html License and copyright --------------------- nose is copyright Jason Pellerin 2005-2007 This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA (s TestCollectors collectors configuresmainsrunsrun_exits runmodule(sSkipTestsDeprecatedTest(s TestLoader(s LazySuite(sTextTestResult(s with_setup(s file_likessplit_test_names test_addresssJason Pellerinii is.sTextTestResults LazySuitesSkipTestsDeprecatedTests TestCollectors TestLoaders collectors configuresmainsrunsrun_exits runmodules with_setups file_likessplit_test_names test_addressN(s__doc__s nose.cores TestCollectors collectors configuresmainsrunsrun_exits runmodulesnose.excsSkipTestsDeprecatedTests nose.loaders TestLoaders nose.suites LazySuites nose.resultsTextTestResults nose.toolss with_setups nose.utils file_likessplit_test_names test_addresss __author__s__versioninfo__sjoinsmapsstrs __version__s__all__(sSkipTestsDeprecatedTestssplit_test_names collectorsTextTestResults file_likes__all__s TestCollectors runmodules__versioninfo__s with_setups test_addresss __version__s TestLoadersruns configures __author__smainsrun_exits LazySuite((s1build/bdist.darwin-8.0.1-x86/egg/nose/__init__.pys?xs1    PK£žC8Mh¥àCC nose/exc.pyc;ò è’*Fc@s6dZdefd„ƒYZdefd„ƒYZdS(s7Exceptions for marking tests as skipped or deprecated. sDeprecatedTestcBstZdZRS(s7Raise this exception to mark a test as deprecated. (s__name__s __module__s__doc__(((s,build/bdist.darwin-8.0.1-x86/egg/nose/exc.pysDeprecatedTests sSkipTestcBstZdZRS(s4Raise this exception to mark a test as skipped. (s__name__s __module__s__doc__(((s,build/bdist.darwin-8.0.1-x86/egg/nose/exc.pysSkipTests N(s__doc__s ExceptionsDeprecatedTestsSkipTest(sSkipTestsDeprecatedTest((s,build/bdist.darwin-8.0.1-x86/egg/nose/exc.pys?sPK¤žC8"9x44nose/proxy.pyc;ò è’*Fc@s†dZdkZdkZdklZlZeieƒZdefd„ƒYZ dei fd„ƒYZ dei fd„ƒYZ dS( smCompatibility shim for running under the setuptools test command. The ResultProxy wraps the actual TestResult passed to a test and implements output capture and plugin support. TestProxy wraps test cases and in those wrapped test cases, wraps the TestResult with a ResultProxy. To enable this functionality, use ResultProxySuite as the suiteClass in a TestLoader. N(sResultslns ResultProxycBsetZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z e e e ƒZ RS( sºResult proxy. Performs nose-specific result operations, such as handling output capture, inspecting assertions and calling plugins, then delegates to another result handler. cCs ||_dS(N(sresultsself(sselfsresult((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__init__scCs¯tid||ƒti|||ƒ|itj o t |iƒoR|\}}}di t|ƒtdƒ|itdƒgƒ}|||f}n|ii||ƒdS(NsProxy addError %s %ss s>> begin captured stdout <> end captured stdout <<(slogsdebugstestserrsResultsaddErrorsselfscaptsNoneslensecsevstbsjoinsstrslnsresult(sselfstestserrsevstbsec((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysaddErrors 0cCsñtid||ƒti|||ƒ|\}}}|i t j o t |i ƒo"di t|ƒ|i gƒ}n|it j o t |iƒo4di t|ƒtdƒ|itdƒgƒ}n|||f}|ii||ƒdS(NsProxy addFailure %s %ss s>> begin captured stdout <> end captured stdout <<(slogsdebugstestserrsResults addFailuresselfsecsevstbstbinfosNoneslensjoinsstrscaptslnsresult(sselfstestserrsecsevstb((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys addFailure#s " 4cCs$ti||ƒ|ii|ƒdS(N(sResults addSuccesssselfstestsresult(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys addSuccess2scCs$ti||ƒ|ii|ƒdS(N(sResults startTestsselfstestsresult(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys startTest6scCs$ti||ƒ|ii|ƒdS(N(sResultsstopTestsselfstestsresult(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysstopTest:scCs|iiSdS(N(sselfsresults shouldStop(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys_get_shouldStop>scCs||i_dS(N(svalsselfsresults shouldStop(sselfsval((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys_set_shouldStopAs( s__name__s __module__s__doc__s__init__saddErrors addFailures addSuccesss startTestsstopTests_get_shouldStops_set_shouldStopspropertys shouldStop(((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys ResultProxys        sResultProxySuitecBs tZdZd„Zd„ZRS(s\Test suite that supports output capture, etc, by wrapping each test in a TestProxy. cCst|iƒSdS(N(sitersselfs_tests(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__iter__LscCs|iit|ƒƒdS(s%Add test, first wrapping in TestProxyN(sselfs_testssappends TestProxystest(sselfstest((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysaddTestPs(s__name__s __module__s__doc__s__iter__saddTest(((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysResultProxySuiteGs  s TestProxycBsStZdZeZd„Zd„Zd„Zd„Zd„Z d„Z d„Z RS(s;Test case that wraps the test result in a ResultProxy. cCs||_tid|ƒdS(Ns %r.__init__(s wrapped_testsselfslogsdebug(sselfs wrapped_test((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__init__Zs cOs$tid|ƒ|i||ŽdS(Ns %r.__call__(slogsdebugsselfsrunsargskw(sselfsargskw((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__call__^scCsd|iSdS(NsTestProxy for: %r(sselfs wrapped_test(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__repr__bscCst|iƒSdS(N(sstrsselfs wrapped_test(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys__str__escCs|iiƒSdS(N(sselfs wrapped_testsid(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysidhscCs3tid||i|ƒ|i|i|ƒƒdS(Ns/TestProxy run test %s in proxy %s for result %s(slogsdebugsselfs resultProxysresults wrapped_test(sselfsresult((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysrunks cCs|iiƒSdS(N(sselfs wrapped_testsshortDescription(sself((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pysshortDescriptionps( s__name__s __module__s__doc__s ResultProxys resultProxys__init__s__call__s__repr__s__str__sidsrunsshortDescription(((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys TestProxyUs       (s__doc__sloggingsunittests nose.resultsResultslns getLoggers__name__slogs ResultProxys TestSuitesResultProxySuitesTestCases TestProxy(sloggingslogslnsunittestsResultsResultProxySuites ResultProxys TestProxy((s.build/bdist.darwin-8.0.1-x86/egg/nose/proxy.pys?s  8PK¤žC8„¢!¹22nose/result.pyc;ò è’*Fc@s dZdkZdkZdkZdkZdkZdklZlZydk l Z Wn e j odk l Z nXdk l Z dklZlZdklZgZeidƒZdefd „ƒYZd eefd „ƒYZd „Zd „Zd„ZdS(sTest result handlers. Base class (Result) implements plugin handling, output capture, and assert introspection, and handles deprecated and skipped tests. TextTestResult is a drop-in replacement for unittest._TextTestResult that uses the capabilities in Result. N(s_TextTestResults TestSuite(sStringIO(sinspect_traceback(sDeprecatedTestsSkipTest(s call_pluginss nose.resultsResultcBs‰tZdZeZeZeZeZd„Z d„Z d„Z d„Z d„Z d„Zd„Zd„Zd „Zd „Zd „ZRS( s%Base class for results handlers. cCs$|iƒt|iid|ƒdS(Ns addDeprecated(sselfs resetBuffers call_pluginssconfspluginsstest(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addDeprecated"s cCsê|i|ƒo|i|ƒnÆ|i|ƒo|i|ƒn¥|iƒ|_|i i oE|i i o t ƒnt i|dƒ|i i o tƒq£n|iƒt|i id|||iƒ|i io t|_ndS(NisaddError(sselfs isDeprecatedserrs addDeprecatedstestsisSkipsaddSkips getBufferscaptsconfs debugErrorsscaptures end_capturespdbs post_mortems start_captures resetBuffers call_pluginsspluginss stopOnErrorsTrues shouldStop(sselfstestserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysaddError&s       cCs|iƒ|_|iioE|iio tƒnti|dƒ|iio t ƒqan|ii o=yt |dƒ|_ Wq´tij od|_ q´Xn d|_ |iƒt|iid|||i|i ƒ|iio t|_ndS(Nis ERR: unable to inspect tracebackss addFailure(sselfs getBufferscaptsconfs debugFailuresscaptures end_capturespdbs post_mortemserrs start_capturesdetailedErrorssinspect_tracebackstbinfostokenizes TokenErrors resetBuffers call_pluginsspluginsstests stopOnErrorsTrues shouldStop(sselfstestserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addFailure9s$        cCs$|iƒt|iid|ƒdS(NsaddSkip(sselfs resetBuffers call_pluginssconfspluginsstest(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysaddSkipNs cCs9|iƒ|_|iƒt|iid||iƒdS(Ns addSuccess(sselfs getBufferscapts resetBuffers call_pluginssconfspluginsstest(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addSuccessRs cCs:to+ytiiƒSWq2tj oq2XndSdS(Ns(sstdoutssyssgetvaluesAttributeError(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys getBufferWs  cCs5|dtjpt|dtƒotSntSdS(Ni(serrsDeprecatedTests isinstancesTruesFalse(sselfserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys isDeprecated`s%cCs5|dtjpt|dtƒotSntSdS(Ni(serrsSkipTests isinstancesTruesFalse(sselfserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysisSkipes%cCs/to$tiidƒtiidƒndS(Ni(sstdoutssysstruncatesseek(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys resetBufferjscCsG|iio|iƒt|_nt|_t|iid|ƒdS(Ns startTest( sselfsconfscaptures resetBuffersNonescaptstbinfos call_pluginsspluginsstest(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys startTestos     cCsG|iio|iƒt|_nt|_t|iid|ƒdS(NsstopTest( sselfsconfscaptures resetBuffersNonescaptstbinfos call_pluginsspluginsstest(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysstopTestvs     (s__name__s __module__s__doc__sNonescaptsconfstbinfosFalses shouldStops addDeprecatedsaddErrors addFailuresaddSkips addSuccesss getBuffers isDeprecatedsisSkips resetBuffers startTestsstopTest(((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysResults          sTextTestResultcBsztZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z d „Z d „Z d „ZRS( s¨Text test result that extends unittest's default test result with several optional features: - output capture Capture stdout while tests are running, and print captured output with errors and failures. - debug on error/fail Drop into pdb on error or failure, in the frame where the exception was raised. - deprecated or skipped tests raise DeprecatedTest or SkipTest to indicated that a test is deprecated or has been skipped. Deprecated or skipped tests will be printed with errors and failures, but don't cause the test run as a whole to be considered non-successful. cCsAg|_g|_||_|i|_ti||||ƒdS(N( sselfs deprecatedsskipsconfscaptures_TextTestResults__init__sstreams descriptionss verbosity(sselfsstreams descriptionss verbositysconf((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys__init__“s     cCs=ti||ƒ|ii|ddfƒ|iddƒdS(Nss DEPRECATEDsD(sResults addDeprecatedsselfstests deprecatedsappendswriteRes(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addDeprecatedšscCsuti|||ƒ|i|ƒ o|i|ƒ o<|ii||i ||ƒ|i fƒ|i ddƒndS(NsERRORsE( sResultsaddErrorsselfstestserrs isDeprecatedsisSkipserrorssappends_exc_info_to_stringscaptswriteRes(sselfstestserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysaddErrorŸs"(cCsVti|||ƒ|ii||i||ƒ|i|i fƒ|i ddƒdS(NsFAILsF( sResults addFailuresselfstestserrsfailuressappends_exc_info_to_stringstbinfoscaptswriteRes(sselfstestserr((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addFailure§s/cCs=ti||ƒ|ii|ddfƒ|iddƒdS(NssSKIPsS(sResultsaddSkipsselfstestsskipsappendswriteRes(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysaddSkip®scCs$ti||ƒ|iddƒdS(Nsoks.(sResults addSuccesssselfstestswriteRes(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys addSuccess³scCsjtidƒti|ƒ|id|iƒ|id|iƒtidƒt|i i d|i ƒdS(NsprintErrors calleds DEPRECATEDsSKIPPEDscalling plugin reportssreport( slogsdebugs_TextTestResults printErrorssselfsprintErrorLists deprecatedsskips call_pluginssconfspluginssstream(sself((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys printErrors·s    cCsÕxÎ|D]Æ\}}}|ii|iƒ|iid||i |ƒfƒ|ii|i ƒ|iid|ƒ|t j o t |ƒo@|iit dƒƒ|ii|ƒ|iit dƒƒqqWdS(Ns%s: %ss%ss>> begin captured stdout <> end captured stdout <<(serrorsstestserrscaptsselfsstreamswritelns separator1sflavorsgetDescriptions separator2sNoneslensln(sselfsflavorserrorsserrscaptstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysprintErrorList¿s#cCs9ti||ƒt|tƒ oti||ƒndS(N(sResults startTestsselfstests isinstances TestSuites_TextTestResult(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys startTestÊscCs9ti||ƒt|tƒ oti||ƒndS(N(sResultsstopTestsselfstests isinstances TestSuites_TextTestResult(sselfstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysstopTestÏscCs2|io|ii|ƒn|ii|ƒdS(N(sselfsshowAllsstreamswritelnslongswritesshort(sselfslongsshort((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pyswriteResÔs cCsAyti|||ƒSWn#tj oti||ƒSnXdS(N(s_TextTestResults_exc_info_to_stringsselfserrstests TypeError(sselfserrstest((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys_exc_info_to_stringÚs(s__name__s __module__s__doc__s__init__s addDeprecatedsaddErrors addFailuresaddSkips addSuccesss printErrorssprintErrorLists startTestsstopTestswriteRess_exc_info_to_string(((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pysTextTestResult~s           cCsHtidtiƒtitiƒtƒt_tidtiƒdS(sAStart capturing output to stdout. DOES NOT reset the buffer. sstart capture from %rssys.stdout is now %rN(slogsdebugssyssstdoutsappendsStringIO(((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys start_captureâs  cCs2to'tiƒt_tidtiƒndS(sAStop capturing output to stdout. DOES NOT reset the buffer.x s#capture ended, sys.stdout is now %rN(sstdoutspopssysslogsdebug(((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys end_captureêscCspt|ƒd}d|d}dd||d|f}dt|ƒ}|djo|d|}n|SdS(NiiFs%s %s %ss-i(slenslabels label_lenschunksoutspad(slabelschunkspadsouts label_len((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pyslnòs (s__doc__sinspectsloggingspdbssysstokenizesunittests_TextTestResults TestSuites cStringIOsStringIOs ImportErrorsnose.inspectorsinspect_tracebacksnose.excsDeprecatedTestsSkipTests nose.pluginss call_pluginssstdouts getLoggerslogsobjectsResultsTextTestResults start_captures end_capturesln(sstdouts TestSuites_TextTestResultsloggingslogsStringIOsSkipTestsinspect_tracebacksinspects call_pluginsssysslnsTextTestResultsDeprecatedTests start_capturestokenizes end_capturespdbsResult((s/build/bdist.darwin-8.0.1-x86/egg/nose/result.pys?s(       dd  PK••6-Lûûnose/commands.py""" nosetests setuptools command ---------------------------- You can run tests using the `nosetests` setuptools command:: python setup.py nosetests This command has a few benefits over the standard `test` command: all nose plugins are supported, and you can configure the test run with both command line arguments and settings in your setup.cfg file. To configure the `nosetests` command, add a [nosetests] section to your setup.cfg. The [nosetests] section can contain any command line arguments that nosetests supports. The differences between issuing an option on the command line and adding it to setup.cfg are: * In setup.cfg, the -- prefix must be excluded * In setup.cfg, command line flags that take no arguments must be given an argument flag (1, T or TRUE for active, 0, F or FALSE for inactive) Here's an example [nosetests] setup.cfg section:: [nosetests] verbosity=1 detailed-errors with-coverage=1 cover-package=nose debug=nose.loader pdb=1 pdb-failures=1 If you commonly run nosetests with a large number of options, using the nosetests setuptools command and configuring with setup.cfg can make running your tests much less tedious. """ import os from setuptools import Command from nose.core import get_parser, main parser = get_parser(env={}) option_blacklist = ['help', 'verbose'] def get_user_options(): """convert a optparse option list into a distutils option tuple list""" opt_list = [] for opt in parser.option_list: if opt._long_opts[0][2:] in option_blacklist: continue long_name = opt._long_opts[0][2:] if opt.action != 'store_true': long_name = long_name + "=" short_name = None if opt._short_opts: short_name = opt._short_opts[0][1:] opt_list.append((long_name, short_name, opt.help or "")) return opt_list class nosetests(Command): description = "Run unit tests using nosetests" user_options = get_user_options() def initialize_options(self): """create the member variables, but change hyphens to underscores""" self.option_to_cmds = {} for opt in parser.option_list: cmd_name = opt._long_opts[0][2:] option_name = cmd_name.replace('-', '_') self.option_to_cmds[option_name] = cmd_name setattr(self, option_name, None) self.attr = None def finalize_options(self): """nothing to do here""" pass def run(self): """ensure tests are capable of being run, then run nose.main with a reconstructed argument list""" self.run_command('egg_info') # Build extensions in-place self.reinitialize_command('build_ext', inplace=1) self.run_command('build_ext') if self.distribution.tests_require: self.distribution.fetch_build_eggs(self.distribution.tests_require) argv = [] for (option_name, cmd_name) in self.option_to_cmds.items(): if option_name in option_blacklist: continue value = getattr(self, option_name) if value is not None: if flag(value): if _bool(value): argv.append('--' + cmd_name) else: argv.append('--' + cmd_name) argv.append(value) main(argv=argv, env=os.environ) def flag(val): """Does the value look like an on/off flag?""" if type(val)==type(1): val = str(val) if len(val) > 5: return False return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF') def _bool(val): if type(val) != str: val = str(val) return val.upper() in ('1', 'T', 'TRUE', 'ON') PK••6¡ìÇ6$$nose/twistedtools.py""" Twisted integration ------------------- This module provides a very simple way to integrate your tests with the Twisted event loop. You must import this module *before* importing anything from Twisted itself! Example: from nose.twistedtools import reactor, deferred @deferred() def test_resolve(): return reactor.resolve("nose.python-hosting.com") Or, more realistically: @deferred(timeout=5.0) def test_resolve(): d = reactor.resolve("nose.python-hosting.com") def check_ip(ip): assert ip == "67.15.36.43" d.addCallback(check_ip) return d """ import sys from Queue import Queue, Empty from nose.tools import make_decorator, TimeExpired __all__ = [ 'threaded_reactor', 'reactor', 'deferred', 'TimeExpired', ] _twisted_thread = None def threaded_reactor(): """ Start the Twisted reactor in a separate thread, if not already done. Returns the reactor. The thread will automatically be destroyed when all the tests are done. """ global _twisted_thread from twisted.internet import reactor if not _twisted_thread: from twisted.python import threadable from threading import Thread _twisted_thread = Thread(target=lambda: reactor.run( \ installSignalHandlers=False)) _twisted_thread.setDaemon(True) _twisted_thread.start() return reactor # Export global reactor variable, as Twisted does reactor = threaded_reactor() def deferred(timeout=None): """ By wrapping a test function with this decorator, you can return a twisted Deferred and the test will wait for the deferred to be triggered. The whole test function will run inside the Twisted event loop. The optional timeout parameter specifies the maximum duration of the test. The difference with timed() is that timed() will still wait for the test to end, while deferred() will stop the test when its timeout has expired. The latter is more desireable when dealing with network tests, because the result may actually never arrive. If the callback is triggered, the test has passed. If the errback is triggered or the timeout expires, the test has failed. Example: @deferred(timeout=5.0) def test_resolve(): return reactor.resolve("nose.python-hosting.com") Attention! If you combine this decorator with other decorators (like "raises"), deferred() must be called *first*! In other words, this is good: @raises(DNSLookupError) @deferred() def test_error(): return reactor.resolve("xxxjhjhj.biz") and this is bad: @deferred() @raises(DNSLookupError) def test_error(): return reactor.resolve("xxxjhjhj.biz") """ reactor = threaded_reactor() # Check for common syntax mistake # (otherwise, tests can be silently ignored # if one writes "@deferred" instead of "@deferred()") try: timeout is None or timeout + 0 except TypeError: raise TypeError("'timeout' argument must be a number or None") def decorate(func): def wrapper(*args, **kargs): q = Queue() def callback(value): q.put(None) def errback(failure): # Retrieve and save full exception info try: failure.raiseException() except: q.put(sys.exc_info()) def g(): try: d = func(*args, **kargs) try: d.addCallbacks(callback, errback) # Check for a common mistake and display a nice error # message except AttributeError: raise TypeError("you must return a twisted Deferred " "from your test case!") # Catch exceptions raised in the test body (from the # Twisted thread) except: q.put(sys.exc_info()) reactor.callFromThread(g) try: error = q.get(timeout=timeout) except Empty: raise TimeExpired("timeout expired before end of test (%f s.)" % timeout) # Re-raise all exceptions if error is not None: exc_type, exc_value, tb = error raise exc_type, exc_value, tb wrapper = make_decorator(func)(wrapper) return wrapper return decorate PK••6×à¨é;;nose/selector.pyimport logging import os import sys import unittest from nose.config import Config from nose.plugins import call_plugins from nose.util import absfile, file_like, split_test_name, test_address log = logging.getLogger(__name__) class Selector(object): """Core test selector. Examines test candidates and determines whether, given the specified configuration, the test candidate should be selected as a test. """ def __init__(self, conf): self.conf = conf self.configure(conf) def anytest(self, func): """Check func against all tests. Funcs should return None if they don't apply, False if they apply but don't match, True if they apply and match. Example: a func that wants tests based on what file they are in should return None for a test address that doesn't contain a file part. It should return true if a test address contains a file part that matches the comparison file, and False if a test address contains a file part that does not match the comparison file. """ if not self.tests: return True log.debug('tests to check: %s', self.tests) matches = [ func(*test_tuple) for test_tuple in map(split_test_name, self.tests) ] log.debug('anytest matches: %s', matches) res = filter(lambda x: x is not False, matches) log.debug('anytest result: %s', res) return res def classInTests(self, cls): def match(filename, modname, funcname, cls=cls): if funcname is None: return None try: clsn, dummy = funcname.split('.') except (ValueError, AttributeError): clsn, dummy = funcname, None return cls.__name__ == clsn return self.anytest(match) def configure(self, conf): self.exclude = conf.exclude self.ignoreFiles = conf.ignoreFiles self.include = conf.include self.plugins = conf.plugins self.match = conf.testMatch self.tests = conf.tests def fileInTests(self, file): orig = file if not os.path.isabs(file): file = absfile(file, self.conf.working_dir) log.debug("abs file %s is %s", orig, file) if file is None: log.debug("File %s does not exist" % orig) if self.tests: return False return True log.debug('Check file in tests') def match(filename, modname, funcname, file=file): return self.filematch(filename, modname, funcname, file) return self.anytest(match) def filematch(self, filename, modname, funcname, file): log.debug("Filematch (%s, %s, %s, %s)", filename, modname, funcname, file) if filename is None: if modname is None: return None # be liberal... could this file possibly be this module? # return None if the module name, converted to a file # path, matches any part of the full filename mpath = os.path.sep.join(modname.split('.')) log.debug("Is module path %s in file %s?", mpath, file) if mpath in file: return None else: return False if not os.path.isabs(filename): filename = absfile(filename, self.conf.working_dir) log.debug("Abs match file: %s", filename) # A file is a match if it is an exact match, or if # the filename to match against is a directory (or package init file) # and the file appears to be under that directory. Files that # don't exist can't match. if filename is None: return False if filename.endswith('__init__.py'): dirname = os.path.dirname(filename) elif os.path.isdir(filename): dirname = filename else: dirname = None log.debug("Files are same: %s", filename == file) log.debug("Dirname: %s", dirname) if dirname is not None: log.debug("File startswith dirname: %s", file.startswith(dirname)) try: log.debug("File has sep at end of dirname: %s == %s", file[len(dirname)], os.path.sep) except IndexError: log.debug("File is not within dir") return filename == file \ or (dirname is not None and file.startswith(dirname) and file[len(dirname)] == os.path.sep) def funcInTests(self, func): def match(filename, modname, funcname, func=func): if funcname is None: return None return func.__name__ == funcname return self.anytest(match) def matches(self, name): """Does the name match my requirements? To match, a name must match conf.testMatch OR conf.include and it must not match conf.exclude """ return ((self.match.search(name) or (self.include and filter(None, [inc.search(name) for inc in self.include]))) and ((not self.exclude) or not filter(None, [exc.search(name) for exc in self.exclude]) )) def methodInTests(self, method): """Determine if a method is listed in the requested tests. To be consideed a match, the method's class must be in the class part of the test address, and the function part of the test address must match the method name or be None. """ def match(filename, modname, funcname, method=method): if funcname is None: return None mcls = method.im_class.__name__ mname = method.__name__ try: cls, func = funcname.split('.') except (ValueError, AttributeError): cls, func = funcname, None return mcls == cls and (mname == func or func is None) return self.anytest(match) def moduleInTests(self, module, either=False): def match(filename, modname, funcname, module=module, either=either): log.debug("Checking module %s in test %s:%s (either: %s)", module.__name__, modname, funcname, either) if modname is None: if filename is None: return None mod_file = module.__file__ if mod_file.endswith('.pyc') or mod_file.endswith('.pyo'): mod_file = mod_file[:-3] + 'py' log.debug("Checking module file %s against filename %s", mod_file, filename) return self.filematch(filename, modname, funcname, file=mod_file) mname = module.__name__ result = (subpackage_of(mname, modname) or (either and subpackage_of(modname, mname))) log.debug("Module %s match %s (either: %s) result %s", module.__name__, modname, either, result) return result res = self.anytest(match) log.debug("Module %s in tests result: %s", module,res) return res def wantClass(self, cls): """Is the class a wanted test class? A class must be a unittest.TestCase subclass, or match test name requirements. If self.tests is defined, the class must match something in self.tests: """ log.debug("Load tests from class %s?", cls) wanted = (not cls.__name__.startswith('_') and (issubclass(cls, unittest.TestCase) or self.match.search(cls.__name__))) log.debug("%s is wanted? %s", cls, wanted) plug_wants = call_plugins(self.plugins, 'wantClass', cls) if plug_wants is not None: log.debug("Plugin setting selection of %s to %s", cls, plug_wants) wanted = plug_wants return wanted and self.classInTests(cls) def wantDirectory(self, dirname): """Is the directory a wanted test directory? All package directories match, so long as they do not match exclude. All other directories must match test requirements. """ init = os.path.join(dirname, '__init__.py') tail = os.path.basename(dirname) if os.path.exists(init): wanted = (not self.exclude or not filter(None, [exc.search(tail) for exc in self.exclude] )) else: wanted = (self.matches(tail) or (self.conf.srcDirs and tail in self.conf.srcDirs)) plug_wants = call_plugins(self.plugins, 'wantDirectory', dirname) if plug_wants is not None: wanted = plug_wants # FIXME in tests? return wanted def wantFile(self, file, package=None): """Is the file a wanted test file? If self.tests is defined, the file must match the file part of a test address in self.tests. The default implementation ignores the package setting, but it is passed in case plugins need to distinguish package from non-package files. """ # never, ever load files that match anything in ignore # (.* _* and *setup*.py by default) base = os.path.basename(file) ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles if ignore_this.search(base) ] if ignore_matches: log.debug('%s matches ignoreFiles pattern; skipped', base) return False if not self.conf.includeExe and os.access(file, os.X_OK): log.info('%s is executable; skipped', file) return False in_tests = self.fileInTests(file) if not in_tests: return False dummy, ext = os.path.splitext(base) pysrc = ext == '.py' wanted = pysrc and self.matches(base) plug_wants = call_plugins(self.plugins, 'wantFile', file, package) if plug_wants is not None: wanted = plug_wants return wanted or (pysrc and self.tests and in_tests) def wantFunction(self, function): """Is the function a test function? If conf.function_only is defined, the function name must match function_only. Otherwise, the function name must match test requirements. """ try: if hasattr(function, 'compat_func_name'): funcname = function.compat_func_name else: funcname = function.__name__ except AttributeError: # not a function return False in_tests = self.funcInTests(function) if not in_tests: return False wanted = not funcname.startswith('_') and self.matches(funcname) plug_wants = call_plugins(self.plugins, 'wantFunction', function) if plug_wants is not None: wanted = plug_wants return wanted def wantMethod(self, method): """Is the method a test method? If conf.function_only is defined, the qualified method name (class.method) must match function_only. Otherwise, the base method name must match test requirements. """ try: method_name = method.__name__ except AttributeError: # not a method return False if method_name.startswith('_'): # never collect 'private' methods return False in_tests = self.methodInTests(method) if not in_tests: return False wanted = self.matches(method_name) plug_wants = call_plugins(self.plugins, 'wantMethod', method) if plug_wants is not None: wanted = plug_wants return wanted def wantModule(self, module): """Is the module a test module? The tail of the module name must match test requirements. If a module is wanted, it means that the module should be loaded, and its setup/teardown fixtures run -- if any. It does not mean that tests will be collected from the module; tests are only collected from modules where wantModuleTests() is true. """ in_tests = self.moduleInTests(module, either=True) if not in_tests: return False wanted = self.matches(module.__name__.split('.')[-1]) plug_wants = call_plugins(self.plugins, 'wantModule', module) if plug_wants is not None: wanted = plug_wants return wanted or (self.tests and in_tests) def wantModuleTests(self, module): """Collect tests from this module? The tail of the module name must match test requirements. If the modules tests are wanted, they will be collected by the standard test collector. If your plugin wants to collect tests from a module in some other way, it MUST NOT return true for wantModuleTests; that would not allow the plugin to collect tests, but instead cause the standard collector to collect tests. """ in_tests = self.moduleInTests(module) if not in_tests: return False # unittest compat: always load from __main__ wanted = (self.matches(module.__name__.split('.')[-1]) or module.__name__ == '__main__') plug_wants = call_plugins(self.plugins, 'wantModuleTests', module) if plug_wants is not None: wanted = plug_wants return wanted or (self.tests and in_tests) defaultSelector = Selector # Helpers def subpackage_of(modname, package): """Is module modname a subpackage of package?""" # quick negative case log.debug('subpackage_of(%s,%s)', modname, package) if not modname.startswith(package): log.debug('not %s startswith %s' , modname, package) return False if len(package) > len(modname): log.debug('package name longer than mod name') return False mod_parts = modname.split('.') pkg_parts = package.split('.') try: for p in pkg_parts: pp = mod_parts.pop(0) log.debug('check part %s vs part %s', p, pp) if p != pp: return False except IndexError: log.debug('package %s more parts than modname %s', package, modname) return False return True PK••6Bôa>””nose/plugins/__init__.py"""Writing Plugins --------------- nose supports setuptools_ entry point plugins for test collection, selection, observation and reporting. There are two basic rules for plugins: * Plugin classes should subclass `nose.plugins.Plugin`_. * Plugins may implement any of the methods described in the class PluginInterface in nose.plugins.base. Please note that this class is for documentary purposes only; plugins may not subclass PluginInterface. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _nose.plugins.Plugin: http://python-nose.googlecode.com/svn/trunk/nose/plugins/base.py Registering =========== For nose to find a plugin, it must be part of a package that uses setuptools, and the plugin must be included in the entry points defined in the setup.py for the package:: setup(name='Some plugin', ... entry_points = { 'nose.plugins': [ 'someplugin = someplugin:SomePlugin' ] }, ... ) Once the package is installed with install or develop, nose will be able to load the plugin. Defining options ================ All plugins must implement the methods ``add_options(self, parser, env)`` and ``configure(self, options, conf)``. Subclasses of nose.plugins.Plugin that want the standard options should call the superclass methods. nose uses optparse.OptionParser from the standard library to parse arguments. A plugin's ``add_options()`` method receives a parser instance. It's good form for a plugin to use that instance only to add additional arguments that take only long arguments (--like-this). Most of nose's built-in arguments get their default value from an environment variable. This is a good practice because it allows options to be utilized when run through some other means than the nosetests script. A plugin's ``configure()`` method receives the parsed ``OptionParser`` options object, as well as the current config object. Plugins should configure their behavior based on the user-selected settings, and may raise exceptions if the configured behavior is nonsensical. Logging ======= nose uses the logging classes from the standard library. To enable users to view debug messages easily, plugins should use ``logging.getLogger()`` to acquire a logger in the ``nose.plugins`` namespace. Recipes ======= * Writing a plugin that monitors or controls test result output Implement any or all of ``addError``, ``addFailure``, etc., to monitor test results. If you also want to monitor output, implement ``setOutputStream`` and keep a reference to the output stream. If you want to prevent the builtin ``TextTestResult`` output, implement ``setOutputSteam`` and *return a dummy stream*. The default output will go to the dummy stream, while you send your desired output to the real stream. Example: `examples/html_plugin/htmlplug.py`_ * Writing a plugin that loads tests from files other than python modules Implement ``wantFile`` and ``loadTestsFromPath``. In ``wantFile``, return True for files that you want to examine for tests. In ``loadTestsFromPath``, for those files, return a TestSuite or other iterable containing TestCases. ``loadTestsFromPath`` may also be a generator. Example: `nose.plugins.doctests`_ * Writing a plugin that prints a report Implement begin if you need to perform setup before testing begins. Implement ``report`` and output your report to the provided stream. Examples: `nose.plugins.cover`_, `nose.plugins.profile`_, `nose.plugins.missed`_ * Writing a plugin that selects or rejects tests Implement any or all ``want*`` methods. Return False to reject the test candidate, True to accept it -- which means that the test candidate will pass through the rest of the system, so you must be prepared to load tests from it if tests can't be loaded by the core loader or another plugin -- and None if you don't care. Examples: `nose.plugins.attrib`_, `nose.plugins.doctests`_ Examples ======== See `nose.plugins.attrib`_, `nose.plugins.cover`_, `nose.plugins.doctests`_ and `nose.plugins.profile`_ for examples. Further examples may be found the examples_ directory in the nose source distribution. .. _examples/html_plugin/htmlplug.py: http://python-nose.googlecode.com/svn/trunk/examples/html_plugin/htmlplug.py .. _examples: http://python-nose.googlecode.com/svn/trunk/examples .. _nose.plugins.attrib: http://python-nose.googlecode.com/svn/trunk/nose/plugins/attrib.py .. _nose.plugins.cover: http://python-nose.googlecode.com/svn/trunk/nose/plugins/cover.py .. _nose.plugins.doctests: http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py .. _nose.plugins.missed: http://python-nose.googlecode.com/svn/trunk/nose/plugins/missed.py .. _nose.plugins.profile: http://python-nose.googlecode.com/svn/trunk/nose/plugins/profile.py """ from __future__ import generators import logging import pkg_resources from inspect import isclass from warnings import warn from nose.plugins.base import * builtin_plugins = ('attrib', 'cover', 'doctests', 'isolate', 'missed', 'prof') log = logging.getLogger(__name__) def call_plugins(plugins, method, *arg, **kw): """Call all method on plugins in list, that define it, with provided arguments. The first response that is not None is returned. """ for plug in plugins: func = getattr(plug, method, None) if func is None: continue log.debug("call plugin %s: %s", plug.name, method) result = func(*arg, **kw) if result is not None: return result return None def load_plugins(builtin=True, others=True): """Load plugins, either builtin, others, or both. """ loaded = [] if builtin: for name in builtin_plugins: try: parent = __import__(__name__, globals(), locals(), [name]) pmod = getattr(parent, name) for entry in dir(pmod): obj = getattr(pmod, entry) if (isclass(obj) and issubclass(obj, Plugin) and obj is not Plugin and not obj in loaded): log.debug("load builtin plugin %s (%s)" % (name, obj)) yield obj loaded.append(obj) except KeyboardInterrupt: raise except Exception, e: warn("Unable to load builtin plugin %s: %s" % (name, e), RuntimeWarning) if not others: return for ep in pkg_resources.iter_entry_points('nose.plugins'): log.debug("load plugin %s" % ep) try: plug = ep.load() except KeyboardInterrupt: raise except Exception, e: # never want a plugin load to kill the test run # but we can't log here because the logger is not yet # configured warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning) continue if plug.__module__.startswith('nose.plugins'): # already loaded as a builtin pass elif plug not in loaded: yield plug loaded.append(plug) PK£žC8j²zAAnose/plugins/doctests.pyc;ò è’*Fc@s¹dZdklZdkZdkZdkZdklZdkl Z l Z ei e ƒZ y,eiZdefd„ƒYZee_Wnej onXdefd„ƒYZdS( s^Use the Doctest plugin with --with-doctest or the NOSE_WITH_DOCTEST environment variable to enable collection and execution of doctests. doctest_ tests are usually included in the tested package, not grouped into packages or modules of their own. For this reason, nose will try to detect and run doctest tests only in the non-test packages it discovers in the working directory. Doctests may also be placed into files other than python modules, in which case they can be collected and executed by using the --doctest-extension switch or NOSE_DOCTEST_EXTENSION environment variable to indicate which file extension(s) to load. doctest tests are run like any other test, with the exception that output capture does not work, because doctest does its own output capture in the course of running a test. .. _doctest: http://docs.python.org/lib/module-doctest.html (s generatorsN(sPlugin(sanypstolistsNoseOutputRedirectingPdbcBs#tZd„Zd„Zd„ZRS(NcCst|_ti||ƒdS(N(sFalsesselfs(_NoseOutputRedirectingPdb__debugger_useds_orps__init__sout(sselfsout((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys__init__'s cCst|_ti|ƒdS(N(sTruesselfs(_NoseOutputRedirectingPdb__debugger_useds_orps set_trace(sself((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys set_trace+s cCs|ioti|ƒndS(N(sselfs(_NoseOutputRedirectingPdb__debugger_useds_orps set_continue(sself((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys set_continue/s (s__name__s __module__s__init__s set_traces set_continue(((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pysNoseOutputRedirectingPdb&s  sDoctestcBsbtZdZeZeid„Zd„Zd„Z d„Z eed„Z d„Z ed„Z RS(sO Activate doctest plugin to find and run doctests in non-test modules. c Cs»ti|||ƒ|idddddd|idƒdd ƒy`ti|id dd dd dd ƒ|idƒ}|t j o|i d t |ƒƒnWnt j onXdS(Ns--doctest-testssactions store_truesdests doctest_testssdefaultsNOSE_DOCTEST_TESTSshelps;Also look for doctests in test modules [NOSE_DOCTEST_TESTS]s--doctest-extensionsappendsdoctestExtensionsLAlso look for doctests in files with this extension [NOSE_DOCTEST_EXTENSION]sNOSE_DOCTEST_EXTENSION(sPlugins add_optionssselfsparsersenvs add_optionsgetsdoctests DocFileSuites env_settingsNones set_defaultsstolistsAttributeError(sselfsparsersenvs env_setting((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys add_options?s   cCsXti|||ƒ|i|_yt|iƒ|_Wnt j ot |_nXdS(N( sPlugins configuresselfsoptionssconfigs doctest_testsstolistsdoctestExtensions extensionsAttributeErrorsNone(sselfsoptionssconfig((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys configureVs  ccs—|i|iƒ otid|ƒdSn|i|ƒ}| odSntid|ƒt|dƒo |}n |i }x|D] }|Vq…WdS(NsDoctest doesn't want module %ssDoctests found in %ss__iter__( sselfsmatchessmodules__name__slogsdebugs _loadDoctestssdoctestsshasattrs doctest_suites_testsstest(sselfsmodulesdoctestss doctest_suitestest((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pysloadTestsFromModule_s  cCsEyti|ƒSWn-tj o!}d|jodSn‚nXdS(Ns has no tests(sdoctests DocTestSuitesmodules ValueErrorse(sselfsmodulese((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys _loadDoctestsos  cCse|iot|i|iƒo=yti|dtƒSWqatj ot dƒ‚qaXngSdS(Nsmodule_relativesYDoctests in files other than .py (python source) not supported in this version of doctest( sselfs extensionsanypsfilenamesendswithsdoctests DocFileSuitesFalsesAttributeErrors Exception(sselfsfilenamespackages importPath((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pysloadTestsFromPathxs  cCsÓ|djotSn|ipa|iii|ƒ pJ|iio=tt gi }|iiD]}||i|ƒƒq]~ƒoL|ii p>tt gi }|ii D]}||i|ƒƒq«~ƒ SdS(s8Doctest wants only non-test modules in general. s __init__.pyN(snamesFalsesselfs doctest_testssconfs testMatchssearchsincludesfiltersNonesappends_[1]sincsexcludesexc(sselfsnames_[1]sexcsinc((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pysmatches„s  4NcCs—|idƒotSn|iobt|i|iƒoL|ii p>tt gi }|iiD]}||i |ƒƒq`~ƒ otSnt SdS(Ns.py(sfilesendswithsTruesselfs extensionsanypsconfsexcludesfiltersNonesappends_[1]sexcssearch(sselfsfilespackages_[1]sexc((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pyswantFile”s 4;(s__name__s __module__s__doc__sNones extensionsossenvirons add_optionss configuresloadTestsFromModules _loadDoctestssloadTestsFromPathsmatchesswantFile(((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pysDoctest9s    (s__doc__s __future__s generatorssdoctestsloggingsossnose.plugins.basesPlugins nose.utilsanypstolists getLoggers__name__slogs_OutputRedirectingPdbs_orpsNoseOutputRedirectingPdbsAttributeErrorsDoctest( sNoseOutputRedirectingPdbstolistsloggingslogsPluginsanyps generatorssdoctests_orpsossDoctest((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/doctests.pys?s        PK£žC8› sÂÝGÝGnose/plugins/base.pyc;ò è’*Fc@sXdkZdkZdkZdklZdefd„ƒYZdefd„ƒYZdS(N(stolistsPlugincBsStZdZeZeZeZd„Ze i d„Z d„Z d„Z d„ZRS(s£Base class for nose plugins. It's not *necessary* to subclass this class to create a plugin; however, all plugins must implement `add_options(self, parser, env)` and `configure(self, options, conf)`, and must have the attributes `enabled` and `name`. Plugins should not be enabled by default. Subclassing Plugin will give your plugin some friendly default behavior: * A --with-$name option will be added to the command line interface to enable the plugin. The plugin class's docstring will be used as the help for this option. * The plugin will not be enabled unless this option is selected by the user. cCsQ|itjo|iiiƒ|_n|itjod|i|_ndS(Nsenable_plugin_%s(sselfsnamesNones __class__s__name__slowers enableOpt(sself((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys__init__sc Csxd|iiƒ}|iddƒ|id|iddd|id|i |ƒd d |i i |i ƒ|fƒd S( s“Add command-line options for this plugin. The base plugin class adds --with-$name by default, used to enable the plugin. s NOSE_WITH_%ss-s_s --with-%ssactions store_truesdestsdefaultshelpsEnable plugin %s: %s [%s]N( sselfsnamesuppersenv_optsreplacesparsers add_options enableOptsenvsgets __class__s__name__shelp(sselfsparsersenvsenv_opt((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys add_options!s cCs9||_t||iƒot||iƒ|_ndS(sÄConfigure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable option for the plugin (self.enableOpt) is true. N(sconfsselfshasattrsoptionss enableOptsgetattrsenabled(sselfsoptionssconf((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys configure0s cCs,|iioti|iiƒSndSdS(s‰Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. s(no help available)N(sselfs __class__s__doc__stextwrapsdedent(sself((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pyshelp:s cCs(dkl}|dtƒt|ƒSdS(N(swarns9Plugin.tolist is deprecated. Use nose.util.tolist instead(swarningsswarnsDeprecationWarningstolistsval(sselfsvalswarn((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pystolistDs (s__name__s __module__s__doc__sFalsesenabledsNones enableOptsnames__init__sossenvirons add_optionss configureshelpstolist(((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysPlugins   sIPluginInterfacecBsõtZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z d „Z e e d „Z e e d „Zd „Zd „Zd„Zd„Zd„Zd„Zd„Zd„Ze d„Zd„Zd„Zd„Zd„ZRS(sp Nose plugin API --------------- While it is recommended that plugins subclass nose.plugins.Plugin, the only requirements for a plugin are that it implement the methods `add_options(self, parser, env)` and `configure(self, options, conf)`, and have the attributes `enabled` and `name`. Plugins may implement any or all of the methods documented below. Please note that they *must not* subclass PluginInterface; PluginInterface is a only description of the plugin API. When plugins are called, the first plugin that implements a method and returns a non-None value wins, and plugin processing ends. The exceptions to this are `loadTestsFromModule`, `loadTestsFromName`, and `loadTestsFromPath`, which allow multiple plugins to load and return tests. In general, plugin methods correspond directly to methods of nose.selector.Selector, nose.loader.TestLoader and nose.result.TextTestResult are called by those methods when they are called. In some cases, the plugin hook doesn't neatly match the method in which it is called; for those, the documentation for the hook will tell you where in the test process it is called. Plugin hooks fall into two broad categories: selecting and loading tests, and watching and reporting on test results. Selecting and loading tests =========================== To alter test selection behavior, implement any necessary `want*` methods as outlined below. Keep in mind, though, that when your plugin returns True from a `want*` method, you will send the requested object through the normal test collection process. If the object represents something from which normal tests can't be collected, you must also implement a loader method to load the tests. Examples: * The builtin doctests plugin, for python 2.4 only, implements `wantFile` to enable loading of doctests from files that are not python modules. It also implements `loadTestsFromModule` to load doctests from python modules, and `loadTestsFromPath` to load tests from the non-module files selected by `wantFile`. * The builtin attrib plugin implements `wantFunction` and `wantMethod` so that it can reject tests that don't match the specified attributes. Watching or reporting on tests ============================== To record information about tests or other modules imported during the testing process, output additional reports, or entirely change test report output, implement any of the methods outlined below that correspond to TextTestResult methods. Examples: * The builtin cover plugin implements `begin` and `report` to capture and report code coverage metrics for all or selected modules loaded during testing. * The builtin profile plugin implements `begin`, `prepareTest` and `report` to record and output profiling information. In this case, the plugin's `prepareTest` method constructs a function that runs the test through the hotshot profiler's runcall() method. cOstdƒ‚dS(Ns0IPluginInterface class is for documentation only(s TypeError(sclssargskw((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys__new__’scCsdS(sÜCalled when a deprecated test is seen. DO NOT return a value unless you want to stop other plugins from seeing the deprecated test. Parameters: * test: the test case N((sselfstest((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys addDeprecated•scCsdS(sWCalled when a test raises an uncaught exception. DO NOT return a value unless you want to stop other plugins from seeing that the test has raised an error. Parameters: * test: the test case * err: sys.exc_info() tuple * capt: Captured output, if any N((sselfstestserrscapt((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysaddError s cCsdS(srCalled when a test fails. DO NOT return a value unless you want to stop other plugins from seeing that the test has failed. Parameters: * test: the test case * err: sys.exc_info() tuple * capt: Captured output, if any * tb_info: Introspected traceback info, if any N((sselfstestserrscaptstb_info((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys addFailure¯s cCsdS(sÈCalled when a test is skipped. DO NOT return a value unless you want to stop other plugins from seeing the skipped test. Parameters: * test: the test case N((sselfstest((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysaddSkip¿scCsdS(søCalled when a test passes. DO NOT return a value unless you want to stop other plugins from seeing the passing test. Parameters: * test: the test case * capt: Captured output, if any N((sselfstestscapt((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys addSuccessÉs cCsdS(szCalled before any tests are collected or run. Use this to perform any setup needed before testing begins. N((sself((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysbeginÕscCsdS(sýCalled after all report output, including output from all plugins, has been sent to the stream. Use this to print final test results. Return None to allow other plugins to continue printing, any other value to stop them. N((sselfsresult((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysfinalizeÛscCsdS(s"Return iterable of tests in a module. May be a generator. Each item returned must be a runnable unittest.TestCase subclass. Return None if your plugin cannot collect any tests from module. Parameters: * module: The module object N((sselfsmodule((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysloadTestsFromModuleãs cCsdS(séReturn tests in this file or module. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * name: The test name. May be a file or module name plus a test callable. Use split_test_name to split into parts. * module: Module in which the file is found * importPath: Path from which file (must be a python module) was found N((sselfsnamesmodules importPath((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysloadTestsFromNameïs cCsdS(s¢Return tests in this file or directory. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * path: The full path to the file or directory. * module: Module in which the file/dir is found * importPath: Path from which file (must be a python module) was found N((sselfspathsmodules importPath((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysloadTestsFromPathÿs cCsdS(säReturn tests in this test case class. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * cls: The test case class N((sselfscls((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysloadTestsFromTestCasescCsdS(sCalled before the test is run by the test runner. Please note the article *the* in the previous sentence: prepareTest is called *only once*, and is passed the test case or test suite that the test runner will execute. It is *not* called for each individual test case. If you return a non-None value, that return value will be run as the test. Use this hook to wrap or decorate the test with another function. Parameters: * test: the test case N((sselfstest((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys prepareTests cCsdS(s&Called after all error output has been printed. Print your plugin's report to the provided stream. Return None to allow other plugins to print reports, any other value to stop them. Parameters: * stream: stream object; send your output here N((sselfsstream((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysreport(scCsdS(sNCalled before test output begins. To direct test output to a new stream, return a stream object, which must implement a `write(msg)` method. If you only want to note the stream, not capture or redirect it, then return None. Parameters: * stream: the original output stream N((sselfsstream((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pyssetOutputStream3s cCsdS(sÇCalled before each test is run. DO NOT return a value unless you want to stop other plugins from seeing the test start. Parameters: * test: the test case N((sselfstest((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys startTest>scCsdS(sÑCalled after each test is run. DO NOT return a value unless you want to stop other plugins from seeing that the test has stopped. Parameters: * test: the test case N((sselfstest((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysstopTestHscCsdS(sÓReturn true if you want the main test selector to collect tests from this class, false if you don't, and None if you don't care. Parameters: * cls: The class N((sselfscls((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys wantClassRscCsdS(sÔReturn true if you want test collection to descend into this directory, false if you do not, and None if you don't care. Parameters: * dirname: Full path to directory N((sselfsdirname((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys wantDirectory]scCsdS(sReturn true if you want to collect tests from this file, false if you do not and None if you don't care. Parameters: * file: Full path to file * package: Package in which file is found, if any N((sselfsfilespackage((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pyswantFilegs cCsdS(sÏReturn true to collect this function as a test, false to prevent it from being collected, and None if you don't care. Parameters: * function: The function object N((sselfsfunction((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys wantFunctionsscCsdS(sÉReturn true to collect this method as a test, false to prevent it from being collected, and None if you don't care. Parameters: * method: The method object N((sselfsmethod((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys wantMethod}scCsdS(süReturn true if you want to collection to descend into this module, false to prevent the collector from descending into the module, and None if you don't care. Parameters: * module: The module object N((sselfsmodule((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys wantModule‡scCsdS(sEReturn true if you want the standard test loader to load tests from this module, false if you want to prevent it from doing so, and None if you don't care. DO NOT return true if your plugin will be loading the tests itself! Parameters: * module: The module object N((sselfsmodule((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pyswantModuleTests’s (s__name__s __module__s__doc__s__new__s addDeprecatedsaddErrors addFailuresaddSkips addSuccesssbeginsfinalizesloadTestsFromModulesNonesloadTestsFromNamesloadTestsFromPathsloadTestsFromTestCases prepareTestsreportssetOutputStreams startTestsstopTests wantClasss wantDirectoryswantFiles wantFunctions wantMethods wantModuleswantModuleTests(((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pysIPluginInterfaceJs2 G        (sossrestextwraps nose.utilstolistsobjectsPluginsIPluginInterface(stolistsPluginstextwrapsIPluginInterfacesresos((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/base.pys?s    DPK••6Ÿi.´¤¤nose/plugins/doctests.py"""Use the Doctest plugin with --with-doctest or the NOSE_WITH_DOCTEST environment variable to enable collection and execution of doctests. doctest_ tests are usually included in the tested package, not grouped into packages or modules of their own. For this reason, nose will try to detect and run doctest tests only in the non-test packages it discovers in the working directory. Doctests may also be placed into files other than python modules, in which case they can be collected and executed by using the --doctest-extension switch or NOSE_DOCTEST_EXTENSION environment variable to indicate which file extension(s) to load. doctest tests are run like any other test, with the exception that output capture does not work, because doctest does its own output capture in the course of running a test. .. _doctest: http://docs.python.org/lib/module-doctest.html """ from __future__ import generators import doctest import logging import os from nose.plugins.base import Plugin from nose.util import anyp, tolist log = logging.getLogger(__name__) # # Doctest and coverage don't get along, so we need to create # a monkeypatch that will replace the part of doctest that # interferes with coverage reports. # # The monkeypatch is based on this zope patch: # http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679&r1=28703&r2=28705 # try: _orp = doctest._OutputRedirectingPdb class NoseOutputRedirectingPdb(_orp): def __init__(self, out): self.__debugger_used = False _orp.__init__(self, out) def set_trace(self): self.__debugger_used = True _orp.set_trace(self) def set_continue(self): # Calling set_continue unconditionally would break unit test # coverage reporting, as Bdb.set_continue calls sys.settrace(None). if self.__debugger_used: _orp.set_continue(self) doctest._OutputRedirectingPdb = NoseOutputRedirectingPdb except AttributeError: # Python 2.3: no support pass class Doctest(Plugin): """ Activate doctest plugin to find and run doctests in non-test modules. """ extension = None def add_options(self, parser, env=os.environ): Plugin.add_options(self, parser, env) parser.add_option('--doctest-tests', action='store_true', dest='doctest_tests', default=env.get('NOSE_DOCTEST_TESTS'), help="Also look for doctests in test modules " "[NOSE_DOCTEST_TESTS]") try: # 2.4 or better supports loading tests from non-modules doctest.DocFileSuite parser.add_option('--doctest-extension', action="append", dest="doctestExtension", help="Also look for doctests in files with " "this extension [NOSE_DOCTEST_EXTENSION]") # Set the default as a list, if given in env; otherwise # an additional value set on the command line will cause # an error. env_setting = env.get('NOSE_DOCTEST_EXTENSION') if env_setting is not None: parser.set_defaults(doctestExtension=tolist(env_setting)) except AttributeError: pass def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = options.doctest_tests try: self.extension = tolist(options.doctestExtension) except AttributeError: # 2.3, no other-file option self.extension = None def loadTestsFromModule(self, module): if not self.matches(module.__name__): log.debug("Doctest doesn't want module %s", module) return doctests = self._loadDoctests(module) if not doctests: return # < 2.4 doctest (and unittest) suites don't have iterators log.debug("Doctests found in %s", module) if hasattr(doctests, '__iter__'): doctest_suite = doctests else: doctest_suite = doctests._tests for test in doctest_suite: yield test def _loadDoctests(self, module): try: return doctest.DocTestSuite(module) except ValueError, e: # empty = ValueError if 'has no tests' in e: return raise def loadTestsFromPath(self, filename, package=None, importPath=None): if self.extension and anyp(filename.endswith, self.extension): try: return doctest.DocFileSuite(filename, module_relative=False) except AttributeError: raise Exception("Doctests in files other than .py " "(python source) not supported in this " "version of doctest") else: # Don't return None, users may iterate over result return [] def matches(self, name): """Doctest wants only non-test modules in general. """ if name == '__init__.py': return False # FIXME don't think we need include/exclude checks here? return ((self.doctest_tests or not self.conf.testMatch.search(name) or (self.conf.include and filter(None, [inc.search(name) for inc in self.conf.include]))) and (not self.conf.exclude or not filter(None, [exc.search(name) for exc in self.conf.exclude]))) def wantFile(self, file, package=None): # always want .py files if file.endswith('.py'): return True # also want files that match my extension if (self.extension and anyp(file.endswith, self.extension) and (not self.conf.exclude or not filter(None, [exc.search(file) for exc in self.conf.exclude]))): return True return None PK••6,ÒÄŽŽnose/plugins/missed.pyfrom nose.plugins.base import Plugin from nose.util import split_test_name, test_address class MissedTests(Plugin): """ Enable to get a warning when tests specified on the command line are not found during the test run. """ name = 'missed-tests' def begin(self): if not self.conf.tests: self.missed = None else: self.missed = self.conf.tests[:] def finalize(self, result): if self.missed: for missed in self.missed: result.stream.writeln("WARNING: missed test '%s'" % missed) def match(self, test, test_name): adr_file, adr_mod, adr_tst = test_address(test) chk_file, chk_mod, chk_tst = split_test_name(test_name) if chk_file is not None and not adr_file.startswith(chk_file): return False if chk_mod is not None and not adr_mod.startswith(chk_mod): return False if chk_tst is not None and chk_tst != adr_tst: # could be a test like Class.test and a check like Class if not '.' in chk_tst: try: cls, mth = adr_tst.split('.') except ValueError: return False if cls != chk_tst: return False else: return False return True def startTest(self, test): if not self.missed: return found = [] for name in self.missed: if self.match(test, name): found.append(name) for name in found: self.missed.remove(name) PK••6¢BxÍß6ß6nose/plugins/base.pyimport os import re import textwrap from nose.util import tolist class Plugin(object): """Base class for nose plugins. It's not *necessary* to subclass this class to create a plugin; however, all plugins must implement `add_options(self, parser, env)` and `configure(self, options, conf)`, and must have the attributes `enabled` and `name`. Plugins should not be enabled by default. Subclassing Plugin will give your plugin some friendly default behavior: * A --with-$name option will be added to the command line interface to enable the plugin. The plugin class's docstring will be used as the help for this option. * The plugin will not be enabled unless this option is selected by the user. """ enabled = False enableOpt = None name = None def __init__(self): if self.name is None: self.name = self.__class__.__name__.lower() if self.enableOpt is None: self.enableOpt = "enable_plugin_%s" % self.name def add_options(self, parser, env=os.environ): """Add command-line options for this plugin. The base plugin class adds --with-$name by default, used to enable the plugin. """ env_opt = 'NOSE_WITH_%s' % self.name.upper() env_opt.replace('-', '_') parser.add_option("--with-%s" % self.name, action="store_true", dest=self.enableOpt, default=env.get(env_opt), help="Enable plugin %s: %s [%s]" % (self.__class__.__name__, self.help(), env_opt)) def configure(self, options, conf): """Configure the plugin and system, based on selected options. The base plugin class sets the plugin to enabled if the enable option for the plugin (self.enableOpt) is true. """ self.conf = conf if hasattr(options, self.enableOpt): self.enabled = getattr(options, self.enableOpt) def help(self): """Return help for this plugin. This will be output as the help section of the --with-$name option that enables the plugin. """ if self.__class__.__doc__: # doc sections are often indented; compress the spaces return textwrap.dedent(self.__class__.__doc__) return "(no help available)" # Compatiblity shim def tolist(self, val): from warnings import warn warn("Plugin.tolist is deprecated. Use nose.util.tolist instead", DeprecationWarning) return tolist(val) class IPluginInterface(object): """ Nose plugin API --------------- While it is recommended that plugins subclass nose.plugins.Plugin, the only requirements for a plugin are that it implement the methods `add_options(self, parser, env)` and `configure(self, options, conf)`, and have the attributes `enabled` and `name`. Plugins may implement any or all of the methods documented below. Please note that they *must not* subclass PluginInterface; PluginInterface is a only description of the plugin API. When plugins are called, the first plugin that implements a method and returns a non-None value wins, and plugin processing ends. The exceptions to this are `loadTestsFromModule`, `loadTestsFromName`, and `loadTestsFromPath`, which allow multiple plugins to load and return tests. In general, plugin methods correspond directly to methods of nose.selector.Selector, nose.loader.TestLoader and nose.result.TextTestResult are called by those methods when they are called. In some cases, the plugin hook doesn't neatly match the method in which it is called; for those, the documentation for the hook will tell you where in the test process it is called. Plugin hooks fall into two broad categories: selecting and loading tests, and watching and reporting on test results. Selecting and loading tests =========================== To alter test selection behavior, implement any necessary `want*` methods as outlined below. Keep in mind, though, that when your plugin returns True from a `want*` method, you will send the requested object through the normal test collection process. If the object represents something from which normal tests can't be collected, you must also implement a loader method to load the tests. Examples: * The builtin doctests plugin, for python 2.4 only, implements `wantFile` to enable loading of doctests from files that are not python modules. It also implements `loadTestsFromModule` to load doctests from python modules, and `loadTestsFromPath` to load tests from the non-module files selected by `wantFile`. * The builtin attrib plugin implements `wantFunction` and `wantMethod` so that it can reject tests that don't match the specified attributes. Watching or reporting on tests ============================== To record information about tests or other modules imported during the testing process, output additional reports, or entirely change test report output, implement any of the methods outlined below that correspond to TextTestResult methods. Examples: * The builtin cover plugin implements `begin` and `report` to capture and report code coverage metrics for all or selected modules loaded during testing. * The builtin profile plugin implements `begin`, `prepareTest` and `report` to record and output profiling information. In this case, the plugin's `prepareTest` method constructs a function that runs the test through the hotshot profiler's runcall() method. """ def __new__(cls, *arg, **kw): raise TypeError("IPluginInterface class is for documentation only") def addDeprecated(self, test): """Called when a deprecated test is seen. DO NOT return a value unless you want to stop other plugins from seeing the deprecated test. Parameters: * test: the test case """ pass def addError(self, test, err, capt): """Called when a test raises an uncaught exception. DO NOT return a value unless you want to stop other plugins from seeing that the test has raised an error. Parameters: * test: the test case * err: sys.exc_info() tuple * capt: Captured output, if any """ pass def addFailure(self, test, err, capt, tb_info): """Called when a test fails. DO NOT return a value unless you want to stop other plugins from seeing that the test has failed. Parameters: * test: the test case * err: sys.exc_info() tuple * capt: Captured output, if any * tb_info: Introspected traceback info, if any """ pass def addSkip(self, test): """Called when a test is skipped. DO NOT return a value unless you want to stop other plugins from seeing the skipped test. Parameters: * test: the test case """ pass def addSuccess(self, test, capt): """Called when a test passes. DO NOT return a value unless you want to stop other plugins from seeing the passing test. Parameters: * test: the test case * capt: Captured output, if any """ pass def begin(self): """Called before any tests are collected or run. Use this to perform any setup needed before testing begins. """ pass def finalize(self, result): """Called after all report output, including output from all plugins, has been sent to the stream. Use this to print final test results. Return None to allow other plugins to continue printing, any other value to stop them. """ pass def loadTestsFromModule(self, module): """Return iterable of tests in a module. May be a generator. Each item returned must be a runnable unittest.TestCase subclass. Return None if your plugin cannot collect any tests from module. Parameters: * module: The module object """ pass def loadTestsFromName(self, name, module=None, importPath=None): """Return tests in this file or module. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * name: The test name. May be a file or module name plus a test callable. Use split_test_name to split into parts. * module: Module in which the file is found * importPath: Path from which file (must be a python module) was found """ pass def loadTestsFromPath(self, path, module=None, importPath=None): """Return tests in this file or directory. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * path: The full path to the file or directory. * module: Module in which the file/dir is found * importPath: Path from which file (must be a python module) was found """ pass def loadTestsFromTestCase(self, cls): """Return tests in this test case class. Return None if you are not able to load any tests, or an iterable if you are. May be a generator. Parameters: * cls: The test case class """ pass def prepareTest(self, test): """Called before the test is run by the test runner. Please note the article *the* in the previous sentence: prepareTest is called *only once*, and is passed the test case or test suite that the test runner will execute. It is *not* called for each individual test case. If you return a non-None value, that return value will be run as the test. Use this hook to wrap or decorate the test with another function. Parameters: * test: the test case """ pass def report(self, stream): """Called after all error output has been printed. Print your plugin's report to the provided stream. Return None to allow other plugins to print reports, any other value to stop them. Parameters: * stream: stream object; send your output here """ pass def setOutputStream(self, stream): """Called before test output begins. To direct test output to a new stream, return a stream object, which must implement a `write(msg)` method. If you only want to note the stream, not capture or redirect it, then return None. Parameters: * stream: the original output stream """ def startTest(self, test): """Called before each test is run. DO NOT return a value unless you want to stop other plugins from seeing the test start. Parameters: * test: the test case """ pass def stopTest(self, test): """Called after each test is run. DO NOT return a value unless you want to stop other plugins from seeing that the test has stopped. Parameters: * test: the test case """ pass def wantClass(self, cls): """Return true if you want the main test selector to collect tests from this class, false if you don't, and None if you don't care. Parameters: * cls: The class """ pass def wantDirectory(self, dirname): """Return true if you want test collection to descend into this directory, false if you do not, and None if you don't care. Parameters: * dirname: Full path to directory """ pass def wantFile(self, file, package=None): """Return true if you want to collect tests from this file, false if you do not and None if you don't care. Parameters: * file: Full path to file * package: Package in which file is found, if any """ pass def wantFunction(self, function): """Return true to collect this function as a test, false to prevent it from being collected, and None if you don't care. Parameters: * function: The function object """ pass def wantMethod(self, method): """Return true to collect this method as a test, false to prevent it from being collected, and None if you don't care. Parameters: * method: The method object """ pass def wantModule(self, module): """Return true if you want to collection to descend into this module, false to prevent the collector from descending into the module, and None if you don't care. Parameters: * module: The module object """ pass def wantModuleTests(self, module): """Return true if you want the standard test loader to load tests from this module, false if you want to prevent it from doing so, and None if you don't care. DO NOT return true if your plugin will be loading the tests itself! Parameters: * module: The module object """ pass PK••6*K­o55nose/plugins/isolate.py"""Use the isolation plugin with --with-isolation or the NOSE_WITH_ISOLATION environment variable to clean sys.modules before and after each test module is executed. The isolation module is in effect the same as including the following functions in every test module and test package __init__.py: >>> def setup(module): ... module._mods = sys.modules.copy() >>> def teardown(module): ... to_del = [ m for m in sys.modules.keys() if m not in ... module._mods ] ... for mod in to_del: ... del sys.modules[mod] ... sys.modules.update(module._mods) PLEASE NOTE that this plugin MAY NOT be used in combination with the coverage plugin, as coverage data and state will be flushed after each test module is run. """ import logging import sys from nose.plugins import Plugin from nose.suite import TestModule log = logging.getLogger('nose.plugins.isolation') class IsolationPlugin(Plugin): """ Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used with the coverage plugin. """ name = 'isolation' def startTest(self, test): """Save the state of sys.modules if we're starting a test module """ if isinstance(test, TestModule): log.debug('isolating sys.modules changes in %s', test) self._mods = sys.modules.copy() def stopTest(self, test): """Restore the saved state of sys.modules if we're ending a test module """ if isinstance(test, TestModule): to_del = [ m for m in sys.modules.keys() if m not in self._mods ] if to_del: log.debug('removing sys modules entries: %s', to_del) for mod in to_del: del sys.modules[mod] sys.modules.update(self._mods) PK£žC8Lÿ÷ ÷ nose/plugins/missed.pyc;ò è’*Fc@s:dklZdklZlZdefd„ƒYZdS((sPlugin(ssplit_test_names test_addresss MissedTestscBs8tZdZdZd„Zd„Zd„Zd„ZRS(sq Enable to get a warning when tests specified on the command line are not found during the test run. s missed-testscCs/|ii o t|_n|ii|_dS(N(sselfsconfstestssNonesmissed(sself((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pysbegin s cCs:|io,x)|iD]}|iid|ƒqWndS(NsWARNING: missed test '%s'(sselfsmissedsresultsstreamswriteln(sselfsresultsmissed((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pysfinalizes  c Csút|ƒ\}}}t|ƒ\} }}| t j o|i | ƒ ot Sn|t j o|i |ƒ ot Sn|t j o ||jobd|j oLy|i dƒ\} }Wntj o t SnX| |jot Sqîqòt SntSdS(Ns.(s test_addressstestsadr_filesadr_modsadr_tstssplit_test_names test_nameschk_fileschk_modschk_tstsNones startswithsFalsessplitsclssmths ValueErrorsTrue( sselfstests test_namesadr_filesadr_modschk_tstsmthsadr_tstschk_modschk_filescls((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pysmatchs    cCsv|i odSng}x5|iD]*}|i||ƒo|i|ƒq#q#Wx|D]}|ii|ƒqXWdS(N(sselfsmissedsfoundsnamesmatchstestsappendsremove(sselfstestsfoundsname((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pys startTest+s  (s__name__s __module__s__doc__snamesbeginsfinalizesmatchs startTest(((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pys MissedTestss    N(snose.plugins.basesPlugins nose.utilssplit_test_names test_addresss MissedTests(ssplit_test_names test_addresss MissedTestssPlugin((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/missed.pys?s PK¤žC8ôÛ9œ‘‘nose/plugins/attrib.pyc;ò è’*Fc@s±dZdkZdkZdkZdkZdkZdklZdkl Z ei dƒZ ei ddfjZ dfd„ƒYZd fd „ƒYZd efd „ƒYZdS( s+Attribute selector plugin. Simple syntax (-a, --attr) examples: * nosetests -a status=stable => only test cases with attribute "status" having value "stable" * nosetests -a priority=2,status=stable => both attributes must match * nosetests -a priority=2 -a slow => either attribute must match * nosetests -a tags=http => attribute list "tags" must contain value "http" (see test_foobar() below for definition) * nosetests -a slow => attribute "slow" must be defined and its value cannot equal to False (False, [], "", etc...) * nosetests -a !slow => attribute "slow" must NOT be defined or its value must be equal to False Eval expression syntax (-A, --eval-attr) examples: * nosetests -A "not slow" * nosetests -A "(priority > 5) and not slow" N(sPlugin(stolistsnose.plugins.attribiis ContextHelpercBs tZdZd„Zd„ZRS(s.Returns default values for dictionary lookups.cCs ||_dS(N(sobjsself(sselfsobj((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys__init__+scCs|ii|tƒSdS(N(sselfsobjsgetsnamesFalse(sselfsname((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys __getitem__.s(s__name__s __module__s__doc__s__init__s __getitem__(((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys ContextHelper)s  sAttributeGettercBs,tZdZeƒZd„Zed„ZRS(sHelper for looking up attributes First we check the method, and if the attribute is not present, we check the method's class. cCs||_||_dS(N(sclssselfsmethod(sselfsclssmethod((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys__init__:s cCs‹tid||i|iƒ|iii||iƒ}||ijo<tid|ƒt |i||ƒ}tid||ƒn|SdS(NsGet %s from %s.%ss-No attribute %s in method, getting from classsClass attribute %s value: %s( slogsdebugsnamesselfsclssmethods__dict__sgetsmissingsvalsgetattrsdefault(sselfsnamesdefaultsval((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pysget>s (s__name__s __module__s__doc__sobjectsmissings__init__sNonesget(((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pysAttributeGetter2s   sAttributeSelectorcBsJtZdZd„Zeid„Zd„Zd„Zd„Z d„Z RS(s<Selects test cases to be run based on their attributes. cCsti|ƒg|_dS(N(sPlugins__init__sselfsattribs(sself((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys__init__Ls c Csw|iddddddd|idƒd d ƒto;|id d dd ddddd|idƒd dƒndS(s)Add command-line options for this plugin.s-as--attrsdestsattrsactionsappendsdefaults NOSE_ATTRshelpsARun only tests that have attributes specified by ATTR [NOSE_ATTR]s-As --eval-attrs eval_attrsmetavarsEXPRsNOSE_EVAL_ATTRsaRun only tests for whose attributes the Python expression EXPR evaluates to True [NOSE_EVAL_ATTR]N(sparsers add_optionsenvsgets compat_24(sselfsparsersenv((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys add_optionsPs    c Cseg|_to|ioFt|iƒ}x4|D](}d„}|ii||fgƒq0Wn|ioàt|iƒ}xÎ|D]Â}g}x£|i dƒD]’} | oqœn| i ddƒ}t|ƒdjo|\} } n6|d} | ddjo| d} t} nt} |i| | fƒqœW|ii|ƒq€Wn|io t|_ndS(sConfigure the plugin and system, based on selected options. attr and eval_attr may each be lists. self.attribs will be a list of lists of tuples. In that list, each list is a group of attributes, all of which must match for the rule to match. cCst|tt|ƒƒSdS(N(sevalsexprsNones ContextHelpersattribs(sexprsattribs((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pyseval_in_contextrss,s=iis!N(sselfsattribss compat_24soptionss eval_attrstolistsattrseval_in_contextsappendsstd_attrs attr_groupssplitsattribsitemsslenskeysvaluesFalsesTruesenabled( sselfsoptionssconfigsattrs attr_groupsitemsseval_in_contextsstd_attrs eval_attrskeysattribsvalue((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys configureas:  !     c CsŠt}xj|iD]_}t} xC|D];\}}|i |ƒ}t |ƒo |||ƒ o t} Pq^q#|tjot |ƒ o t} Pq^q#|tjot |ƒo t} Pq^q#t |ƒttfjoJ|gi}|D]}|t|ƒiƒƒqè~j o t} Pq^q#||jo"t|ƒiƒt|ƒiƒjo t} Pq#q#W|p| }qW|otSntSdS(N(sFalsesanysselfsattribssgroupsTruesmatchskeysvaluesgets obj_valuescallablesboolstypesliststuplesappends_[1]sxsstrslowersNone( sselfsattribss_[1]sgroups obj_valuesvalueskeysxsanysmatch((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pysvalidateAttrib–s<         ; 2 cCs|i|iƒSdS(N(sselfsvalidateAttribsfunctions__dict__(sselfsfunction((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys wantFunctionÁscCs#t|i|ƒ}|i|ƒSdS(N(sAttributeGettersmethodsim_classsattribssselfsvalidateAttrib(sselfsmethodsattribs((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys wantMethodÄs( s__name__s __module__s__doc__s__init__sossenvirons add_optionss configuresvalidateAttribs wantFunctions wantMethod(((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pysAttributeSelectorHs   5 + (s__doc__sloggingsossressysstextwrapsnose.plugins.basesPlugins nose.utilstolists getLoggerslogs version_infos compat_24s ContextHelpersAttributeGettersAttributeSelector( stolists compat_24sloggingslogsPlugins ContextHelperstextwrapssyssresAttributeSelectorsAttributeGettersos((s7build/bdist.darwin-8.0.1-x86/egg/nose/plugins/attrib.pys?s        PK¤žC8Ô ïïnose/plugins/cover.pyc;ò è’*Fc@sddZdkZdkZdkZdklZdklZeie ƒZ defd„ƒYZ dS(s¦If you have Ned Batchelder's coverage_ module installed, you may activate a coverage report with the --with-coverage switch or NOSE_WITH_COVERAGE environment variable. The coverage report will cover any python source module imported after the start of the test run, excluding modules that match testMatch. If you want to include those modules too, use the --cover-tests switch, or set the NOSE_COVER_TESTS environment variable to a true value. To restrict the coverage report to modules from a particular package or packages, use the --cover-packages switch or the NOSE_COVER_PACKAGES environment variable. .. _coverage: http://www.nedbatchelder.com/code/modules/coverage.html N(sPlugin(stolistsCoveragecBsYtZdZeZeZeid„Z d„Z d„Z d„Z d„Z ed„ZRS(s8 If you have Ned Batchelder's coverage module installed, you may activate a coverage report. The coverage report will cover any python source module imported after the start of the test run, excluding modules that match testMatch. If you want to include those modules too, use the --cover-tests switch, or set the NOSE_COVER_TESTS environment variable to a true value. To restrict the coverage report to modules from a particular package or packages, use the --cover-packages switch or the NOSE_COVER_PACKAGES environment variable. c CsÏti|||ƒ|idddd|idƒdddd ƒ|id dd d|id ƒdd ddƒ|iddd ddd|idƒddƒ|iddd ddd|idƒddƒdS(Ns--cover-packagesactionsappendsdefaultsNOSE_COVER_PACKAGEsdestscover_packagesshelpsBRestrict coverage output to selected packages [NOSE_COVER_PACKAGE]s --cover-erases store_truesNOSE_COVER_ERASEs cover_erases9Erase previously collected coverage statistics before runs --cover-testss cover_testssNOSE_COVER_TESTSs:Include test modules in coverage report [NOSE_COVER_TESTS]s--cover-inclusivescover_inclusivesNOSE_COVER_INCLUSIVEs»Include all python files under working directory in coverage report. Useful for discovering holes in test coverage if not all files are imported by the test suite. [NOSE_COVER_INCLUSIVE](sPlugins add_optionssselfsparsersenvs add_optionsget(sselfsparsersenv((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pys add_options#s"   cCsÂti|||ƒ|ioAy dk}Wq^tj o!ti dƒt |_dSq^Xn||_ |i |_ |i|_t|iƒ|_|i|_|iotid|iƒndS(Ns8Coverage not available: unable to import coverage modules.Coverage report will include only packages: %s(sPlugins configuresselfsoptionssconfigsenabledscoverages ImportErrorslogserrorsFalsesconfs cover_erases coverErases cover_testss coverTestsstolistscover_packagess coverPackagesscover_inclusivescoverInclusivesinfo(sselfsoptionssconfigscoverage((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pys configure>s            cCsitidƒdk}tiiƒ|_|iotidƒ|i ƒn|i dƒ|i ƒdS(NsCoverage begins1Clearing previously collected coverage statisticss)#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]( slogsdebugscoveragessyssmodulesskeyssselfs skipModuless coverEraseserasesexcludesstart(sselfscoverage((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pysbeginQs     cCs¡tidƒdk}|iƒ|iiƒgi}ti i ƒD]-\}}|i||ƒo||ƒqDqD~}tid|ƒ|i|d|ƒdS(NsCoverage reports&Coverage report will cover modules: %ssfile(slogsdebugscoveragesstops the_coveragessavesappends_[1]ssyssmodulessitemssnamesmodulesselfswantModuleCoveragesreportsstream(sselfsstreamsmodulessmodules_[1]scoveragesname((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pysreport[s    McCsKt|dƒ otid|ƒtSntii|i ƒ\}}|dddfj otid|ƒtSn|i oax^|i D]O}|i|ƒo|ip|iii|ƒ otid|ƒtSq‡q‡Wn||ijotid|ƒtSn|iii|ƒo|i otid |ƒtSn|i SdS( Ns__file__sno coverage of %s: no __file__s.pys.pycs.pyos$no coverage of %s: not a python filescoverage for %ss0no coverage for %s: loaded before coverage startsno coverage for %s: is a test(shasattrsmoduleslogsdebugsnamesFalsesosspathssplitexts__file__srootsextsselfs coverPackagesspackages startswiths coverTestssconfs testMatchssearchsTrues skipModules(sselfsnamesmodulespackagesextsroot((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pyswantModuleCoveragegs*  1 !cCso|io]|idƒoI|o|io0x1|iD]}|i|ƒotSq5q5WqctSqgnt SdS(s\If inclusive coverage enabled, return true for all source files in wanted packages.s.pyN( sselfscoverInclusivesfilesendswithspackages coverPackagesswants startswithsTruesNone(sselfsfilespackageswant((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pyswantFile‚s   (s__name__s __module__s__doc__sFalses coverTestssNones coverPackagessossenvirons add_optionss configuresbeginsreportswantModuleCoverageswantFile(((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pysCoverages   ( s__doc__sloggingsosssyssnose.plugins.basesPlugins nose.utilstolists getLoggers__name__slogsCoverage(stolistsloggingslogsPluginssyssCoveragesos((s6build/bdist.darwin-8.0.1-x86/egg/nose/plugins/cover.pys? s     PK••6'äD Î Î nose/plugins/prof.py"""Use the profile plugin with --with-profile or NOSE_WITH_PROFILE to enable profiling using the hotshot profiler. Profiler output can be controlled with the --profile-sort and --profile-restrict, and the profiler output file may be changed with --profile-stats-file. See the hotshot documentation in the standard library documentation for more details on the various output options. """ import hotshot, hotshot.stats import logging import os import sys import tempfile from nose.plugins.base import Plugin from nose.util import tolist log = logging.getLogger('nose.plugins') class Profile(Plugin): """ Use this plugin to run tests using the hotshot profiler. """ pfile = None fileno = None clean_stats_file = True def add_options(self, parser, env=os.environ): Plugin.add_options(self, parser, env) parser.add_option('--profile-sort',action='store',dest='profile_sort', default=env.get('NOSE_PROFILE_SORT','cumulative'), help="Set sort order for profiler output") parser.add_option('--profile-stats-file',action='store', dest='profile_stats_file', default=env.get('NOSE_PROFILE_STATS_FILE'), help='Profiler stats file; default is a new ' 'temp file on each run') parser.add_option('--profile-restrict',action='append', dest='profile_restrict', default=env.get('NOSE_PROFILE_RESTRICT'), help="Restrict profiler output. See help for " "pstats.Stats for details") def begin(self): self._create_pfile() self.prof = hotshot.Profile(self.pfile) def configure(self, options, conf): Plugin.configure(self, options, conf) self.options = options self.conf = conf if options.profile_stats_file: self.pfile = options.profile_stats_file self.clean_stats_file = False else: self.pfile = None self.clean_stats_file = True self.fileno = None self.sort = options.profile_sort self.restrict = tolist(options.profile_restrict) def prepareTest(self, test): log.debug('preparing test %s' % test) def run_and_profile(result, prof=self.prof, test=test): self._create_pfile() prof.runcall(test, result) return run_and_profile def report(self, stream): log.debug('printing profiler report') self.prof.close() stats = hotshot.stats.load(self.pfile) stats.sort_stats(self.sort) try: tmp = sys.stdout sys.stdout = stream if self.restrict: log.debug('setting profiler restriction to %s', self.restrict) stats.print_stats(*self.restrict) else: stats.print_stats() finally: sys.stdout = tmp def finalize(self, result): if self.clean_stats_file: if self.fileno: try: os.close(self.fileno) except OSError: pass try: os.unlink(self.pfile) except OSError: pass return None def _create_pfile(self): if not self.pfile: self.fileno, self.pfile = tempfile.mkstemp() PK••6.‰Gªnose/plugins/attrib.py"""Attribute selector plugin. Simple syntax (-a, --attr) examples: * nosetests -a status=stable => only test cases with attribute "status" having value "stable" * nosetests -a priority=2,status=stable => both attributes must match * nosetests -a priority=2 -a slow => either attribute must match * nosetests -a tags=http => attribute list "tags" must contain value "http" (see test_foobar() below for definition) * nosetests -a slow => attribute "slow" must be defined and its value cannot equal to False (False, [], "", etc...) * nosetests -a !slow => attribute "slow" must NOT be defined or its value must be equal to False Eval expression syntax (-A, --eval-attr) examples: * nosetests -A "not slow" * nosetests -A "(priority > 5) and not slow" """ import logging import os import re import sys import textwrap from nose.plugins.base import Plugin from nose.util import tolist log = logging.getLogger('nose.plugins.attrib') compat_24 = sys.version_info >= (2, 4) class ContextHelper: """Returns default values for dictionary lookups.""" def __init__(self, obj): self.obj = obj def __getitem__(self, name): return self.obj.get(name, False) class AttributeGetter: """Helper for looking up attributes First we check the method, and if the attribute is not present, we check the method's class. """ missing = object() def __init__(self, cls, method): self.cls = cls self.method = method def get(self, name, default=None): log.debug('Get %s from %s.%s', name, self.cls, self.method) val = self.method.__dict__.get(name, self.missing) if val is self.missing: log.debug('No attribute %s in method, getting from class', name) val = getattr(self.cls, name, default) log.debug('Class attribute %s value: %s', name, val) return val class AttributeSelector(Plugin): """Selects test cases to be run based on their attributes. """ def __init__(self): Plugin.__init__(self) self.attribs = [] def add_options(self, parser, env=os.environ): """Add command-line options for this plugin.""" parser.add_option("-a", "--attr", dest="attr", action="append", default=env.get('NOSE_ATTR'), help="Run only tests that have attributes " "specified by ATTR [NOSE_ATTR]") # disable in < 2.4: eval can't take needed args if compat_24: parser.add_option("-A", "--eval-attr", dest="eval_attr", metavar="EXPR", action="append", default=env.get('NOSE_EVAL_ATTR'), help="Run only tests for whose attributes " "the Python expression EXPR evaluates " "to True [NOSE_EVAL_ATTR]") def configure(self, options, config): """Configure the plugin and system, based on selected options. attr and eval_attr may each be lists. self.attribs will be a list of lists of tuples. In that list, each list is a group of attributes, all of which must match for the rule to match. """ self.attribs = [] # handle python eval-expression parameter if compat_24 and options.eval_attr: eval_attr = tolist(options.eval_attr) for attr in eval_attr: # "" # -> eval(expr) in attribute context must be True def eval_in_context(expr, attribs): return eval(expr, None, ContextHelper(attribs)) self.attribs.append([(attr, eval_in_context)]) # attribute requirements are a comma separated list of # 'key=value' pairs if options.attr: std_attr = tolist(options.attr) for attr in std_attr: # all attributes within an attribute group must match attr_group = [] for attrib in attr.split(","): # don't die on trailing comma if not attrib: continue items = attrib.split("=", 1) if len(items) > 1: # "name=value" # -> 'str(obj.name) == value' must be True key, value = items else: key = items[0] if key[0] == "!": # "!name" # 'bool(obj.name)' must be False key = key[1:] value = False else: # "name" # -> 'bool(obj.name)' must be True value = True attr_group.append((key, value)) self.attribs.append(attr_group) if self.attribs: self.enabled = True def validateAttrib(self, attribs): # TODO: is there a need for case-sensitive value comparison? # within each group, all must match for the group to match # if any group matches, then the attribute set as a whole # has matched any = False for group in self.attribs: match = True for key, value in group: obj_value = attribs.get(key) if callable(value): if not value(key, attribs): match = False break elif value is True: # value must exist and be True if not bool(obj_value): match = False break elif value is False: # value must not exist or be False if bool(obj_value): match = False break elif type(obj_value) in (list, tuple): # value must be found in the list attribute if not value in [str(x).lower() for x in obj_value]: match = False break else: # value must match, convert to string and compare if (value != obj_value and str(value).lower() != str(obj_value).lower()): match = False break any = any or match if any: # not True because we don't want to FORCE the selection of the # item, only say that it is acceptable return None return False def wantFunction(self, function): return self.validateAttrib(function.__dict__) def wantMethod(self, method): attribs = AttributeGetter(method.im_class, method) return self.validateAttrib(attribs) PK••6ìÀº¯¯nose/plugins/cover.py"""If you have Ned Batchelder's coverage_ module installed, you may activate a coverage report with the --with-coverage switch or NOSE_WITH_COVERAGE environment variable. The coverage report will cover any python source module imported after the start of the test run, excluding modules that match testMatch. If you want to include those modules too, use the --cover-tests switch, or set the NOSE_COVER_TESTS environment variable to a true value. To restrict the coverage report to modules from a particular package or packages, use the --cover-packages switch or the NOSE_COVER_PACKAGES environment variable. .. _coverage: http://www.nedbatchelder.com/code/modules/coverage.html """ import logging import os import sys from nose.plugins.base import Plugin from nose.util import tolist log = logging.getLogger(__name__) class Coverage(Plugin): """ If you have Ned Batchelder's coverage module installed, you may activate a coverage report. The coverage report will cover any python source module imported after the start of the test run, excluding modules that match testMatch. If you want to include those modules too, use the --cover-tests switch, or set the NOSE_COVER_TESTS environment variable to a true value. To restrict the coverage report to modules from a particular package or packages, use the --cover-packages switch or the NOSE_COVER_PACKAGES environment variable. """ coverTests = False coverPackages = None def add_options(self, parser, env=os.environ): Plugin.add_options(self, parser, env) parser.add_option("--cover-package", action="append", default=env.get('NOSE_COVER_PACKAGE'), dest="cover_packages", help="Restrict coverage output to selected packages " "[NOSE_COVER_PACKAGE]") parser.add_option("--cover-erase", action="store_true", default=env.get('NOSE_COVER_ERASE'), dest="cover_erase", help="Erase previously collected coverage " "statistics before run") parser.add_option("--cover-tests", action="store_true", dest="cover_tests", default=env.get('NOSE_COVER_TESTS'), help="Include test modules in coverage report " "[NOSE_COVER_TESTS]") parser.add_option("--cover-inclusive", action="store_true", dest="cover_inclusive", default=env.get('NOSE_COVER_INCLUSIVE'), help="Include all python files under working " "directory in coverage report. Useful for " "discovering holes in test coverage if not all " "files are imported by the test suite. " "[NOSE_COVER_INCLUSIVE]") def configure(self, options, config): Plugin.configure(self, options, config) if self.enabled: try: import coverage except ImportError: log.error("Coverage not available: " "unable to import coverage module") self.enabled = False return self.conf = config self.coverErase = options.cover_erase self.coverTests = options.cover_tests self.coverPackages = tolist(options.cover_packages) self.coverInclusive = options.cover_inclusive if self.coverPackages: log.info("Coverage report will include only packages: %s", self.coverPackages) def begin(self): log.debug("Coverage begin") import coverage self.skipModules = sys.modules.keys()[:] if self.coverErase: log.debug("Clearing previously collected coverage statistics") coverage.erase() coverage.exclude('#pragma[: ]+[nN][oO] [cC][oO][vV][eE][rR]') coverage.start() def report(self, stream): log.debug("Coverage report") import coverage coverage.stop() coverage.the_coverage.save() modules = [ module for name, module in sys.modules.items() if self.wantModuleCoverage(name, module) ] log.debug("Coverage report will cover modules: %s", modules) coverage.report(modules, file=stream) def wantModuleCoverage(self, name, module): if not hasattr(module, '__file__'): log.debug("no coverage of %s: no __file__", name) return False root, ext = os.path.splitext(module.__file__) if not ext in ('.py', '.pyc', '.pyo'): log.debug("no coverage of %s: not a python file", name) return False if self.coverPackages: for package in self.coverPackages: if (name.startswith(package) and (self.coverTests or not self.conf.testMatch.search(name))): log.debug("coverage for %s", name) return True if name in self.skipModules: log.debug("no coverage for %s: loaded before coverage start", name) return False if self.conf.testMatch.search(name) and not self.coverTests: log.debug("no coverage for %s: is a test", name) return False # accept any package that passed the previous tests, unless # coverPackages is on -- in that case, if we wanted this # module, we would have already returned True return not self.coverPackages def wantFile(self, file, package=None): """If inclusive coverage enabled, return true for all source files in wanted packages.""" if self.coverInclusive: if file.endswith(".py"): if package and self.coverPackages: for want in self.coverPackages: if package.startswith(want): return True else: return True return None PK£žC87ûÝ--nose/plugins/__init__.pyc;ò è’*Fc@s‰dZdklZdkZdkZdklZdklZdk Tdddd d d fZ ei e ƒZ d „Zeed „ZdS(s&Writing Plugins --------------- nose supports setuptools_ entry point plugins for test collection, selection, observation and reporting. There are two basic rules for plugins: * Plugin classes should subclass `nose.plugins.Plugin`_. * Plugins may implement any of the methods described in the class PluginInterface in nose.plugins.base. Please note that this class is for documentary purposes only; plugins may not subclass PluginInterface. .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _nose.plugins.Plugin: http://python-nose.googlecode.com/svn/trunk/nose/plugins/base.py Registering =========== For nose to find a plugin, it must be part of a package that uses setuptools, and the plugin must be included in the entry points defined in the setup.py for the package:: setup(name='Some plugin', ... entry_points = { 'nose.plugins': [ 'someplugin = someplugin:SomePlugin' ] }, ... ) Once the package is installed with install or develop, nose will be able to load the plugin. Defining options ================ All plugins must implement the methods ``add_options(self, parser, env)`` and ``configure(self, options, conf)``. Subclasses of nose.plugins.Plugin that want the standard options should call the superclass methods. nose uses optparse.OptionParser from the standard library to parse arguments. A plugin's ``add_options()`` method receives a parser instance. It's good form for a plugin to use that instance only to add additional arguments that take only long arguments (--like-this). Most of nose's built-in arguments get their default value from an environment variable. This is a good practice because it allows options to be utilized when run through some other means than the nosetests script. A plugin's ``configure()`` method receives the parsed ``OptionParser`` options object, as well as the current config object. Plugins should configure their behavior based on the user-selected settings, and may raise exceptions if the configured behavior is nonsensical. Logging ======= nose uses the logging classes from the standard library. To enable users to view debug messages easily, plugins should use ``logging.getLogger()`` to acquire a logger in the ``nose.plugins`` namespace. Recipes ======= * Writing a plugin that monitors or controls test result output Implement any or all of ``addError``, ``addFailure``, etc., to monitor test results. If you also want to monitor output, implement ``setOutputStream`` and keep a reference to the output stream. If you want to prevent the builtin ``TextTestResult`` output, implement ``setOutputSteam`` and *return a dummy stream*. The default output will go to the dummy stream, while you send your desired output to the real stream. Example: `examples/html_plugin/htmlplug.py`_ * Writing a plugin that loads tests from files other than python modules Implement ``wantFile`` and ``loadTestsFromPath``. In ``wantFile``, return True for files that you want to examine for tests. In ``loadTestsFromPath``, for those files, return a TestSuite or other iterable containing TestCases. ``loadTestsFromPath`` may also be a generator. Example: `nose.plugins.doctests`_ * Writing a plugin that prints a report Implement begin if you need to perform setup before testing begins. Implement ``report`` and output your report to the provided stream. Examples: `nose.plugins.cover`_, `nose.plugins.profile`_, `nose.plugins.missed`_ * Writing a plugin that selects or rejects tests Implement any or all ``want*`` methods. Return False to reject the test candidate, True to accept it -- which means that the test candidate will pass through the rest of the system, so you must be prepared to load tests from it if tests can't be loaded by the core loader or another plugin -- and None if you don't care. Examples: `nose.plugins.attrib`_, `nose.plugins.doctests`_ Examples ======== See `nose.plugins.attrib`_, `nose.plugins.cover`_, `nose.plugins.doctests`_ and `nose.plugins.profile`_ for examples. Further examples may be found the examples_ directory in the nose source distribution. .. _examples/html_plugin/htmlplug.py: http://python-nose.googlecode.com/svn/trunk/examples/html_plugin/htmlplug.py .. _examples: http://python-nose.googlecode.com/svn/trunk/examples .. _nose.plugins.attrib: http://python-nose.googlecode.com/svn/trunk/nose/plugins/attrib.py .. _nose.plugins.cover: http://python-nose.googlecode.com/svn/trunk/nose/plugins/cover.py .. _nose.plugins.doctests: http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py .. _nose.plugins.missed: http://python-nose.googlecode.com/svn/trunk/nose/plugins/missed.py .. _nose.plugins.profile: http://python-nose.googlecode.com/svn/trunk/nose/plugins/profile.py (s generatorsN(sisclass(swarn(s*sattribscoversdoctestssisolatesmissedsprofcOsyxn|D]f}t||tƒ}|tjoqntid|i|ƒ|||Ž}|tj o|SqqWtSdS(s†Call all method on plugins in list, that define it, with provided arguments. The first response that is not None is returned. scall plugin %s: %sN( spluginssplugsgetattrsmethodsNonesfuncslogsdebugsnamesargskwsresult(spluginssmethodsargskwsplugsresultsfunc((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/__init__.pys call_pluginss   c csðg}|oxtD]}y»tttƒtƒ|gƒ}t ||ƒ}x‡t |ƒD]y} t || ƒ}t|ƒo(t|tƒo|tj o ||j o,tid||fƒ|V|i|ƒqWqWWWqtj o ‚qtj o } td|| ftƒqXqWn| odSnx¸tidƒD]§}tid|ƒy|iƒ}WnDtj o ‚n0tj o#} td|| ftƒqAnX|ii dƒoqA||jo|V|i|ƒqAqAWdS(s3Load plugins, either builtin, others, or both. sload builtin plugin %s (%s)s$Unable to load builtin plugin %s: %sNs nose.pluginssload plugin %ssUnable to load plugin %s: %s(!sloadedsbuiltinsbuiltin_pluginssnames __import__s__name__sglobalsslocalssparentsgetattrspmodsdirsentrysobjsisclasss issubclasssPluginslogsdebugsappendsKeyboardInterrupts ExceptionseswarnsRuntimeWarningsotherss pkg_resourcessiter_entry_pointssepsloadsplugs __module__s startswith( sbuiltinsotherssloadedsepspmodsparentsplugsobjsnamesentryse((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/__init__.pys load_pluginssJ 8 (s__doc__s __future__s generatorssloggings pkg_resourcessinspectsisclassswarningsswarnsnose.plugins.basesbuiltin_pluginss getLoggers__name__slogs call_pluginssTrues load_plugins( s load_pluginssloggingslogsisclasss pkg_resourcesswarns generatorss call_pluginssbuiltin_plugins((s9build/bdist.darwin-8.0.1-x86/egg/nose/plugins/__init__.pys?us      PK¤žC8ÊûŒŒŒnose/plugins/prof.pyc;ò è’*Fc@sdZdkZdkZdkZdkZdkZdkZdklZdk l Z ei dƒZ defd„ƒYZ dS(s~Use the profile plugin with --with-profile or NOSE_WITH_PROFILE to enable profiling using the hotshot profiler. Profiler output can be controlled with the --profile-sort and --profile-restrict, and the profiler output file may be changed with --profile-stats-file. See the hotshot documentation in the standard library documentation for more details on the various output options. N(sPlugin(stolists nose.pluginssProfilecBsetZdZeZeZeZei d„Z d„Z d„Z d„Z d„Zd„Zd„ZRS(sC Use this plugin to run tests using the hotshot profiler. c Cs¤ti|||ƒ|idddddd|iddƒd d ƒ|id dddd d|id ƒd dƒ|idddddd|idƒd dƒdS(Ns--profile-sortsactionsstoresdests profile_sortsdefaultsNOSE_PROFILE_SORTs cumulativeshelps"Set sort order for profiler outputs--profile-stats-filesprofile_stats_filesNOSE_PROFILE_STATS_FILEs;Profiler stats file; default is a new temp file on each runs--profile-restrictsappendsprofile_restrictsNOSE_PROFILE_RESTRICTs?Restrict profiler output. See help for pstats.Stats for details(sPlugins add_optionssselfsparsersenvs add_optionsget(sselfsparsersenv((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pys add_optionss  cCs#|iƒti|iƒ|_dS(N(sselfs _create_pfileshotshotsProfilespfilesprof(sself((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pysbegin-s cCs…ti|||ƒ||_||_|io|i|_t|_nt |_t |_t |_ |i |_ t|iƒ|_dS(N(sPlugins configuresselfsoptionssconfsprofile_stats_filespfilesFalsesclean_stats_filesNonesTruesfilenos profile_sortssortstolistsprofile_restrictsrestrict(sselfsoptionssconf((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pys configure1s         cs.tid|ƒˆi|‡d†}|SdS(Nspreparing test %scsˆiƒ|i||ƒdS(N(sselfs _create_pfilesprofsruncallstestsresult(sresultsprofstest(sself(s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pysrun_and_profileBs (slogsdebugstestsselfsprofsrun_and_profile(sselfstestsrun_and_profile((sselfs5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pys prepareTest@scCs¡tidƒ|iiƒtii|iƒ}|i |i ƒzQt i }|t _ |io'tid|iƒ|i|iŒn |iƒWd|t _ XdS(Nsprinting profiler reports"setting profiler restriction to %s(slogsdebugsselfsprofscloseshotshotsstatssloadspfiles sort_statsssortssyssstdoutstmpsstreamsrestricts print_stats(sselfsstreamstmpsstats((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pysreportGs     cCsx|iof|io.yti|iƒWqBtj oqBXnyti|iƒWqptj oqpXntSdS(N( sselfsclean_stats_filesfilenosossclosesOSErrorsunlinkspfilesNone(sselfsresult((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pysfinalizeWs    cCs+|i otiƒ\|_|_ndS(N(sselfspfilestempfilesmkstempsfileno(sself((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pys _create_pfileds (s__name__s __module__s__doc__sNonespfilesfilenosTruesclean_stats_filesossenvirons add_optionssbegins configures prepareTestsreportsfinalizes _create_pfile(((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pysProfiles      (s__doc__shotshots hotshot.statssloggingsosssysstempfilesnose.plugins.basesPlugins nose.utilstolists getLoggerslogsProfile( sProfilestolistsloggingslogsPluginstempfilessysshotshotsos((s5build/bdist.darwin-8.0.1-x86/egg/nose/plugins/prof.pys?s      PK£žC8ÜÞQµ µ nose/plugins/isolate.pyc;ò è’*Fc@s[dZdkZdkZdklZdklZeidƒZdefd„ƒYZ dS(sUse the isolation plugin with --with-isolation or the NOSE_WITH_ISOLATION environment variable to clean sys.modules before and after each test module is executed. The isolation module is in effect the same as including the following functions in every test module and test package __init__.py: >>> def setup(module): ... module._mods = sys.modules.copy() >>> def teardown(module): ... to_del = [ m for m in sys.modules.keys() if m not in ... module._mods ] ... for mod in to_del: ... del sys.modules[mod] ... sys.modules.update(module._mods) PLEASE NOTE that this plugin MAY NOT be used in combination with the coverage plugin, as coverage data and state will be flushed after each test module is run. N(sPlugin(s TestModulesnose.plugins.isolationsIsolationPlugincBs&tZdZdZd„Zd„ZRS(sF Activate the isolation plugin to isolate changes to external modules to a single test module or package. The isolation plugin resets the contents of sys.modules after each test module or package runs to its state before the test. PLEASE NOTE that this plugin may not be used with the coverage plugin. s isolationcCs:t|tƒo&tid|ƒtiiƒ|_ ndS(sFSave the state of sys.modules if we're starting a test module s#isolating sys.modules changes in %sN( s isinstancestests TestModuleslogsdebugssyssmodulesscopysselfs_mods(sselfstest((s8build/bdist.darwin-8.0.1-x86/egg/nose/plugins/isolate.pys startTest*scCs¥t|tƒo‘gi}tiiƒD]$}||i jo||ƒq'q'~}|o/t i d|ƒx|D]}ti|=qrWntii|i ƒndS(sMRestore the saved state of sys.modules if we're ending a test module s removing sys modules entries: %sN(s isinstancestests TestModulesappends_[1]ssyssmodulesskeyssmsselfs_modssto_delslogsdebugsmodsupdate(sselfstestsms_[1]smodsto_del((s8build/bdist.darwin-8.0.1-x86/egg/nose/plugins/isolate.pysstopTest1sD(s__name__s __module__s__doc__snames startTestsstopTest(((s8build/bdist.darwin-8.0.1-x86/egg/nose/plugins/isolate.pysIsolationPlugin s  ( s__doc__sloggingssyss nose.pluginssPlugins nose.suites TestModules getLoggerslogsIsolationPlugin(sloggingslogsPluginsIsolationPluginssyss TestModule((s8build/bdist.darwin-8.0.1-x86/egg/nose/plugins/isolate.pys?s     PK žC8ÖTJ´ëëEGG-INFO/SOURCES.txtAUTHORS CHANGELOG MANIFEST.in NEWS NEWS_0.9 README.txt TODO_0_9 ez_setup.py index.html.tpl lgpl.txt nosetests.1 setup.cfg setup.py tickets.csv tickets.rss examples/attrib_plugin.py examples/html_plugin/htmlplug.py examples/html_plugin/setup.py examples/plugin/plug.py examples/plugin/setup.py nose/__init__.py nose/case.py nose/commands.py nose/config.py nose/core.py nose/exc.py nose/importer.py nose/inspector.py nose/loader.py nose/proxy.py nose/result.py nose/selector.py nose/suite.py nose/tools.py nose/twistedtools.py nose/util.py nose.egg-info/PKG-INFO nose.egg-info/SOURCES.txt nose.egg-info/dependency_links.txt nose.egg-info/entry_points.txt nose.egg-info/top_level.txt nose/plugins/__init__.py nose/plugins/attrib.py nose/plugins/base.py nose/plugins/cover.py nose/plugins/doctests.py nose/plugins/isolate.py nose/plugins/missed.py nose/plugins/prof.py scripts/mkindex.py scripts/mkrelease.py scripts/mkwiki.py scripts/rst2wiki.py unit_tests/helpers.py unit_tests/mock.py unit_tests/test_bug105.py unit_tests/test_cases.py unit_tests/test_collector.py unit_tests/test_config.py unit_tests/test_core.py unit_tests/test_doctest_error_handling.py unit_tests/test_importer.py unit_tests/test_inspector.py unit_tests/test_isolation_plugin.py unit_tests/test_issue_006.py unit_tests/test_lazy_suite.py unit_tests/test_loader.py unit_tests/test_logging.py unit_tests/test_plugin_interfaces.py unit_tests/test_plugins.py unit_tests/test_proxy.py unit_tests/test_result.py unit_tests/test_selector.py unit_tests/test_selector_plugins.py unit_tests/test_tools.py unit_tests/test_twisted.py unit_tests/test_twisted_testcase.py unit_tests/test_utils.py unit_tests/support/script.py unit_tests/support/test.py unit_tests/support/bug101/tests.py unit_tests/support/bug105/tests.py unit_tests/support/doctest/err_doctests.py unit_tests/support/doctest/no_doctests.py unit_tests/support/foo/__init__.py unit_tests/support/foo/doctests.txt unit_tests/support/foo/test_foo.py unit_tests/support/foo/bar/__init__.py unit_tests/support/foo/bar/buz.py unit_tests/support/foo/tests/dir_test_file.py unit_tests/support/issue006/tests.py unit_tests/support/other/file.txt unit_tests/support/pkgorg/lib/modernity.py unit_tests/support/pkgorg/tests/test_mod.py unit_tests/support/test-dir/test.py PK žC8¬ƒÖÝggEGG-INFO/entry_points.txt[console_scripts] nosetests = nose:run_exit [distutils.commands] nosetests = nose.commands:nosetests PK žC8“×2EGG-INFO/dependency_links.txt PK žC8»ºq]¦¦EGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: nose Version: 0.9.3 Summary: A unittest extension offering automatic test suite discovery and easy test authoring Home-page: http://somethingaboutorange.com/mrl/projects/nose/ Author: Jason Pellerin Author-email: jpellerin+nose@gmail.com License: GNU LGPL Download-URL: http://somethingaboutorange.com/mrl/projects/nose/nose-0.9.3.tar.gz Description: nose extends the test loading and running features of unittest, making it easier to write, find and run tests. By default, nose will run tests in files or directories under the current working directory whose names include "test" or "Test" at a word boundary (like "test_this" or "functional_test" or "TestClass" but not "libtest"). Test output is similar to that of unittest, but also includes captured stdout output from failing tests, for easy print-style debugging. These features, and many more, are customizable through the use of plugins. Plugins included with nose provide support for doctest, code coverage and profiling, and flexible attribute-based test selection. More information about writing plugins may be found on the wiki, here: http://code.google.com/p/python-nose/wiki/WritingPlugins. If you have recently reported a bug marked as fixed, or have a craving for the very latest, you may want the development version instead: http://python-nose.googlecode.com/svn/trunk#egg=nose-dev Keywords: test unittest doctest automatic discovery Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Testing PK žC8‘y-EGG-INFO/top_level.txtnose PK¤žC8“×2EGG-INFO/not-zip-safe PK£žC8Ûè;; ¤nose/case.pycPK£žC8`8¨}}¤fnose/importer.pycPK••6`¾[íÀ9À9¤-nose/loader.pyPK••6³–pœ8œ8¤þfnose/__init__.pyPK••6 ]Ø9¤ÈŸnose/inspector.pyPK¤žC8niá á ¤»nose/config.pycPK••6ÇD={ ¤!Énose/exc.pyPK••6Z*Ѝ¨W¨W ¤XÊnose/core.pyPK£žC8°üÛûÿ]ÿ] ¤*"nose/core.pycPK••6£9ÇÉii ¤T€nose/util.pyPK¤žC8“êÏ2ÿDÿD¤çžnose/selector.pycPK••6\©&kk¤änose/importer.pyPK¤žC8ÝA·^^¤®õnose/commands.pycPK£žC8÷œ»Ä..¤; nose/suite.pycPK¤žC8­¯{ëSS¤ô8nose/tools.pycPK••6LM‡²² ¤sSnose/case.pyPK••6fOÈÒÒ ¤Ofnose/suite.pyPK¤žC8Ç©6 ""¤L„nose/twistedtools.pycPK••6Y·yáᤡ›nose/result.pyPK••6ÿ<£‹ÏÏ ¤®»nose/tools.pyPK£žC8Áçèúú¤¨Ênose/inspector.pycPK••6`ë#%55¤Òånose/config.pyPK¢žC8>g‡i<<¤3înose/loader.pycPK••6ÞÊQXžž ¤u*nose/proxy.pyPK£žC85ßòô¯¯ ¤>9nose/util.pycPK£žC8È&\G<G<¤Ynose/__init__.pycPK£žC8Mh¥àCC ¤Ž•nose/exc.pycPK¤žC8"9x44¤û˜nose/proxy.pycPK¤žC8„¢!¹22¤[´nose/result.pycPK••6-Lûû¤çnose/commands.pyPK••6¡ìÇ6$$¤>önose/twistedtools.pyPK••6×à¨é;;¤”nose/selector.pyPK••6Bôa>””¤ÜCnose/plugins/__init__.pyPK£žC8j²zAA¤¦`nose/plugins/doctests.pycPK£žC8› sÂÝGÝG¤}nose/plugins/base.pycPK••6Ÿi.´¤¤¤.Ånose/plugins/doctests.pyPK••6,ÒÄŽŽ¤Þnose/plugins/missed.pyPK••6¢BxÍß6ß6¤Êänose/plugins/base.pyPK••6*K­o55¤Ûnose/plugins/isolate.pyPK£žC8Lÿ÷ ÷ ¤E$nose/plugins/missed.pycPK¤žC8ôÛ9œ‘‘¤q.nose/plugins/attrib.pycPK¤žC8Ô ïï¤7Mnose/plugins/cover.pycPK••6'äD Î Î ¤Zhnose/plugins/prof.pyPK••6.‰Gª¤Zvnose/plugins/attrib.pyPK••6ìÀº¯¯¤¢’nose/plugins/cover.pyPK£žC87ûÝ--¤„«nose/plugins/__init__.pycPK¤žC8ÊûŒŒŒ¤èÉnose/plugins/prof.pycPK£žC8ÜÞQµ µ ¤§Ýnose/plugins/isolate.pycPK žC8ÖTJ´ë뤒éEGG-INFO/SOURCES.txtPK žC8¬ƒÖÝgg¤¯òEGG-INFO/entry_points.txtPK žC8“×2¤MóEGG-INFO/dependency_links.txtPK žC8»ºq]¦¦¤‰óEGG-INFO/PKG-INFOPK žC8‘y-¤^ûEGG-INFO/top_level.txtPK¤žC8“×2¤—ûEGG-INFO/not-zip-safePK66| Ëû