Exemple #1
0
def PageTestSuite(storydir, package=None, setUp=setUpGlobs):
    """Create a suite of page tests for files found in storydir.

    :param storydir: the directory containing the page tests.
    :param package: the package to resolve storydir relative to.  Defaults
        to the caller's package.

    Each file is added as a separate DocFileTest.
    """
    # we need to normalise the package name here, because it
    # involves checking the parent stack frame.  Otherwise the
    # files would be looked up relative to this module.
    package = doctest._normalize_module(package)
    abs_storydir = doctest._module_relative_path(package, storydir)

    filenames = set(filename for filename in os.listdir(abs_storydir)
                    if filename.lower().endswith('.txt'))

    suite = unittest.TestSuite()
    # Add tests to the suite individually.
    if filenames:
        checker = doctest.OutputChecker()
        paths = [os.path.join(storydir, filename) for filename in filenames]
        suite.addTest(
            LayeredDocFileSuite(paths=paths,
                                package=package,
                                checker=checker,
                                stdout_logging=False,
                                layer=PageTestLayer,
                                setUp=setUp))
    return suite
Exemple #2
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxContentXMLRPCLayer

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()
        root = functional.getRootFolder()
        setSite(root)
        setattr(root, 'title', 'Test Site')

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #3
0
def FunctionalDocFileSuite(*paths, **kw):
    globs = kw.setdefault('globs', {})
    globs['sync'] = functional.sync
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        root['principalannotation'] = PrincipalAnnotationUtility()
        root.getSiteManager().registerUtility(
            root['principalannotation'], IPrincipalAnnotationUtility)

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old
                             | doctest.ELLIPSIS
                             | doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = zojaxPreferences
    return suite
Exemple #4
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxBloggerLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        newInteraction()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()
        sm.getUtility(INameChooserConfiglet).short_url_enabled = True

        # IIntIds
        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)
        root['ids'].register(root)

        # catalog
        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        # space
        space = ContentSpace(title=u'Space')
        event.notify(ObjectCreatedEvent(space))
        root['space'] = space

        # people
        people = PersonalSpaceManager(title=u'People')
        event.notify(ObjectCreatedEvent(people))
        root['people'] = people
        sm.registerUtility(root['people'], IPersonalSpaceManager)

        endInteraction()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #5
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxErrorLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #6
0
    def test_file(self, filename):

        import doctest
        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir)+1:]
        module = rel_name.replace(os.sep, '.')[:-3]
        setup_pprint()
        try:
            module = doctest._normalize_module(module)
            tests = doctest.DocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests.sort()
        tests = [test for test in tests if len(test.examples) > 0]
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = doctest.DocTestRunner(optionflags=doctest.ELLIPSIS | \
                    doctest.NORMALIZE_WHITESPACE)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
Exemple #7
0
def PageTestSuite(storydir, package=None, setUp=setUpGlobs):
    """Create a suite of page tests for files found in storydir.

    :param storydir: the directory containing the page tests.
    :param package: the package to resolve storydir relative to.  Defaults
        to the caller's package.

    Each file is added as a separate DocFileTest.
    """
    # we need to normalise the package name here, because it
    # involves checking the parent stack frame.  Otherwise the
    # files would be looked up relative to this module.
    package = doctest._normalize_module(package)
    abs_storydir = doctest._module_relative_path(package, storydir)

    filenames = set(filename for filename in os.listdir(abs_storydir) if filename.lower().endswith(".txt"))

    suite = unittest.TestSuite()
    # Add tests to the suite individually.
    if filenames:
        checker = doctest.OutputChecker()
        paths = [os.path.join(storydir, filename) for filename in filenames]
        suite.addTest(
            LayeredDocFileSuite(
                paths=paths, package=package, checker=checker, stdout_logging=False, layer=PageTestLayer, setUp=setUp
            )
        )
    return suite
def FunctionalDocFileSuite(*paths, **kw):
    """Build a functional test suite from a text file."""
    kw['package'] = doctest._normalize_module(kw.get('package'))
    _prepare_doctest_keywords(kw)
    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = Functional
    return suite
Exemple #9
0
def build_test_suite(base_dir,
                     special_tests={},
                     layer=None,
                     setUp=setUp,
                     tearDown=tearDown,
                     pageTestsSetUp=None):
    """Build a test suite from a directory containing test files.

    The parent's 'stories' subdirectory will be checked for pagetests and
    the parent's 'doc' subdirectory will be checked for doctests.

    :param base_dir: The tests subdirectory that.

    :param special_tests: A dict mapping filenames to TestSuite
        objects. These files need special treatment (for instance, they
        should be run in a different layer, or they need custom
        setup/teardown). The given TestSuite object will be used for that
        file, rather than a new one generated.

    :param layer: The layer in which to run the tests.
    """
    from lp.testing.layers import DatabaseFunctionalLayer
    from lp.testing.pages import (
        PageTestSuite,
        setUpGlobs,
    )
    if layer is None:
        layer = DatabaseFunctionalLayer
    if pageTestsSetUp is None:
        pageTestsSetUp = setUpGlobs

    suite = unittest.TestSuite()

    # Tests are run relative to the calling module, not this module.
    package = doctest._normalize_module(None)

    # Add the pagetests.
    stories_dir = os.path.join(os.path.pardir, 'stories')
    stories_path = os.path.join(base_dir, stories_dir)
    if os.path.exists(stories_path):
        suite.addTest(PageTestSuite(stories_dir, package,
                                    setUp=pageTestsSetUp))
        for story_entry in scandir.scandir(stories_path):
            if not story_entry.is_dir():
                continue
            story_path = os.path.join(stories_dir, story_entry.name)
            if story_path in special_tests:
                continue
            suite.addTest(
                PageTestSuite(story_path, package, setUp=pageTestsSetUp))

    # Add the special doctests.
    for key, special_suite in sorted(special_tests.items()):
        suite.addTest(special_suite)

    tests_path = os.path.join(os.path.pardir, 'doc')
    suite.addTest(
        build_doctest_suite(base_dir, tests_path, special_tests, layer, setUp,
                            tearDown, package))
    return suite
Exemple #10
0
def FunctionalDocFileSuite(*paths, **kw):
    # use our custom HTTPCaller and layer
    kw['package'] = doctest._normalize_module(kw.get('package'))
    _prepare_doctest_keywords(kw)
    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = JSONRPCTestingLayer
    return suite
Exemple #11
0
def FunctionalDocFileSuite(*paths, **kw):
    globs = kw.setdefault('globs', {})
    globs['sync'] = functional.sync
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        root['intid'] = IntIds()
        component.provideUtility(root['intid'], IIntIds)

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old
                             | doctest.ELLIPSIS
                             | doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = zojaxSkinTool
    return suite
Exemple #12
0
    def test_file(self, filename):

        import doctest
        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir)+1:]
        module = rel_name.replace(os.sep, '.')[:-3]
        setup_pprint()
        try:
            module = doctest._normalize_module(module)
            tests = doctest.DocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests.sort()
        tests = [test for test in tests if len(test.examples) > 0]
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = doctest.DocTestRunner(optionflags=doctest.ELLIPSIS | \
                    doctest.NORMALIZE_WHITESPACE)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
Exemple #13
0
def build_doctest_suite(
    base_dir, tests_path, special_tests={}, layer=None, setUp=setUp, tearDown=tearDown, package=None
):
    """Build the doc test suite."""
    from lp.testing.layers import DatabaseFunctionalLayer

    if layer is None:
        layer = DatabaseFunctionalLayer
    suite = unittest.TestSuite()
    # Tests are run relative to the calling module, not this module.
    if package is None:
        package = doctest._normalize_module(None)
    testsdir = os.path.abspath(os.path.normpath(os.path.join(base_dir, tests_path)))

    if os.path.exists(testsdir):
        # Add doctests using default setup/teardown.
        filenames = [
            filename
            for filename in os.listdir(testsdir)
            if (filename.endswith(".txt") and filename not in special_tests)
        ]
        # Sort the list to give a predictable order.
        filenames.sort()
        for filename in filenames:
            path = os.path.join(tests_path, filename)
            one_test = LayeredDocFileSuite(
                path, package=package, setUp=setUp, tearDown=tearDown, layer=layer, stdout_logging_level=logging.WARNING
            )
            suite.addTest(one_test)
    return suite
Exemple #14
0
    def _patched_DocFileTest(path,
                             module_relative=True,
                             package=None,
                             globs=None,
                             parser=DocTestParser(),
                             **options):
        if globs is None:
            globs = {}

        if package and not module_relative:
            raise ValueError("Package may only be specified for module-"
                             "relative paths.")

        # Relativize the path.
        if module_relative:
            package = _normalize_module(package)
            path = _module_relative_path(package, path)

        # Find the file and read it.
        name = os.path.basename(path)
        doc = open(path, 'U').read()

        # Convert it to a test, and wrap it in a DocFileCase.
        test = parser.get_doctest(doc, globs, name, path, 0)
        return DocFileCase(test, **options)
Exemple #15
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxQuickLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        newInteraction()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        # IIntIds
        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)
        root['ids'].register(root)

        # catalog
        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        # setup default role
        roles = sm.getUtility(IPortalRoles)
        if 'site.member' not in roles:
            role = PortalRole(title = u'Site Member')
            event.notify(ObjectCreatedEvent(role))

            roles['site.member'] = role
            roleId = role.id
            sm.getUtility(IDefaultPortalRole).roles = [role.id]

        endInteraction()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        #old = doctest.set_unittest_reportflags(0)
        #doctest.set_unittest_reportflags(old)
        #kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)
        kw['optionflags'] = (doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #16
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxContentActionsLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)
        setUpCache()

        sm = root.getSiteManager()

        # IIntIds
        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)
        root['ids'].register(root)

        # catalog
        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        # people
        root['people'] = PersonalSpaceManager()
        sm.registerUtility(root['people'], IPersonalSpaceManager)

        # space
        space = ContentSpace(title=u'Space')
        event.notify(ObjectCreatedEvent(space))
        root['space'] = space
        interface.directlyProvides(root['space'], IDoNotCacheActionsPortlet)

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        tearDownCache()
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxPersistentFieldsLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)

        # IIntIds
        root['ids'] = IntIds()
        root.getSiteManager().registerUtility(root['ids'], IIntIds)

        # HomeFolderManager
        manager = PersonalSpaceManager(title=u'People')
        event.notify(ObjectCreatedEvent(manager))

        root['people'] = manager
        root.getSiteManager().registerUtility(root['people'], IPersonalSpaceManager)

        principal = root.getSiteManager().getUtility(
            IAuthentication).getPrincipal('zope.user')

        manager.assignPersonalSpace(principal)

        # profiles category
        configlet = component.getUtility(IProfilesCategory)
        configlet.fieldCategories = [u'Category1', u'Category2']


    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
def FunctionalDocFileSuite(*paths, **kw):
    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)

        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        authconfig = sm.getUtility(IAuthenticationConfiglet)
        authconfig.installUtility()

        auth = sm.getUtility(IAuthentication)
        auth._cache = False
        auth.prefix = u'test.'
        auth.authenticatorPlugins = tuple(auth.authenticatorPlugins) + ('principal.users',)

        authfactory = sm.getUtility(IAuthenticatorPluginFactory, name='principal.users')
        authfactory.install()

        if kwsetUp is not None:
            kwsetUp(test)

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        if kwtearDown is not None:
            kwtearDown(test)
        functional.FunctionalTestSetup().tearDown()
    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old
                             | doctest.ELLIPSIS
                             | doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = zojaxPrincipalManagement
    return suite
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxContentDiscussionLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        # IIntIds
        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)
        root['ids'].register(root)

        # catalog
        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        # personal space manager
        root['people'] = PersonalSpaceManager()
        sm.registerUtility(root['people'], IPersonalSpaceManager)

        # default content
        content = Content()
        event.notify(ObjectCreatedEvent(content))
        IOwnership(content).ownerId = 'zope.user'
        root['content'] = content

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        #old = doctest.set_unittest_reportflags(0)
        #doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #20
0
    def test_file(self, filename):
        clear_cache()

        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir)+1:]
        module = rel_name.replace(os.sep, '.')[:-3]
        setup_pprint()
        try:
            module = pdoctest._normalize_module(module)
            tests = SymPyDocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests = [test for test in tests if len(test.examples) > 0]
        # By default (except for python 2.4 in which it was broken) tests
        # are sorted by alphabetical order by function name. We sort by line number
        # so one can edit the file sequentially from bottom to top...HOWEVER
        # if there are decorated functions, their line numbers will be too large
        # and for now one must just search for these by text and function name.
        tests.sort(key=lambda x: -x.lineno)

        if not tests:
            return
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | \
                    pdoctest.NORMALIZE_WHITESPACE)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            # If the testing is normal, the doctests get importing magic to
            # provide the global namespace. If not normal (the default) then
            # then must run on their own; all imports must be explicit within
            # a function's docstring. Once imported that import will be
            # available to the rest of the tests in a given function's
            # docstring (unless clear_globs=True below).
            if not self._normal:
                test.globs = {}
                # if this is uncommented then all the test would get is what
                # comes by default with a "from sympy import *"
                #exec('from sympy import *') in test.globs
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
Exemple #21
0
    def _patched_testfile(
        filename,
        module_relative=True,
        name=None,
        package=None,
        globs=None,
        verbose=None,
        report=True,
        optionflags=0,
        extraglobs=None,
        raise_on_error=False,
        parser=DocTestParser(),
    ):
        global master

        if package and not module_relative:
            raise ValueError("Package may only be specified for module-" "relative paths.")

        # Relativize the path
        if module_relative:
            package = _normalize_module(package)
            filename = _module_relative_path(package, filename)

        # If no name was given, then use the file's name.
        if name is None:
            name = os.path.basename(filename)

        # Assemble the globals.
        if globs is None:
            globs = {}
        else:
            globs = globs.copy()
        if extraglobs is not None:
            globs.update(extraglobs)

        if raise_on_error:
            runner = DebugRunner(verbose=verbose, optionflags=optionflags)
        else:
            runner = DocTestRunner(verbose=verbose, optionflags=optionflags)

        # Read the file, convert it to a test, and run it.
        s = open(filename, "U").read()
        test = parser.get_doctest(s, globs, name, filename, 0)
        runner.run(test)

        if report:
            runner.summarize()

        if master is None:
            master = runner
        else:
            master.merge(runner)

        return runner.failures, runner.tries
Exemple #22
0
def FunctionalDocFileSuite(*paths, **kw):
    try:
        layer = kw['layer']
    except KeyError:
        layer = Layer
    else:
        del kw['layer']
    kw['package'] = doctest._normalize_module(kw.get('package'))
    test = zope.app.testing.functional.FunctionalDocFileSuite(
        *paths, **kw)
    test.layer = layer
    return test
Exemple #23
0
    def test_file(self, filename):

        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir) + 1:]
        module = rel_name.replace(os.sep, '.')[:-3]
        setup_pprint()
        try:
            module = pdoctest._normalize_module(module)
            tests = SymPyDocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests = [test for test in tests if len(test.examples) > 0]
        # By default (except for python 2.4 in which it was broken) tests
        # are sorted by alphabetical order by function name. We sort by line number
        # so one can edit the file sequentially from bottom to top...HOWEVER
        # if there are decorated functions, their line numbers will be too large
        # and for now one must just search for these by text and function name.
        tests.sort(key=lambda x: -x.lineno)

        if not tests:
            return
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | \
                    pdoctest.NORMALIZE_WHITESPACE)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            # If the testing is normal, the doctests get importing magic to
            # provide the global namespace. If not normal (the default) then
            # then must run on their own; all imports must be explicit within
            # a function's docstring. Once imported that import will be
            # available to the rest of the tests in a given function's
            # docstring (unless clear_globs=True below).
            if not self._normal:
                test.globs = {}
                # if this is uncommented then all the test would get is what
                # comes by default with a "from sympy import *"
                #exec('from sympy import *') in test.globs
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
Exemple #24
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxFormulatorLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        portal = Portal()
        event.notify(ObjectCreatedEvent(portal))
        root['portal'] = portal
        sm = LocalSiteManager(portal)
        portal.setSiteManager(sm)
        setSite(portal)
        sm = portal.getSiteManager()
        portal['ids'] = IntIds()
        sm.registerUtility(portal['ids'], IIntIds)

        portal['catalog'] = Catalog()
        sm.registerUtility(portal['catalog'], ICatalog)

        authconfiglet = sm.getUtility(IAuthenticationConfiglet)
        authconfiglet.installUtility()

        sm.getUtility(IAuthentication)._caching = False




    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #25
0
    def _patched_testfile(filename,
                          module_relative=True,
                          name=None,
                          package=None,
                          globs=None,
                          verbose=None,
                          report=True,
                          optionflags=0,
                          extraglobs=None,
                          raise_on_error=False,
                          parser=DocTestParser()):
        global master

        if package and not module_relative:
            raise ValueError("Package may only be specified for module-"
                             "relative paths.")

        # Relativize the path
        if module_relative:
            package = _normalize_module(package)
            filename = _module_relative_path(package, filename)

        # If no name was given, then use the file's name.
        if name is None:
            name = os.path.basename(filename)

        # Assemble the globals.
        if globs is None:
            globs = {}
        else:
            globs = globs.copy()
        if extraglobs is not None:
            globs.update(extraglobs)

        if raise_on_error:
            runner = DebugRunner(verbose=verbose, optionflags=optionflags)
        else:
            runner = DocTestRunner(verbose=verbose, optionflags=optionflags)

        # Read the file, convert it to a test, and run it.
        s = open(filename, 'U').read()
        test = parser.get_doctest(s, globs, name, filename, 0)
        runner.run(test)

        if report:
            runner.summarize()

        if master is None:
            master = runner
        else:
            master.merge(runner)

        return runner.failures, runner.tries
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxContentUrlmapperLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)

        # default content
        content = Content1()
        event.notify(ObjectCreatedEvent(content))
        root['content11'] = content

        content = Content1()
        event.notify(ObjectCreatedEvent(content))
        root['content12'] = content

        content = Content2()
        event.notify(ObjectCreatedEvent(content))
        root['content21'] = content

        content = Content2()
        event.notify(ObjectCreatedEvent(content))
        root['content22'] = content


    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #27
0
def _load_testfile(filename):
    # Copied from Python 3.6 doctest._load_testfile to ensure utf-8
    # encoding on Python 2.
    package = doctest._normalize_module(None, 3)
    if getattr(package, '__loader__', None) is not None:
        if hasattr(package.__loader__, 'get_data'):
            file_contents = package.__loader__.get_data(filename)
            file_contents = file_contents.decode("utf-8")
            # get_data() opens files as 'rb', so one must do the equivalent
            # conversion as universal newlines would do.
            return file_contents.replace(os.linesep, '\n'), filename
    with codecs.open(filename, encoding="utf-8") as f:
        return f.read(), filename
Exemple #28
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxPersonalContentLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        root = functional.getRootFolder()
        setSite(root)

        # IIntIds
        root['ids'] = IntIds()
        root.getSiteManager().registerUtility(root['ids'], IIntIds)

        # catalog
        root['catalog'] = Catalog()
        root.getSiteManager().registerUtility(root['catalog'], ICatalog)

        # home folder manager
        manager = PersonalSpaceManager(title=u'People')
        event.notify(ObjectCreatedEvent(manager))

        root['people'] = manager
        root.getSiteManager().registerUtility(root['people'], IPersonalSpaceManager)


    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #29
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = hubspot

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        newInteraction()

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        # IIntIds
        root['ids'] = IntIds()
        sm.registerUtility(root['ids'], IIntIds)
        root['ids'].register(root)

        # space
        space = ContentSpace(title=u'Space')
        event.notify(ObjectCreatedEvent(space))
        root['space'] = space

        endInteraction()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old|doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #30
0
 def _patched_load_testfile(filename, package, module_relative, encoding=None):
     if module_relative:
         package = doctest._normalize_module(package, 3)
         filename = doctest._module_relative_path(package, filename)
         if hasattr(package, "__loader__"):
             if hasattr(package.__loader__, "get_data"):
                 file_contents = package.__loader__.get_data(filename)
                 if encoding is not None:  # Python 3
                     file_contents = file_contents.decode(encoding)
                 # get_data() opens files as 'rb', so one must do the equivalent
                 # conversion as universal newlines would do.
                 return file_contents.replace(os.linesep, "\n"), filename
     if encoding:  # Python 3:
         return open(filename, encoding=encoding).read(), filename
     else:
         return open(filename, "U").read(), filename
Exemple #31
0
def build_test_suite(base_dir, special_tests={}, layer=None, setUp=setUp, tearDown=tearDown):
    """Build a test suite from a directory containing test files.

    The parent's 'stories' subdirectory will be checked for pagetests and
    the parent's 'doc' subdirectory will be checked for doctests.

    :param base_dir: The tests subdirectory that.

    :param special_tests: A dict mapping filenames to TestSuite
        objects. These files need special treatment (for instance, they
        should be run in a different layer, or they need custom
        setup/teardown). The given TestSuite object will be used for that
        file, rather than a new one generated.

    :param layer: The layer in which to run the tests.
    """
    from lp.testing.layers import DatabaseFunctionalLayer
    from lp.testing.pages import PageTestSuite

    if layer is None:
        layer = DatabaseFunctionalLayer

    suite = unittest.TestSuite()

    # Tests are run relative to the calling module, not this module.
    package = doctest._normalize_module(None)

    # Add the pagetests.
    stories_dir = os.path.join(os.path.pardir, "stories")
    stories_path = os.path.join(base_dir, stories_dir)
    if os.path.exists(stories_path):
        suite.addTest(PageTestSuite(stories_dir, package))
        for story_dir in os.listdir(stories_path):
            full_story_dir = os.path.join(stories_path, story_dir)
            if not os.path.isdir(full_story_dir):
                continue
            story_path = os.path.join(stories_dir, story_dir)
            suite.addTest(PageTestSuite(story_path, package))

    # Add the special doctests.
    for key in sorted(special_tests):
        special_suite = special_tests[key]
        suite.addTest(special_suite)

    tests_path = os.path.join(os.path.pardir, "doc")
    suite.addTest(build_doctest_suite(base_dir, tests_path, special_tests, layer, setUp, tearDown, package))
    return suite
Exemple #32
0
def collect_ftests(package=None, level=None, layer=None, filenames=None,
                   extra_globs=None):
    package = doctest._normalize_module(package)
    extra_globs = extra_globs or {}
    extra_globs.update({'analyze': analyze,
                        'Browser': TestBrowser})
    def make_suite(filename, package=None):
        optionflags = (doctest.ELLIPSIS | doctest.REPORT_NDIFF |
                       doctest.NORMALIZE_WHITESPACE |
                       doctest.REPORT_ONLY_FIRST_FAILURE)
        suite = FunctionalDocFileSuite(filename, package=package,
                                       optionflags=optionflags,
                                       globs=extra_globs)
        return suite
    return collect_txt_ftests(package=package, level=level,
                              layer=layer, filenames=filenames,
                              suite_factory=make_suite)
Exemple #33
0
    def test_file(self, filename):
        def setup_pprint():
            from sympy import pprint_use_unicode

            # force pprint to be in ascii mode in doctests
            pprint_use_unicode(False)

            # hook our nice, hash-stable strprinter
            from sympy.interactive import init_printing
            from sympy.printing import sstrrepr

            init_printing(sstrrepr)

        import doctest
        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir) + 1 :]
        module = rel_name.replace("/", ".")[:-3]
        setup_pprint()
        try:
            module = doctest._normalize_module(module)
            tests = doctest.DocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests.sort()
        tests = [test for test in tests if len(test.examples) > 0]
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = doctest.DocTestRunner()
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
def FunctionalDocFileSuite(*paths, **kw):
    layer = zojaxPersonalPhotoalbumLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))
    global oldMethod
    oldMethod = utils.checkPermissionForPrincipal.func_code
    utils.checkPermissionForPrincipal.func_code = checkPermissionForPrincipal.func_code

    kwsetUp = kw.get('setUp')

    def setUp(test):
        functional.FunctionalTestSetup().setUp()
        newInteraction()
        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()
        auth = sm.getUtility(IAuthentication)
        p = auth.getPrincipal('zope.mgr')
        setattr(root, 'principal', p)
        setattr(root, 'owner', p)
        endInteraction()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')

    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old | doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #35
0
def RobotTestSuite(*paths, **kw):
    """Build up a test suite similarly to doctest.DocFileSuite
    """
    suite = unittest.TestSuite()
    if 'ROBOTSUITE_LEVEL' in os.environ:
        try:
            suite.level = int(os.environ.get('ROBOTSUITE_LEVEL', 1))
        except ValueError:
            pass
    if kw.get('module_relative', True):
        kw['package'] = doctest._normalize_module(kw.get('package'))

    variables = get_robot_variables()

    for path in paths:
        filename = doctest._module_relative_path(kw['package'], path)
        robot_suite = robot_parsing.TestData(source=filename)

        # Split the robot suite into separate test cases

        outputdir = []

        def recurs(child_suite):
            suite_base = os.path.basename(child_suite.source)
            suite_dir = os.path.splitext(suite_base)[0]
            outputdir.append(suite_dir)
            for test in child_suite.testcase_table.tests:
                test_dir = normalize(test.name)
                outputdir.append(test_dir)
                suite.addTest(
                    RobotTestCase(path,
                                  name=test.name,
                                  tags=test.tags.value,
                                  variables=variables,
                                  source=child_suite.source,
                                  outputdir='/'.join(outputdir),
                                  **kw))
                outputdir.pop()
            for grandchild in getattr(child_suite, 'children', []):
                recurs(grandchild)
            outputdir.pop()

        recurs(robot_suite)

    return suite
Exemple #36
0
def FunctionalDocFileSuite(*paths, **kw):
    globs = kw.setdefault('globs', {})
    globs['sync'] = sync
    globs['getRootFolder'] = getRootFolder

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        FunctionalTestSetup().setUp()

        root = getRootFolder()
        setSite(root)

        root['ids'] = IntIds()
        root.getSiteManager().registerUtility(root['ids'], IIntIds)

        root['catalog'] = Catalog()
        root.getSiteManager().registerUtility(root['catalog'], ICatalog)


    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old
                             | doctest.ELLIPSIS
                             | doctest.NORMALIZE_WHITESPACE)

    layer = kw.get('layer', Functional)
    if 'layer' in kw:
        del kw['layer']

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #37
0
    def test_file(self, filename):
        def setup_pprint():
            from sympy import pprint_use_unicode
            # force pprint to be in ascii mode in doctests
            pprint_use_unicode(False)

            # hook our nice, hash-stable strprinter
            from sympy.interactive import init_printing
            from sympy.printing import sstrrepr
            init_printing(sstrrepr)

        import doctest
        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir) + 1:]
        module = os.path.splitext(rel_name.replace('/', '.'))[0]
        #setup_pprint()
        try:
            module = doctest._normalize_module(module)
            tests = doctest.DocTestFinder().find(module)
        except:
            self._reporter.import_error(filename, sys.exc_info())
            return

        tests.sort()
        tests = [test for test in tests if len(test.examples) > 0]
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = doctest.DocTestRunner(optionflags=doctest.ELLIPSIS | \
                    doctest.NORMALIZE_WHITESPACE)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
Exemple #38
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = portalTabs

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')
    def setUp(test):
        functional.FunctionalTestSetup().setUp()
        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        # IIntIds
        root['intids'] = IntIds()
        sm.registerUtility(root['intids'], IIntIds)
        root['intids'].register(root)

        # default content
        content = Content(u'Content', u'Some Content')
        event.notify(ObjectCreatedEvent(content))
        IOwnership(content).ownerId = 'zope.user'
        root['content'] = content


    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')
    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        kw['optionflags'] = (doctest.ELLIPSIS|doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #39
0
 def _patched_load_testfile(filename,
                            package,
                            module_relative,
                            encoding=None):
     if module_relative:
         package = doctest._normalize_module(package, 3)
         filename = doctest._module_relative_path(package, filename)
         if hasattr(package, '__loader__'):
             if hasattr(package.__loader__, 'get_data'):
                 file_contents = package.__loader__.get_data(filename)
                 if encoding is not None:  # Python 3
                     file_contents = file_contents.decode(encoding)
                 # get_data() opens files as 'rb', so one must do the equivalent
                 # conversion as universal newlines would do.
                 return file_contents.replace(os.linesep, '\n'), filename
     if encoding:  # Python 3:
         return open(filename, encoding=encoding).read(), filename
     else:
         return open(filename, 'U').read(), filename
Exemple #40
0
    def _patched_DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), **options):
        if globs is None:
            globs = {}

        if package and not module_relative:
            raise ValueError("Package may only be specified for module-" "relative paths.")

        # Relativize the path.
        if module_relative:
            package = _normalize_module(package)
            path = _module_relative_path(package, path)

        # Find the file and read it.
        name = os.path.basename(path)
        doc = open(path, "U").read()

        # Convert it to a test, and wrap it in a DocFileCase.
        test = parser.get_doctest(doc, globs, name, path, 0)
        return DocFileCase(test, **options)
Exemple #41
0
def collect_ftests(package=None, level=None,
                   layer=ututi.tests.UtutiLayer,
                   filenames=None, exclude=None,
                   setUp=ftest_setUp, tearDown=ututi.tests.tearDown):
    """Collect all functional doctest files in a given package.

    If `package` is None, looks up the call stack for the right module.

    Returns a unittest.TestSuite.
    """
    package = doctest._normalize_module(package)
    testdir = os.path.dirname(package.__file__)
    if filenames is None:
        filenames = [fn for fn in os.listdir(testdir)
                     if fn.endswith('.txt') and not fn.startswith('.')]
    if exclude is not None:
        for fn in exclude:
            filenames.remove(fn)
    suites = []
    checker = RENormalizing([
            (re.compile('[0-9]*[.][0-9]* seconds'), '0.000 seconds'),
            (re.compile('[0-9]* second[s]* ago'), '0 seconds ago'),
            ])
    optionflags = (doctest.ELLIPSIS | doctest.REPORT_NDIFF |
                   doctest.NORMALIZE_WHITESPACE |
                   doctest.REPORT_ONLY_FIRST_FAILURE)
    for n, filename in enumerate(filenames):
        suite = doctest.DocFileSuite(filename,
                                     package=package,
                                     optionflags=optionflags,
                                     checker=checker,
                                     setUp=setUp,
                                     tearDown=tearDown)

        if isinstance(layer, list):
            suite.layer = layer[n % len(layer)]
        else:
            suite.layer = layer

        if level is not None:
            suite.level = level
        suites.append(suite)
    return unittest.TestSuite(suites)
def build_doctest_suite(base_dir,
                        tests_path,
                        special_tests={},
                        layer=None,
                        setUp=setUp,
                        tearDown=tearDown,
                        package=None):
    """Build the doc test suite."""
    from lp.testing.layers import DatabaseFunctionalLayer
    if layer is None:
        layer = DatabaseFunctionalLayer
    suite = unittest.TestSuite()
    # Tests are run relative to the calling module, not this module.
    if package is None:
        package = doctest._normalize_module(None)
    testsdir = os.path.abspath(
        os.path.normpath(os.path.join(base_dir, tests_path)))

    if os.path.exists(testsdir):
        # Add doctests using default setup/teardown.
        filenames = [
            filename for filename in os.listdir(testsdir)
            if (filename.endswith('.txt') and filename not in special_tests)
        ]
        # Sort the list to give a predictable order.
        filenames.sort()
        for filename in filenames:
            path = os.path.join(tests_path, filename)
            one_test = LayeredDocFileSuite(
                path,
                package=package,
                setUp=setUp,
                tearDown=tearDown,
                layer=layer,
                stdout_logging_level=logging.WARNING)
            suite.addTest(one_test)
    return suite
Exemple #43
0
def FunctionalDocFileSuite(*paths, **kw):
    layer = AcknowledgementLayer

    globs = kw.setdefault('globs', {})
    globs['http'] = functional.HTTPCaller()
    globs['getRootFolder'] = functional.getRootFolder
    globs['sync'] = functional.sync

    kw['package'] = doctest._normalize_module(kw.get('package'))

    kwsetUp = kw.get('setUp')

    def setUp(test):
        functional.FunctionalTestSetup().setUp()

        newInteraction()

        def fake_utcnow(self):
            return datetime.datetime(2015, 7, 30, 8, 0, 0)

        curse(datetime.datetime, 'utcnow', classmethod(fake_utcnow))

        root = functional.getRootFolder()
        setSite(root)
        sm = root.getSiteManager()

        # IIntIds
        root['intids'] = IntIds()
        sm.registerUtility(root['intids'], IIntIds)
        root['intids'].register(root)

        # catalog
        root['catalog'] = Catalog()
        sm.registerUtility(root['catalog'], ICatalog)

        # PluggableAuthentication
        pau = PluggableAuthentication(u'')
        event.notify(ObjectCreatedEvent(pau))
        sm[u'auth'] = pau
        sm.registerUtility(pau, IAuthentication)

        # Credentials Plugin
        defaultCreds.install()
        defaultCreds.activate()

        # people
        people = PersonalSpaceManager(title=u'People')
        event.notify(ObjectCreatedEvent(people))
        root['people'] = people
        sm.registerUtility(root['people'], IPersonalSpaceManager)

        user = sm.getUtility(IAuthentication).getPrincipal('zope.mgr')
        people.assignPersonalSpace(user)

        user = sm.getUtility(IAuthentication).getPrincipal('zope.user')
        people.assignPersonalSpace(user)

        # default content
        content = Content(u'Content1', u'Some Content1')
        event.notify(ObjectCreatedEvent(content))
        IOwnership(content).ownerId = 'zope.user'
        root['content1'] = content

        content = Content(u'Content2', u'Some Content2')
        event.notify(ObjectCreatedEvent(content))
        IOwnership(content).ownerId = 'zope.user'
        root['content2'] = content

        endInteraction()

    kw['setUp'] = setUp

    kwtearDown = kw.get('tearDown')

    def tearDown(test):
        setSite(None)
        functional.FunctionalTestSetup().tearDown()
        # datetime_patcher.stop()

    kw['tearDown'] = tearDown

    if 'optionflags' not in kw:
        old = doctest.set_unittest_reportflags(0)
        doctest.set_unittest_reportflags(old)
        kw['optionflags'] = (old | doctest.ELLIPSIS
                             | doctest.NORMALIZE_WHITESPACE)

    suite = doctest.DocFileSuite(*paths, **kw)
    suite.layer = layer
    return suite
Exemple #44
0
    def test_file(self, filename):
        clear_cache()

        import unittest
        from StringIO import StringIO

        rel_name = filename[len(self._root_dir)+1:]
        dirname, file = os.path.split(filename)
        module = rel_name.replace(os.sep, '.')[:-3]

        if rel_name.startswith("examples"):
            # Examples files do not have __init__.py files,
            # So we have to temporarily extend sys.path to import them
            sys.path.insert(0, dirname)
            module = file[:-3] # remove ".py"
        setup_pprint()
        try:
            module = pdoctest._normalize_module(module)
            tests = SymPyDocTestFinder().find(module)
        except (SystemExit, KeyboardInterrupt):
            raise
        except ImportError:
            self._reporter.import_error(filename, sys.exc_info())
            return
        finally:
            if rel_name.startswith("examples"):
                del sys.path[0]

        tests = [test for test in tests if len(test.examples) > 0]
        # By default tests are sorted by alphabetical order by function name.
        # We sort by line number so one can edit the file sequentially from
        # bottom to top. However, if there are decorated functions, their line
        # numbers will be too large and for now one must just search for these
        # by text and function name.
        tests.sort(key=lambda x: -x.lineno)

        if not tests:
            return
        self._reporter.entering_filename(filename, len(tests))
        for test in tests:
            assert len(test.examples) != 0
            runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | \
                    pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL)
            old = sys.stdout
            new = StringIO()
            sys.stdout = new
            # If the testing is normal, the doctests get importing magic to
            # provide the global namespace. If not normal (the default) then
            # then must run on their own; all imports must be explicit within
            # a function's docstring. Once imported that import will be
            # available to the rest of the tests in a given function's
            # docstring (unless clear_globs=True below).
            if not self._normal:
                test.globs = {}
                # if this is uncommented then all the test would get is what
                # comes by default with a "from sympy import *"
                #exec('from sympy import *') in test.globs
            try:
                f, t = runner.run(test, out=new.write, clear_globs=False)
            except KeyboardInterrupt:
                raise
            finally:
                sys.stdout = old
            if f > 0:
                self._reporter.doctest_fail(test.name, new.getvalue())
            else:
                self._reporter.test_pass()
        self._reporter.leaving_filename()
def FunctionalDocFileSuite(*paths, **kw):
    if kw.get('module_relative', True):
        kw['package'] = doctest._normalize_module(kw.get('package'))
    return FunctionalSuiteFactory(*paths, **kw).docfilesuite()
def FunctionalDocTestSuite(module=None, **kw):
    module = doctest._normalize_module(module)
    return FunctionalSuiteFactory(module, **kw).doctestsuite()
def ZopeDocTestSuite(module=None, **kw):
    module = doctest._normalize_module(module)
    return ZopeSuiteFactory(module, **kw).doctestsuite()
Exemple #48
0
 def update_event(self, inp=-1):
     self.set_output_val(0, doctest._normalize_module(self.input(0), self.input(1)))
Exemple #49
0
def _resolve_relative_test_filename(filename):
    if os.path.isabs(filename):
        return filename
    package = doctest._normalize_module(None, 3)
    return doctest._module_relative_path(package, filename)
Exemple #50
0
def LayeredDocFileSuite(paths, id_extensions=None, **kw):
    """Create a DocFileSuite, optionally applying a layer to it.

    In addition to the standard DocFileSuite arguments, the following
    optional keyword arguments are accepted:

    :param stdout_logging: If True, log messages are sent to the
      doctest's stdout (defaults to True).
    :param stdout_logging_level: The logging level for the above.
    :param layer: A Zope test runner layer to apply to the tests (by
      default no layer is applied).
    """
    if not isinstance(paths, (tuple, list)):
        paths = [paths]
    if id_extensions is None:
        id_extensions = []
    kw.setdefault('optionflags', default_optionflags)
    kw.setdefault('parser', default_parser)

    # Make sure that paths are resolved relative to our caller
    kw['package'] = doctest._normalize_module(kw.get('package'))

    # Set stdout_logging keyword argument to True to make
    # logging output be sent to stdout, forcing doctests to deal with it.
    stdout_logging = kw.pop('stdout_logging', True)
    stdout_logging_level = kw.pop('stdout_logging_level', logging.INFO)

    if stdout_logging:
        kw_setUp = kw.get('setUp')

        def setUp(test):
            if kw_setUp is not None:
                kw_setUp(test)
            log = StdoutHandler('')
            log.setLoggerLevel(stdout_logging_level)
            log.install()
            test.globs['log'] = log
            # Store as instance attribute so we can uninstall it.
            test._stdout_logger = log

        kw['setUp'] = setUp

        kw_tearDown = kw.get('tearDown')

        def tearDown(test):
            if kw_tearDown is not None:
                kw_tearDown(test)
            reset_logging()
            test._stdout_logger.uninstall()

        kw['tearDown'] = tearDown

    layer = kw.pop('layer', None)
    suite = doctest.DocFileSuite(*paths, **kw)
    if layer is not None:
        suite.layer = layer

    for i, test in enumerate(suite):
        # doctest._module_relative_path() does not normalize paths. To make
        # test selection simpler and reporting easier to read, normalize here.
        test._dt_test.filename = os.path.normpath(test._dt_test.filename)
        # doctest.DocFileTest insists on using the basename of the file as the
        # test ID. This causes conflicts when two doctests have the same
        # filename, so we patch the id() method on the test cases.
        try:
            ext = id_extensions[i]
            newid = os.path.join(os.path.dirname(test._dt_test.filename), ext)
            test.id = partial(lambda x: x, newid)
        except IndexError:
            test.id = partial(lambda test: test._dt_test.filename, test)

    return suite