Ejemplo n.º 1
0
    def test_deprecation(self):
        import warnings
        argparser = ArgumentParser(prog='prog', add_help=False)
        argparser.add_argument('-n', '--normal', action='store')
        argparser.add_argument(
            '-d', '--deprecated', action='store', deprecation=True)
        argparser.add_argument(
            '--bye', action=StoreDelimitedListBase, deprecation='bye')

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            # test that they store stuff
            args = argparser.parse_args(['-n', 'hello'])
            self.assertEqual(args.normal, 'hello')
            args = argparser.parse_args(['-d', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--deprecated', 'hello'])
            self.assertEqual(args.deprecated, 'hello')
            args = argparser.parse_args(['--bye', 'hello,goodbye'])
            self.assertEqual(args.bye, ['hello', 'goodbye'])

        # and the warnings are triggered
        self.assertEqual(
            "option '-d' is deprecated", str(w[0].message))
        self.assertEqual(
            "option '--deprecated' is deprecated", str(w[1].message))
        self.assertEqual(
            "option '--bye' is deprecated: bye", str(w[2].message))

        stream = StringIO()
        argparser.print_help(file=stream)
        # deprecated options are not visible on help
        self.assertNotIn("--deprecated", stream.getvalue())
        self.assertNotIn("--bye", stream.getvalue())
        self.assertIn("--normal", stream.getvalue())
Ejemplo n.º 2
0
    def test_plugin_package_chained_loaders_initial_simple(self):
        working_dir = mkdtemp(self)
        reg, base, extra, base_dir, extra_dir = self.create_base_extra_plugins(
            working_dir)
        simple = reg.records['simple'] = LoaderPluginHandler(reg, 'simple')

        toolchain = NullToolchain()
        spec = Spec(working_dir=working_dir)

        with pretty_logging(stream=StringIO()) as stream:
            self.assertEqual(
                {},
                simple.generate_handler_sourcepath(toolchain, spec, {
                    'simple!fun.file': 'fun.file',
                }),
            )

        with pretty_logging(stream=StringIO()) as stream:
            self.assertEqual({
                'extra': join(extra_dir, 'extra.js'),
            }, simple.generate_handler_sourcepath(toolchain, spec, {
                    'simple!extra!fun.file': 'fun.file',
                }),
            )
        self.assertIn("for loader plugin 'extra'", stream.getvalue())
Ejemplo n.º 3
0
    def test_export_config_mode_versions(self):
        config = configuration.WebpackConfig(mode='none', )
        self.assertIn('"mode": "none"', str(config))

        # downgrade webpack version
        config['__webpack_target__'] = (2, 6, 1)
        with pretty_logging(stream=StringIO()) as fd:
            # default mode value should not be seralized
            config_str = str(config)
            self.assertNotIn('"mode": "none"', config_str)
            self.assertIn("var webpackConfig = {", config_str)
        self.assertIn(
            'INFO calmjs.webpack.configuration unsupported property with '
            'default value removed for webpack 2.6.1: {"mode": "none"}',
            fd.getvalue())

        # change mode to a non-default value
        config['mode'] = 'production'
        with pretty_logging(stream=StringIO()) as fd:
            # default mode value should not be seralized
            config_str = str(config)
            self.assertNotIn('"mode": "production"', config_str)
            self.assertIn("var webpackConfig = {", config_str)
        self.assertIn(
            'WARNING calmjs.webpack.configuration unsupported property with '
            'non-default value removed for webpack 2.6.1: '
            '{"mode": "production"}', fd.getvalue())
Ejemplo n.º 4
0
 def test_dump(self):
     stream = StringIO()
     json_dump({'a': 'b', 'c': 'd'}, stream)
     self.assertEqual(
         stream.getvalue(),
         '{\n    "a": "b",\n    "c": "d"\n}'
     )
Ejemplo n.º 5
0
 def test_get_modpath_pkg_resources_invalid(self):
     with pretty_logging(stream=StringIO()) as fd:
         self.assertEqual([], indexer.modpath_pkg_resources(None))
         self.assertIn("None does not appear to be a valid module",
                       fd.getvalue())
     with pretty_logging(stream=StringIO()) as fd:
         module = ModuleType('nothing')
         self.assertEqual([], indexer.modpath_pkg_resources(module))
         # module repr differs between python versions.
         self.assertIn("module 'nothing'", fd.getvalue())
         self.assertIn("could not be located", fd.getvalue())
Ejemplo n.º 6
0
 def test_sorted_standard(self):
     parser = argparse.ArgumentParser(formatter_class=SortedHelpFormatter,
                                      add_help=False)
     parser.add_argument('-z', '--zebra', help='make zebras')
     parser.add_argument('-a', '--alpaca', help='make alpacas')
     parser.add_argument('-s', '--sheep', help='make sheep')
     parser.add_argument('-g', '--goat', help='make goats')
     stream = StringIO()
     parser.print_help(file=stream)
     options = [
         line.split()[0] for line in stream.getvalue().splitlines()
         if '--' in line
     ]
     self.assertEqual(options, ['-a', '-g', '-s', '-z'])
Ejemplo n.º 7
0
 def test_sorted_standard(self):
     parser = argparse.ArgumentParser(
         formatter_class=SortedHelpFormatter, add_help=False)
     parser.add_argument('-z', '--zebra', help='make zebras')
     parser.add_argument('-a', '--alpaca', help='make alpacas')
     parser.add_argument('-s', '--sheep', help='make sheep')
     parser.add_argument('-g', '--goat', help='make goats')
     stream = StringIO()
     parser.print_help(file=stream)
     options = [
         line.split()[0]
         for line in stream.getvalue().splitlines() if
         '--' in line
     ]
     self.assertEqual(options, ['-a', '-g', '-s', '-z'])
Ejemplo n.º 8
0
    def test_export_config_optimization(self):
        config = configuration.WebpackConfig(optimization={"minimize": True}, )
        # standard optimization setting is kept for latest webpack
        with pretty_logging(logger='calmjs.webpack', stream=StringIO()) as fd:
            config_s = str(config)
            self.assertIn('"optimization": {', config_s)
            self.assertIn('"minimize": true', config_s)

        self.assertEqual('', fd.getvalue())

        # downgrade webpack version
        config['__webpack_target__'] = (2, 6, 1)
        with pretty_logging(logger='calmjs.webpack', stream=StringIO()) as fd:
            config_s = str(config)
            self.assertNotIn('"optimization": {', config_s)
            self.assertNotIn('"minimize": true', config_s)
            self.assertIn('new webpack.optimize.UglifyJsPlugin({})', config_s)

        self.assertIn(
            "converting unsupported property to a plugin for "
            "webpack 2.6.1: {", fd.getvalue())
        self.assertIn('"minimize": true', fd.getvalue())

        # set minimize to false
        config['optimization']["minimize"] = False
        with pretty_logging(logger='calmjs.webpack', stream=StringIO()) as fd:
            config_s = str(config)
            self.assertNotIn('"optimization": {', config_s)
            self.assertNotIn('"minimize": true', config_s)
            self.assertNotIn('new webpack.optimize.UglifyJsPlugin({})',
                             config_s)

        self.assertIn("dropping unsupported property for webpack 2.6.1: {",
                      fd.getvalue())
        self.assertIn('"minimize": false', fd.getvalue())

        # set minimize to an unsupported value
        config['optimization']["minimize"] = {}
        with pretty_logging(logger='calmjs.webpack', stream=StringIO()) as fd:
            config_s = str(config)
            self.assertNotIn('"optimization": {', config_s)
            self.assertNotIn('"minimize": true', config_s)
            self.assertNotIn('new webpack.optimize.UglifyJsPlugin({})',
                             config_s)

        self.assertIn("dropping unsupported property for webpack 2.6.1: {",
                      fd.getvalue())
        self.assertIn('"minimize": {}', fd.getvalue())
Ejemplo n.º 9
0
    def test_modname_target_to_config_paths_warning(self):
        f = plugin.TextPlugin(None).modname_target_to_config_paths
        # There are cases where if the python style namespace separator
        # is used for the generated path, and the final fragment has no
        # further '.' characters, WILL result in a complete mismatch of
        # the key to the expected target.  That said, this particular
        # type of mapping doesn't seem to be supported at all by the
        # requirejs-text plugin.
        with pretty_logging('calmjs.rjs.plugin', stream=StringIO()) as stream:
            self.assertEqual(
                f('text!some.target/file', '/src/some/target/file'),
                {'some.target/file': '/src/some/target/file'},
                # Do nothing as this type of conversion/mapping doesn't
                # work no matter what, because requirejs and/or the text
                # loader plugin fails at tracking directories if it has
                # a '.' somewhere, so the loader gets confused and just
                # don't see the mapping entry.

                # To mitigate, ensure the provided files or paths
                # provided have a filename extension and does not end
                # with a ``.`` character.
            )

        # ensure that is logged
        err = stream.getvalue()
        self.assertIn('WARNING', err)
        self.assertIn('no possible workaround', err)
Ejemplo n.º 10
0
    def test_process_test_files_assorted(self):
        from calmjs.webpack.cli import default_toolchain as toolchain
        # the bare minimum spec
        spec = Spec(
            build_dir=mkdtemp(self),
            test_module_paths_map={
                # the values are normally absolute paths.
                'example/tests/test_main': 'test_main.js',
                'example/tests/data.json': 'data.json',
                'text!example/tests/data.txt': 'data.txt',
            },
            karma_config={
                'webpack': {
                    'resolve': {
                        'alias': {},
                    },
                },
                'preprocessors': {},
            })

        with pretty_logging(stream=StringIO()) as s:
            test_files, loaderspath = dev._process_test_files(toolchain, spec)

        self.assertEqual({'test_main.js'}, test_files)
        self.assertEqual({'text!example/tests/data.txt': 'data.txt'},
                         loaderspath)
        self.assertIn(
            "only aliasing modpath 'example/tests/data.json' to target "
            "'data.json'", s.getvalue())
Ejemplo n.º 11
0
    def test_process_path_error(self):
        build_dir = mkdtemp(self)
        source1 = join(build_dir, 'source1.js')
        source2 = join(build_dir, 'source2.js')
        source3 = join(build_dir, 'source3.js')

        with open(source1, 'w') as fd:
            fd.write("define('source1/mod1', ['require','exports','module'],"
                     "function (require, exports, module) {});\n"
                     "define('source1/mod2', ['require','exports','module'],"
                     "function (require, exports, module) {});\n")

        with open(source2, 'w') as fd:
            fd.write("define('source2/mod1', ['require','exports','module']"
                     "function (require, exports, module) {});\n")

        with open(source3, 'w') as fd:
            fd.write("define('source3/mod1', ['require','exports','module'],"
                     "function (require, exports, module) {});\n")

        with pretty_logging(stream=StringIO()) as s:
            result = process_artifacts([source1, source2, source3])
        self.assertEqual(sorted(result),
                         ['source1/mod1', 'source1/mod2', 'source3/mod1'])
        self.assertIn('syntax error in', s.getvalue())
        self.assertIn(source2, s.getvalue())
Ejemplo n.º 12
0
 def test_extract_defines_amd_artifact3_missing(self):
     with pretty_logging(stream=StringIO()) as stream:
         result = requirejs.extract_defines_with_deps(artifact_multiple3)
     self.assertEqual(['lib4', 'lib2', 'lib1'], result)
     s = stream.getvalue()
     self.assertIn("module 'missing' required but seems to be missing", s)
     self.assertIn("WARNING", s)
Ejemplo n.º 13
0
    def test_karma_setup_not_webpack_artifact(self):
        karma_config = karma.build_base_config()
        src_dir = mkdtemp(self)
        fake_artifact = join(src_dir, 'fake_artifact.js')

        with open(fake_artifact, 'w') as fd:
            fd.write('(function(root, factory) { factory() })')
            fd.write('(this, function() {});')

        build_dir = mkdtemp(self)
        spec = Spec(
            karma_config=karma_config,
            build_dir=build_dir,
            test_module_paths_map={
                'some/package/tests/test_module':
                '/src/some/package/tests/test_module.js'
            },
            artifact_paths=[fake_artifact],
            toolchain_bin_path=self.setup_fake_webpack(),
        )

        with pretty_logging(stream=StringIO()) as s:
            karma_webpack(spec)

        log = s.getvalue()
        self.assertIn("unable to extract calmjs related exports from", log)
        self.assertIn(fake_artifact, log)
Ejemplo n.º 14
0
    def test_rjs_core_compiled_failure_bad_template(self):
        remember_cwd(self)
        chdir(self._env_root)
        build_dir = mkdtemp(self)
        src_dir = mkdtemp(self)
        src_template = join(src_dir, 'template.nja')

        with open(src_template, 'w') as fd:
            fd.write('<p>Hello {%World%}</p>')

        spec = Spec(
            build_dir=build_dir,
            plugin_sourcepath={
                'text!mold/dummy/template.nja': src_template,
            },
            bundle_sourcepath={},
        )
        build_dir = mkdtemp(self)
        rjs(spec, ())

        with pretty_logging('nunja', stream=StringIO()) as stream:
            spec.handle(BEFORE_COMPILE)

        err = stream.getvalue()
        self.assertIn('ERROR', err)
        self.assertIn('failed to precompile', err)
        self.assertIn('Template render error: (mold/dummy/template.nja)', err)
Ejemplo n.º 15
0
 def test_get_modpath_all_empty(self):
     module = ModuleType('nothing')
     with pretty_logging(stream=StringIO()) as fd:
         self.assertEqual(indexer.modpath_all(module), [])
     self.assertIn(
         "module 'nothing' does not appear to be a namespace module",
         fd.getvalue())
Ejemplo n.º 16
0
    def test_non_working_workaround(self):
        """
        A test to show non-working workaround

        The annoyances just keeps on giving.
        """

        with pretty_logging(stream=StringIO()) as stream:
            result = self.registry.modname_source_mapping_to_config_paths({
                'foo/bar':
                '/src/foo/bar.js',
                'text!foo/bar.txt':
                '/alt/src/foo/bar.txt',
            })
        err = stream.getvalue()
        self.assertEqual(
            {
                'foo/bar': '/src/foo/bar.js?',
                'foo/bar.txt': '/alt/src/foo/bar.txt',
            }, result['paths'])
        self.assertIn('WARNING', err)
        self.assertIn(
            "the value of paths['foo/bar'] is being rewritten from "
            "'/alt/src/foo/bar' to '/src/foo/bar.js?'; "
            "configuration may be in an invalid state.", err)
Ejemplo n.º 17
0
 def test_yarn_no_path(self):
     tmpdir = mkdtemp(self)
     os.chdir(tmpdir)
     os.environ['PATH'] = ''
     with pretty_logging(stream=StringIO()) as stderr:
         self.assertIsNone(yarn.get_yarn_version())
         self.assertIn("failed to execute 'yarn'", stderr.getvalue())
Ejemplo n.º 18
0
 def test_modname_target_to_config_paths_mismatch_dir_ext_file_noext(self):
     f = plugin.TextPlugin(None).modname_target_to_config_paths
     with pretty_logging('calmjs.rjs.plugin', stream=StringIO()) as stream:
         self.assertEqual(
             {
                 'file': 'some.dotted/dir/file',
                 'file.ns': 'some.dotted/dir/file.ns',
                 'file.ns/html': 'some.dotted/dir/file.ns/html',
             },
             f('text!file.ns/html', 'text!some.dotted/dir/file.ns/html'),
         )
     # this one provides both the dot stripped and the underlying
     # directory, to cover both case (unless this screws up some
     # other thing).
     err = stream.getvalue()
     # though since this should work, better to warn about this.
     self.assertIn('WARNING', err)
     self.assertIn(
         "warning triggered by mapping config.paths from "
         "modpath 'text!file.ns/html' to "
         "target 'text!some.dotted/dir/file.ns/html'", err)
     self.assertIn("unsupported values provided", err)
     self.assertIn("potentially working mitigations applied", err)
     self.assertIn('text!file.ns/html', err)
     self.assertIn('text!some.dotted/dir/file.ns/html', err)
Ejemplo n.º 19
0
    def test_fun_edge_case(self):
        """
        A very (un)fun edge case.

        Since the base module isn't so strict, there are situations
        where the workaround is still valid.
        """

        with pretty_logging(stream=StringIO()) as stream:
            result = self.registry.modname_source_mapping_to_config_paths({
                'foo/bar':
                '/src/foo/bar.js',
                'text!foo/bar.txt':
                '/src/foo/bar.txt',
            })
        err = stream.getvalue()
        # The mapping created by the plugin is compatible so no warnings
        # are issued.
        self.assertNotIn('WARNING', err)
        self.assertEqual(
            {
                'foo/bar': '/src/foo/bar',
                # the exact text mapping is also present.
                'foo/bar.txt': '/src/foo/bar.txt',
            },
            result['paths'])
Ejemplo n.º 20
0
    def test_nested(self):
        # the target is 'namespace/text_file.txt'
        build_dir = mkdtemp(self)
        srcdir = join(mkdtemp(self), 'namespace')
        mkdir(srcdir)
        spec = {'build_dir': build_dir}
        source = join(srcdir, 'text_file.txt')

        with open(source, 'w') as fd:
            fd.write('a text file\n')

        toolchain = None  # this one is not necessary for text.
        modname = 'text!namespace/text_file.txt'
        target = 'text!namespace/text_file.txt'
        modpath = 'text!namespace/text_file.txt'

        with pretty_logging('calmjs.rjs.plugin', stream=StringIO()) as stream:
            result = plugin.TextPlugin(None)(toolchain, spec, modname, source,
                                             target, modpath)
        self.assertEqual(stream.getvalue(), '')

        self.assertTrue(exists(join(build_dir, 'namespace', 'text_file.txt')))
        bundled_modpaths, bundled_targets, module_name = result
        self.assertEqual(
            bundled_modpaths, {
                'text!namespace/text_file.txt': 'text!namespace/text_file.txt',
            })
        self.assertEqual(
            bundled_targets, {
                'namespace/text_file': 'namespace/text_file',
                'namespace/text_file.txt': 'namespace/text_file.txt',
            })
        self.assertEqual(module_name, ['text!namespace/text_file.txt'])
Ejemplo n.º 21
0
    def test_requirejs_is_pretty_much_completely_broken(self):
        """
        Showing how requirejs and/or requirejs-text is basically broken

        I mean, I covered how it basically can't deal with filename
        extensions correctly, so no amount of workaround can really fix
        the underlying brokenness.
        """

        with pretty_logging(stream=StringIO()) as stream:
            result = self.registry.modname_target_mapping_to_config_paths({
                'text!foo/bar.txt':
                'text!/src/foo/bar.txt',
                'text!foo/bar.html':
                'text!/alt/src/foo/bar.html',
            })
        err = stream.getvalue()
        # html comes before txt, since the mapping is pre-sorted in
        # alphabetical order, so txt will end up overwriting html's base
        # directory.
        self.assertEqual(
            {
                'foo/bar': '/src/foo/bar',
                'foo/bar.txt': '/src/foo/bar.txt',
                'foo/bar.html': '/alt/src/foo/bar.html',
            }, result['paths'])
        self.assertIn('WARNING', err)
        self.assertIn("value of paths['foo/bar'] is being rewritten", err)
        self.assertIn("configuration may be in an invalid state", err)
        self.assertIn(
            "the value of paths['foo/bar'] is being rewritten from "
            "'/alt/src/foo/bar' to '/src/foo/bar'; "
            "configuration may be in an invalid state.", err)
Ejemplo n.º 22
0
 def test_initialize_warning_dupe_plugin(self):
     # ensure that we have a proper working registry
     working_set = WorkingSet({'calmjs.loader_plugin': [
         'example = calmjs.tests.test_loaderplugin:DupePlugin',
         'example = calmjs.loaderplugin:NPMLoaderPluginHandler',
     ]})
     # should not trigger import failure
     with pretty_logging(stream=StringIO()) as stream:
         registry = LoaderPluginRegistry(
             'calmjs.loader_plugin', _working_set=working_set)
     self.assertIn(
         "loader plugin handler for 'example' was already registered to an "
         "instance of 'calmjs.tests.test_loaderplugin:DupePlugin'",
         stream.getvalue()
     )
     # the second one will be registered
     self.assertTrue(
         isinstance(registry.get('example'), LoaderPluginHandler))
     # ensure that the handler can be acquired from a full name
     self.assertEqual('example', registry.get('example!hi').name)
     self.assertEqual('example', registry.get('example?arg!hi').name)
     self.assertEqual('example', registry.get('example?arg').name)
     self.assertIsNone(registry.get('examplearg'))
     self.assertIsNone(registry.get('ex'))
     self.assertIsNone(registry.get('ex!ample'))
Ejemplo n.º 23
0
 def test_missing_distribution(self):
     d_egg_root = join(mkdtemp(self), 'dummyns')
     make_dummy_dist(self, (
         (
             'namespace_packages.txt',
             'not_ns\n',
         ),
         (
             'entry_points.txt',
             '[dummyns]\n'
             'dummyns = dummyns:attr\n',
         ),
     ),
                     'dummyns',
                     '2.0',
                     working_dir=d_egg_root)
     working_set = pkg_resources.WorkingSet([
         d_egg_root,
         self.ds_egg_root,
     ])
     dummyns_ep = next(working_set.iter_entry_points('dummyns'))
     with pretty_logging(stream=StringIO()) as fd:
         p = indexer.resource_filename_mod_entry_point(
             'dummyns', dummyns_ep)
     # not stubbed working_set, so this is derived using fallback
     # value from the sys.modules['dummyns'] location
     self.assertEqual(normcase(p), normcase(self.dummyns_path))
     self.assertIn("distribution 'dummyns 2.0' not found", fd.getvalue())
Ejemplo n.º 24
0
    def test_get_modpath_pkg_resources_missing_path(self):
        with pretty_logging(stream=StringIO()) as fd:
            self.assertEqual([],
                             indexer.modpath_pkg_resources(None, calmjs_ep))
            self.assertIn("None does not appear to be a valid module",
                          fd.getvalue())
        with pretty_logging(stream=StringIO()) as fd:
            module = ModuleType('nothing')
            self.assertEqual([],
                             indexer.modpath_pkg_resources(module, calmjs_ep))

        err = fd.getvalue()
        self.assertIn("module 'nothing' and entry_point 'demo = demo'", err)
        # the input is fetched using a working entry_point, after all
        self.assertIn("path found at '" + calmjs_dist_dir, err)
        self.assertIn("it does not exist", fd.getvalue())
Ejemplo n.º 25
0
    def test_webpack_core_compiled_raw(self):
        remember_cwd(self)
        chdir(self._env_root)
        build_dir = mkdtemp(self)

        src_dir = mkdtemp(self)
        src_template = join(src_dir, 'template.nja')
        with open(src_template, 'w') as fd:
            fd.write('<p>Hello, {name}</p>')

        spec = Spec(
            build_dir=build_dir,
            loaderplugin_sourcepath={
                'text!some/mold/template.nja': src_template,
            },
            bundle_sourcepath={
                'nunjucks': join('node_modules', 'nunjucks', 'nunjucks.js'),
            },
        )
        with pretty_logging('nunja', stream=StringIO()) as stream:
            webpack(spec, ('raw'))
        # now trigger the advice
        spec.handle(BEFORE_COMPILE)
        # template remains in plugins
        self.assertEqual(spec['loaderplugin_sourcepath'], {
            'text!some/mold/template.nja': src_template,
        })
        # will not be applied in raw.
        self.assertIn('__nunja__/some/mold', spec['bundle_sourcepath'])
        self.assertIn(
            'nunja cannot skip precompilation for webpack toolchain',
            stream.getvalue(),
        )
Ejemplo n.º 26
0
    def test_karma_test_files_located(self):
        karma_config = karma.build_base_config()
        karma_config['files'] = ['example/package/lib.js']
        spec = Spec(
            karma_config=karma_config,
            build_dir=mkdtemp(self),
            rjs_loader_plugin_registry=get(RJS_LOADER_PLUGIN_REGISTRY_NAME),
            export_module_names=['preexported'],
            test_module_paths_map={
                'example/package/tests/test_some_module':
                '/src/example/package/tests/test_some_module.js',
                'example/package/tests/some_test_data':
                '/src/example/package/tests/some_test_data.js',
            },
        )

        with pretty_logging(stream=StringIO()):
            karma_requirejs(spec)

        with open(spec['karma_requirejs_test_script']) as fd:
            script = parse(fd.read())

        # this is the node for the json in the build file
        deps = json.loads(
            script.children()[0].children()[0].initializer.to_ecma())
        tests = json.loads(
            script.children()[1].children()[0].initializer.to_ecma())

        self.assertEqual(['example/package/tests/test_some_module'], tests)
        self.assertEqual(
            ['preexported', 'example/package/tests/some_test_data'], deps)
Ejemplo n.º 27
0
    def test_module_loader_registry_integration(self):
        working_set = WorkingSet({
            'calmjs.module': [
                'module4 = calmjs.testing.module4',
            ],
            'calmjs.module.loader': [
                'css = css[style]',
            ],
            __name__: [
                'calmjs.module = calmjs.module:ModuleRegistry',
                'calmjs.module.loader = '
                'calmjs.loaderplugin:ModuleLoaderRegistry',
            ]},
            dist=Distribution(project_name='calmjs.testing', version='0.0')
        )
        stub_mod_working_set(self, [calmjs.base], working_set)

        # Not going to use the global registry, and using our custom
        # reservation entry
        local_root_registry = Registry(
            __name__, 'calmjs.testing', _working_set=working_set)

        with pretty_logging(stream=StringIO()):
            # silences "distribution 'calmjs.testing 0.0' not found"
            # warnings from stdout produced by the indexer, as the
            # provided working_set is invalid with entry points that do
            # not have a valid distribution.
            module_registry = root_registry_get('calmjs.module')
            module_loader_registry = root_registry_get('calmjs.module.loader')
            registry = local_root_registry.get_record('calmjs.module')
            loader_registry = local_root_registry.get_record(
                'calmjs.module.loader')

        self.assertIsNot(registry, module_registry)
        self.assertIsNot(loader_registry, module_loader_registry)
        self.assertEqual(
            sorted(k for k, v in registry.iter_records()), [
                'calmjs.testing.module4',
            ]
        )

        # test the basic items.
        results = registry.get_records_for_package('calmjs.testing')
        self.assertEqual(sorted(results.keys()), [
           'calmjs/testing/module4/widget',
        ])

        module4 = registry.get_record('calmjs.testing.module4')
        self.assertIn('calmjs/testing/module4/widget', module4)

        self.assertEqual({
            'css!calmjs/testing/module4/widget.style': resource_filename(
                'calmjs.testing', join('module4', 'widget.style')),
        }, loader_registry.get_records_for_package('calmjs.testing'))

        self.assertEqual(
            ['css'],
            loader_registry.get_loaders_for_package('calmjs.testing')
        )
Ejemplo n.º 28
0
    def test_export_config_rules(self):
        config = configuration.WebpackConfig(module={
            "rules": [],
        }, )
        # the disabling rule gets injected
        with pretty_logging(stream=StringIO()) as fd:
            self.assertIn('type: "javascript/auto"', str(config))
        self.assertIn(
            'INFO calmjs.webpack.configuration disabling default json '
            'loader module rule for webpack 4.0.0', fd.getvalue())

        # downgrade webpack version
        config['__webpack_target__'] = (2, 6, 1)
        with pretty_logging(logger='calmjs.webpack', stream=StringIO()) as fd:
            self.assertNotIn('type: "javascript/auto"', str(config))

        self.assertEqual('', fd.getvalue())
Ejemplo n.º 29
0
 def test_sorted_case_insensitivity(self):
     parser = argparse.ArgumentParser(formatter_class=SortedHelpFormatter,
                                      add_help=False)
     parser.add_argument('-z', '--zebra', help='make zebras')
     parser.add_argument('-a', '--alpaca', help='make alpacas')
     parser.add_argument('-A', '--anteater', help='make anteater')
     parser.add_argument('-S', '--SNAKE', help='make snake')
     parser.add_argument('-s', '--sheep', help='make sheep')
     parser.add_argument('-g', '--goat', help='make goats')
     stream = StringIO()
     parser.print_help(file=stream)
     options = [
         line.split()[0] for line in stream.getvalue().splitlines()
         if '--' in line
     ]
     # the case is unspecified due to in-place sorting
     self.assertEqual(options, ['-a', '-A', '-g', '-S', '-s', '-z'])
Ejemplo n.º 30
0
 def test_empty_modname_target_to_config_paths(self):
     f = plugin.TextPlugin(None).modname_target_to_config_paths
     with pretty_logging('calmjs.rjs.plugin', stream=StringIO()) as stream:
         self.assertEqual(
             f('text!', 'text!'),
             {'': ''},  # we are following our own rules...
         )
     self.assertEqual(stream.getvalue(), '')
Ejemplo n.º 31
0
 def test_get_modpath_pkg_resources_invalid(self):
     # fake both module and entry point, which will trigger an import
     # error exception internally that gets logged.
     module = ModuleType('nothing')
     ep = pkg_resources.EntryPoint.parse('nothing = nothing')
     with pretty_logging(stream=StringIO()) as fd:
         self.assertEqual([], indexer.modpath_pkg_resources(module, ep))
     self.assertIn("module 'nothing' could not be imported", fd.getvalue())
Ejemplo n.º 32
0
 def test_dict_key_update_overwrite_check_no_update(self):
     a = {}
     a['base_key'] = {'k1': 'v1'}
     mapping = {'k1': 'v1'}
     with pretty_logging(logger='calmjs.rjs', stream=StringIO()) as s:
         utils.dict_key_update_overwrite_check(a, 'base_key', mapping)
     self.assertEqual(s.getvalue(), '')
     self.assertEqual(a['base_key'], {'k1': 'v1'})
Ejemplo n.º 33
0
 def test_sorted_case_insensitivity(self):
     parser = argparse.ArgumentParser(
         formatter_class=SortedHelpFormatter, add_help=False)
     parser.add_argument('-z', '--zebra', help='make zebras')
     parser.add_argument('-a', '--alpaca', help='make alpacas')
     parser.add_argument('-A', '--anteater', help='make anteater')
     parser.add_argument('-S', '--SNAKE', help='make snake')
     parser.add_argument('-s', '--sheep', help='make sheep')
     parser.add_argument('-g', '--goat', help='make goats')
     stream = StringIO()
     parser.print_help(file=stream)
     options = [
         line.split()[0]
         for line in stream.getvalue().splitlines() if
         '--' in line
     ]
     # the case is unspecified due to in-place sorting
     self.assertEqual(options, ['-a', '-A', '-g', '-S', '-s', '-z'])