Python types.ModuleType() Examples

The following are code examples for showing how to use types.ModuleType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromModule__TestCase_subclass(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromModule(m)
        self.assertIsInstance(suite, loader.suiteClass)

        expected = [loader.suiteClass([MyTestCase('test')])]
        self.assertEqual(list(suite), expected)

    # "This method searches `module` for classes derived from TestCase"
    #
    # What happens if no tests are found (no TestCase instances)? 
Example 2
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromModule__no_TestCase_tests(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromModule(m)
        self.assertIsInstance(suite, loader.suiteClass)

        self.assertEqual(list(suite), [loader.suiteClass()])

    # "This method searches `module` for classes derived from TestCase"s
    #
    # What happens if loadTestsFromModule() is given something other
    # than a module?
    #
    # XXX Currently, it succeeds anyway. This flexibility
    # should either be documented or loadTestsFromModule() should
    # raise a TypeError
    #
    # XXX Certain people are using this behaviour. We'll add a test for it 
Example 3
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromModule__load_tests(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        load_tests_args = []
        def load_tests(loader, tests, pattern):
            self.assertIsInstance(tests, unittest.TestSuite)
            load_tests_args.extend((loader, tests, pattern))
            return tests
        m.load_tests = load_tests

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromModule(m)
        self.assertIsInstance(suite, unittest.TestSuite)
        self.assertEqual(load_tests_args, [loader, suite, None])

        load_tests_args = []
        suite = loader.loadTestsFromModule(m, use_load_tests=False)
        self.assertEqual(load_tests_args, []) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__relative_TestCase_subclass(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromName('testcase_1', m)
        self.assertIsInstance(suite, loader.suiteClass)
        self.assertEqual(list(suite), [MyTestCase('test')])

    # "The specifier name is a ``dotted name'' that may resolve either to
    # a module, a test case class, a TestSuite instance, a test method
    # within a test case class, or a callable object which returns a
    # TestCase or TestSuite instance." 
Example 5
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__relative_testmethod(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromName('testcase_1.test', m)
        self.assertIsInstance(suite, loader.suiteClass)

        self.assertEqual(list(suite), [MyTestCase('test')])

    # "The specifier name is a ``dotted name'' that may resolve either to
    # a module, a test case class, a TestSuite instance, a test method
    # within a test case class, or a callable object which returns a
    # TestCase or TestSuite instance."
    #
    # Does loadTestsFromName() raise the proper exception when trying to
    # resolve "a test method within a test case class" that doesn't exist
    # for the given name (relative to a provided module)? 
Example 6
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__callable__TestCase_instance(self):
        m = types.ModuleType('m')
        testcase_1 = unittest.FunctionTestCase(lambda: None)
        def return_TestCase():
            return testcase_1
        m.return_TestCase = return_TestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromName('return_TestCase', m)
        self.assertIsInstance(suite, loader.suiteClass)
        self.assertEqual(list(suite), [testcase_1])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a callable object which returns a TestCase ... instance"
    #*****************************************************************
    #Override the suiteClass attribute to ensure that the suiteClass
    #attribute is used 
Example 7
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
        class SubTestSuite(unittest.TestSuite):
            pass
        m = types.ModuleType('m')
        testcase_1 = unittest.FunctionTestCase(lambda: None)
        def return_TestCase():
            return testcase_1
        m.return_TestCase = return_TestCase

        loader = unittest.TestLoader()
        loader.suiteClass = SubTestSuite
        suite = loader.loadTestsFromName('return_TestCase', m)
        self.assertIsInstance(suite, loader.suiteClass)
        self.assertEqual(list(suite), [testcase_1])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a test method within a test case class"
    #*****************************************************************
    #Override the suiteClass attribute to ensure that the suiteClass
    #attribute is used 
Example 8
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
        class SubTestSuite(unittest.TestSuite):
            pass
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        loader.suiteClass=SubTestSuite
        suite = loader.loadTestsFromName('testcase_1.test', m)
        self.assertIsInstance(suite, loader.suiteClass)

        self.assertEqual(list(suite), [MyTestCase('test')])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a callable object which returns a TestCase or TestSuite instance"
    #
    # What happens if the callable returns something else? 
Example 9
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromName__callable__wrong_type(self):
        m = types.ModuleType('m')
        def return_wrong():
            return 6
        m.return_wrong = return_wrong

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromName('return_wrong', m)
        except TypeError:
            pass
        else:
            self.fail("TestLoader.loadTestsFromName failed to raise TypeError")

    # "The specifier can refer to modules and packages which have not been
    # imported; they will be imported as a side-effect" 
Example 10
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromNames__relative_testmethod(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(['testcase_1.test'], m)
        self.assertIsInstance(suite, loader.suiteClass)

        ref_suite = unittest.TestSuite([MyTestCase('test')])
        self.assertEqual(list(suite), [ref_suite])

    # "The specifier name is a ``dotted name'' that may resolve ... to ... a
    # test method within a test case class"
    #
    # Does the method gracefully handle names that initially look like they
    # resolve to "a test method within a test case class" but don't? 
Example 11
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromNames__callable__TestSuite(self):
        m = types.ModuleType('m')
        testcase_1 = unittest.FunctionTestCase(lambda: None)
        testcase_2 = unittest.FunctionTestCase(lambda: None)
        def return_TestSuite():
            return unittest.TestSuite([testcase_1, testcase_2])
        m.return_TestSuite = return_TestSuite

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(['return_TestSuite'], m)
        self.assertIsInstance(suite, loader.suiteClass)

        expected = unittest.TestSuite([testcase_1, testcase_2])
        self.assertEqual(list(suite), [expected])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a callable object which returns a TestCase ... instance" 
Example 12
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromNames__callable__TestCase_instance(self):
        m = types.ModuleType('m')
        testcase_1 = unittest.FunctionTestCase(lambda: None)
        def return_TestCase():
            return testcase_1
        m.return_TestCase = return_TestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(['return_TestCase'], m)
        self.assertIsInstance(suite, loader.suiteClass)

        ref_suite = unittest.TestSuite([testcase_1])
        self.assertEqual(list(suite), [ref_suite])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a callable object which returns a TestCase or TestSuite instance"
    #
    # Are staticmethods handled correctly? 
Example 13
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_loadTestsFromNames__callable__wrong_type(self):
        m = types.ModuleType('m')
        def return_wrong():
            return 6
        m.return_wrong = return_wrong

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromNames(['return_wrong'], m)
        except TypeError:
            pass
        else:
            self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")

    # "The specifier can refer to modules and packages which have not been
    # imported; they will be imported as a side-effect" 
Example 14
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_testMethodPrefix__loadTestsFromModule(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
        tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]

        loader = unittest.TestLoader()
        loader.testMethodPrefix = 'foo'
        self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)

        loader.testMethodPrefix = 'test'
        self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)

    # "String giving the prefix of method names which will be interpreted as
    # test methods"
    #
    # Implicit in the documentation is that testMethodPrefix is respected by
    # all loadTestsFrom* methods. 
Example 15
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_testMethodPrefix__loadTestsFromName(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests_1 = unittest.TestSuite([Foo('foo_bar')])
        tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])

        loader = unittest.TestLoader()
        loader.testMethodPrefix = 'foo'
        self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)

        loader.testMethodPrefix = 'test'
        self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)

    # "String giving the prefix of method names which will be interpreted as
    # test methods"
    #
    # Implicit in the documentation is that testMethodPrefix is respected by
    # all loadTestsFrom* methods. 
Example 16
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_testMethodPrefix__loadTestsFromNames(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
        tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
        tests_2 = unittest.TestSuite([tests_2])

        loader = unittest.TestLoader()
        loader.testMethodPrefix = 'foo'
        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)

        loader.testMethodPrefix = 'test'
        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)

    # "The default value is 'test'" 
Example 17
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_sortTestMethodsUsing__loadTestsFromModule(self):
        def reversed_cmp(x, y):
            return -cmp(x, y)

        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
        m.Foo = Foo

        loader = unittest.TestLoader()
        loader.sortTestMethodsUsing = reversed_cmp

        tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
        self.assertEqual(list(loader.loadTestsFromModule(m)), tests)

    # "Function to be used to compare method names when sorting them in
    # getTestCaseNames() and all the loadTestsFromX() methods" 
Example 18
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_sortTestMethodsUsing__loadTestsFromNames(self):
        def reversed_cmp(x, y):
            return -cmp(x, y)

        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
        m.Foo = Foo

        loader = unittest.TestLoader()
        loader.sortTestMethodsUsing = reversed_cmp

        tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
        self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)

    # "Function to be used to compare method names when sorting them in
    # getTestCaseNames()"
    #
    # Does it actually affect getTestCaseNames()? 
Example 19
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_suiteClass__loadTestsFromModule(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests = [[Foo('test_1'), Foo('test_2')]]

        loader = unittest.TestLoader()
        loader.suiteClass = list
        self.assertEqual(loader.loadTestsFromModule(m), tests)

    # It is implicit in the documentation for TestLoader.suiteClass that
    # all TestLoader.loadTestsFrom* methods respect it. Let's make sure 
Example 20
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_suiteClass__loadTestsFromName(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests = [Foo('test_1'), Foo('test_2')]

        loader = unittest.TestLoader()
        loader.suiteClass = list
        self.assertEqual(loader.loadTestsFromName('Foo', m), tests)

    # It is implicit in the documentation for TestLoader.suiteClass that
    # all TestLoader.loadTestsFrom* methods respect it. Let's make sure 
Example 21
Project: pyblish-win   Author: pyblish   File: _mock_backport.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_original(self):
        target = self.getter()
        name = self.attribute

        original = DEFAULT
        local = False

        try:
            original = target.__dict__[name]
        except (AttributeError, KeyError):
            original = getattr(target, name, DEFAULT)
        else:
            local = True

        if name in _builtins and isinstance(target, ModuleType):
            self.create = True

        if not self.create and original is DEFAULT:
            raise AttributeError(
                "%s does not have the attribute %r" % (target, name)
            )
        return original, local 
Example 22
Project: AutoDL   Author: tanguofu   File: config.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_pyfile(self, filename):
        """Update the values in the config from a Python file.
        Only the uppercase variables in that module are stored in the config.

        :param filename: an absolute path to the config file
        """
        module = types.ModuleType('config')
        module.__file__ = filename
        try:
            with open(filename) as config_file:
                exec(compile(config_file.read(), filename, 'exec'),
                     module.__dict__)
        except IOError as e:
            e.strerror = 'Unable to load configuration file (%s)' % e.strerror
            raise
        self.from_object(module)
        return True 
Example 23
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 24
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: __init__.py    MIT License 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 25
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 26
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 27
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 6 votes vote down vote up
def _handle_ns(packageName, path_item):
    """Ensure that named package includes a subpath of path_item (if needed)"""

    importer = get_importer(path_item)
    if importer is None:
        return None
    loader = importer.find_module(packageName)
    if loader is None:
        return None
    module = sys.modules.get(packageName)
    if module is None:
        module = sys.modules[packageName] = types.ModuleType(packageName)
        module.__path__ = []
        _set_parent_ns(packageName)
    elif not hasattr(module, '__path__'):
        raise TypeError("Not a package:", packageName)
    handler = _find_adapter(_namespace_handlers, importer)
    subpath = handler(importer, path_item, packageName, module)
    if subpath is not None:
        path = module.__path__
        path.append(subpath)
        loader.load_module(packageName)
        _rebuild_mod_path(path, packageName, module)
    return subpath 
Example 29
Project: Paradrop   Author: ParadropLabs   File: settings.py    Apache License 2.0 6 votes vote down vote up
def iterate_module_attributes(module):
    """
    Iterate over the attributes in a module.

    This is a generator function.

    Returns (name, value) tuples.
    """
    for name in dir(module):
        # Ignore fields marked as private or builtin.
        if name.startswith('_'):
            continue

        value = getattr(module, name)

        # Ignore callable objects (functions) and loaded modules.
        if callable(value) or isinstance(value, types.ModuleType):
            continue

        yield (name, value) 
Example 30
Project: pcc   Author: jiamo   File: yacc.py    The Unlicense 6 votes vote down vote up
def read_table(self, module):
        if isinstance(module, types.ModuleType):
            parsetab = module
        else:
            exec('import %s' % module)
            parsetab = sys.modules[module]

        if parsetab._tabversion != __tabversion__:
            raise VersionError('yacc table file version is out of date')

        self.lr_action = parsetab._lr_action
        self.lr_goto = parsetab._lr_goto

        self.lr_productions = []
        for p in parsetab._lr_productions:
            self.lr_productions.append(MiniProduction(*p))

        self.lr_method = parsetab._lr_method
        return parsetab._lr_signature 
Example 31
Project: SublimeKSP   Author: nojanath   File: yacc.py    GNU General Public License v3.0 6 votes vote down vote up
def read_table(self,module):
        if isinstance(module,types.ModuleType):
            parsetab = module
        else:
            if sys.version_info[0] < 3:
                exec("import %s as parsetab" % module)
            else:
                env = { }
                exec("import %s as parsetab" % module, env, env)
                parsetab = env['parsetab']

        if parsetab._tabversion != __tabversion__:
            raise VersionError("yacc table file version is out of date")

        self.lr_action = parsetab._lr_action
        self.lr_goto = parsetab._lr_goto

        self.lr_productions = []
        for p in parsetab._lr_productions:
            self.lr_productions.append(MiniProduction(*p))

        self.lr_method = parsetab._lr_method
        return parsetab._lr_signature 
Example 32
Project: calmjs   Author: calmjs   File: test_artifact.py    GNU General Public License v2.0 6 votes vote down vote up
def test_iter_builders_side_effect(self):
        # inject dummy module and add cleanup
        mod = ModuleType('calmjs_testing_dummy')
        mod.complete = generic_builder
        self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
        sys.modules['calmjs_testing_dummy'] = mod

        working_dir = utils.mkdtemp(self)
        utils.make_dummy_dist(self, (
            ('entry_points.txt', '\n'.join([
                '[calmjs.artifacts]',
                'artifact.js = calmjs_testing_dummy:complete',
            ])),
        ), 'app', '1.0', working_dir=working_dir)
        mock_ws = WorkingSet([working_dir])
        registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
        registry.update_artifact_metadata('app', {})

        root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
        self.assertFalse(exists(root))
        ep, toolchain, spec = next(registry.iter_builders_for('app'))
        self.assertFalse(exists(root))
        # directory only created after the toolchain is executed
        toolchain(spec)
        self.assertTrue(exists(root)) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromModule__no_TestCase_instances(self):
        m = types.ModuleType('m')

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromModule(m)
        self.assertIsInstance(suite, loader.suiteClass)
        self.assertEqual(list(suite), [])

    # "This method searches `module` for classes derived from TestCase"
    #
    # What happens if no tests are found (TestCases instances, but no tests)? 
Example 34
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromName__relative_bad_object(self):
        m = types.ModuleType('m')
        m.testcase_1 = object()

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromName('testcase_1', m)
        except TypeError:
            pass
        else:
            self.fail("Should have raised TypeError")

    # "The specifier name is a ``dotted name'' that may
    # resolve either to ... a test case class" 
Example 35
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromName__relative_TestSuite(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testsuite = unittest.TestSuite([MyTestCase('test')])

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromName('testsuite', m)
        self.assertIsInstance(suite, loader.suiteClass)

        self.assertEqual(list(suite), [MyTestCase('test')])

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a test method within a test case class" 
Example 36
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromName__relative_invalid_testmethod(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromName('testcase_1.testfoo', m)
        except AttributeError, e:
            self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") 
Example 37
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromNames__relative_bad_object(self):
        m = types.ModuleType('m')
        m.testcase_1 = object()

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromNames(['testcase_1'], m)
        except TypeError:
            pass
        else:
            self.fail("Should have raised TypeError")

    # "The specifier name is a ``dotted name'' that may resolve ... to
    # ... a test case class" 
Example 38
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromNames__relative_TestSuite(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testsuite = unittest.TestSuite([MyTestCase('test')])

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(['testsuite'], m)
        self.assertIsInstance(suite, loader.suiteClass)

        self.assertEqual(list(suite), [m.testsuite])

    # "The specifier name is a ``dotted name'' that may resolve ... to ... a
    # test method within a test case class" 
Example 39
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromNames__relative_invalid_testmethod(self):
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            def test(self):
                pass
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        try:
            loader.loadTestsFromNames(['testcase_1.testfoo'], m)
        except AttributeError, e:
            self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'") 
Example 40
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_suiteClass__loadTestsFromNames(self):
        m = types.ModuleType('m')
        class Foo(unittest.TestCase):
            def test_1(self): pass
            def test_2(self): pass
            def foo_bar(self): pass
        m.Foo = Foo

        tests = [[Foo('test_1'), Foo('test_2')]]

        loader = unittest.TestLoader()
        loader.suiteClass = list
        self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)

    # "The default value is the TestSuite class" 
Example 41
Project: pyblish-win   Author: pyblish   File: test_loader.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_loadTestsFromName__function_with_different_name_than_method(self):
        # lambdas have the name '<lambda>'.
        m = types.ModuleType('m')
        class MyTestCase(unittest.TestCase):
            test = lambda: 1
        m.testcase_1 = MyTestCase

        loader = unittest.TestLoader()
        suite = loader.loadTestsFromNames(['testcase_1.test'], m)
        self.assertIsInstance(suite, loader.suiteClass)

        ref_suite = unittest.TestSuite([MyTestCase('test')])
        self.assertEqual(list(suite), [ref_suite]) 
Example 42
Project: pyblish-win   Author: pyblish   File: inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def ismodule(object):
    """Return true if the object is a module.

    Module objects provide these attributes:
        __doc__         documentation string
        __file__        filename (missing for built-in modules)"""
    return isinstance(object, types.ModuleType) 
Example 43
Project: pyblish-win   Author: pyblish   File: doctest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def rundict(self, d, name, module=None):
        import types
        m = types.ModuleType(name)
        m.__dict__.update(d)
        if module is None:
            module = False
        return self.rundoc(m, name, module) 
Example 44
Project: pyblish-win   Author: pyblish   File: doctest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run__test__(self, d, name):
        import types
        m = types.ModuleType(name)
        m.__test__ = d
        return self.rundoc(m, name) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_pydoc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # Better not to use unicode escapes in literals, lest the
        # parser choke on it if Python has been built without
        # unicode support.
        self.Q  = types.ModuleType(
            'Q', 'Rational numbers: \xe2\x84\x9a'.decode('utf8'))
        self.Q.__version__ = '\xe2\x84\x9a'.decode('utf8')
        self.Q.__date__ = '\xe2\x84\x9a'.decode('utf8')
        self.Q.__author__ = '\xe2\x84\x9a'.decode('utf8')
        self.Q.__credits__ = '\xe2\x84\x9a'.decode('utf8')

        self.assertIsInstance(self.Q.__doc__, unicode) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_descr.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_unintialized_modules(self):
        # Testing uninitialized module objects...
        from types import ModuleType as M
        m = M.__new__(M)
        str(m)
        self.assertNotHasAttr(m, "__name__")
        self.assertNotHasAttr(m, "__file__")
        self.assertNotHasAttr(m, "foo")
        self.assertFalse(m.__dict__)   # None or {} are both reasonable answers
        m.foo = 1
        self.assertEqual(m.__dict__, {"foo": 1}) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_getmodule_recursion(self):
        from types import ModuleType
        name = '__inspect_dummy'
        m = sys.modules[name] = ModuleType(name)
        m.__file__ = "<string>" # hopefully not a real filename...
        m.__loader__ = "dummy"  # pretend the filename is understood by a loader
        exec "def x(): pass" in m.__dict__
        self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
        del sys.modules[name]
        inspect.getmodule(compile('a=10','','single')) 
Example 48
Project: pyblish-win   Author: pyblish   File: test_getopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_libref_examples(self):
        s = """
        Examples from the Library Reference:  Doc/lib/libgetopt.tex

        An example using only Unix style options:


        >>> import getopt
        >>> args = '-a -b -cfoo -d bar a1 a2'.split()
        >>> args
        ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'abc:d:')
        >>> optlist
        [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
        >>> args
        ['a1', 'a2']

        Using long option names is equally easy:


        >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
        >>> args = s.split()
        >>> args
        ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
        >>> optlist, args = getopt.getopt(args, 'x', [
        ...     'condition=', 'output-file=', 'testing'])
        >>> optlist
        [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
        >>> args
        ['a1', 'a2']
        """

        import types
        m = types.ModuleType("libreftest", s)
        run_doctest(m, verbose) 
Example 49
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadRemoteClient.py    GNU General Public License v3.0 5 votes vote down vote up
def getCallTip(self, line, var, truncate=True):
        element = introspect.getRoot(line)
        if len(element) < len(var): return
        try:
            object = eval(element, self.interp.locals)
        except:
            return
        if var in element:
            try:
                funcName, funcParam, funcHelp = introspect.getCallTip(element, locals=self.interp.locals)
            except:
                funcHelp = ''
            typ = str(type(object))
            if typ.startswith("<type '") and typ.endswith("'>"):
                typ = typ[7:-2]
            if funcHelp:
                textFull = funcHelp
                if truncate: funcHelp = self.maxCallTip(textFull)
                calltip = 'type: ', typ, '\ndoc: ', funcHelp
            else:
                textFull = str(object)
                if isinstance(object, ModuleType):
                    try:
                        textFull = textFull + '\nhelp:\n'+object.__doc__
                    except: pass
                    value = textFull
                    if truncate: value = self.maxCallTip(textFull)
                    calltip = 'type: ', typ, '\nstr: ', ('\n' if '\n' in value else '') + value
                else:
                    value = textFull
                    if truncate: value = self.maxCallTip(textFull)
                    calltip = 'type: ', typ, '\nstr: ', ('\n' if '\n' in value else '') + value
            self.fullCallTip = var, calltip[:-1] + (textFull,)
        nHighlight = 0
        for ct in calltip[:3]:
            nHighlight += len(ct)

        return element, str(nHighlight), calltip 
Example 50
Project: programsynthesishunting   Author: flexgp   File: python_script_evaluation.py    GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        # START LINUX: used to receive Memory Error faster in Linux
        try:
            import resource
            resource.setrlimit(resource.RLIMIT_AS, (2 ** 30, 2 ** 30))  # 2 ** 30 == 1GB in bytes
        except ImportError:
            pass
        # END LINUX:
        while True:
            exception = None
            self.stop.value = False
            script = self.consume.get()
            if script:
                help_globals = {'stop': self.stop}
                try:
                    exec(script, help_globals)
                except BaseException as e:
                    exc_type, exc_obj, exc_tb = sys.exc_info()
                    exception = '{} {} {}'.format(exc_type, exc_obj, e.args)
                if exception:
                    self.produce.put({'exception': exception})
                else:
                    self.produce.put({key: value for key, value in help_globals.items()
                                      if not callable(value) and             # cannot be a function
                                      not isinstance(value, ModuleType) and  # cannot be a module
                                      key not in ['__builtins__', 'stop']})  # cannot be builtins or synchronized objects
                del help_globals
            else:
                break