Ejemplo n.º 1
0
 def test_parse(self):
     text = "process.stdout.write('hello world');"
     tree = ecma.parse(text)
     parser = ecma._parser
     self.assertEqual(text, tree.to_ecma())
     ecma.parse(text)
     # the parser is not mutated.
     self.assertIs(parser, ecma._parser)
Ejemplo n.º 2
0
def generate_test(name, mold_id, test_module_ns, data_module):
    """
    name
        Name of the TestCase subclass to create

    mold_id
        The mold_id to test

    test_module_ns
        The test module name to import the source data from

    data_module
        The name of the CommonJS module that exports the JSON to test
        with within the test_module_ns
    """
    def create_test_method(data, answer):
        def _method(self):
            raw = engine.execute(mold_id, data=data)
            self.assertEqual(reconstitute(answer),
                             reconstitute(raw.splitlines()))

        return _method

    with open(resource_filename(test_module_ns, data_module + '.js')) as fd:
        data = json.loads(
            parse(fd.read()).children()[0].children()[0].initializer.to_ecma())

    attrs = {
        'maxDiff': None,
    }
    attrs.update({
        'test_' + t_name: create_test_method(*values)
        for t_name, values in data.items()
    })
    return type(name, (unittest.TestCase, ), attrs)
Ejemplo n.º 3
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.º 4
0
def extract_all_amd_requires(text):
    """
    Extract all require and define calls from unbundled JavaScript
    source files in both AMD and CommonJS syntax.
    """

    f_names = ('require', 'define',)
    # reserved modules
    define_wrapped = dict(enumerate(('require', 'exports', 'module',)))
    reserved = ['module']

    def visit(node):
        for child in node:
            if isinstance(child, ast.FunctionCall) and isinstance(
                    child.identifier, ast.Identifier):
                if not child.args:
                    continue

                args = child.args
                # either require or define
                standard_amd = ((
                    len(child.args) >= 2 and
                    isinstance(args[0], ast.Array) and
                    isinstance(args[1], ast.FuncExpr) and
                    child.identifier.value in f_names
                ), 0)
                # only for define
                named_define = ((
                    len(child.args) >= 3 and
                    isinstance(args[0], ast.String) and
                    isinstance(args[1], ast.Array) and
                    isinstance(args[2], ast.FuncExpr) and
                    child.identifier.value == 'define'
                ), 1)

                if (isinstance(args[0], ast.String) and
                        child.identifier.value == 'require'):
                    # only yield names just from require
                    yield to_str(args[0])
                    continue

                for checks in (standard_amd, named_define):
                    cond, pos = checks
                    if not cond:
                        continue

                    for i, node in enumerate(child.args[pos]):
                        if isinstance(node, ast.String):
                            result = to_str(node)
                            if ((result not in reserved) and (
                                    result != define_wrapped.get(i))):
                                yield result

            # yield from visit(child)
            for value in visit(child):
                yield value

    tree = parse(text)
    return visit(tree)
Ejemplo n.º 5
0
    def setUpClass(cls):
        if cls.test_examples is NotImplemented:
            raise ValueError(
                'the class must define the test_examples attribute for data')

        with open(resource_filename(cls.test_module_name,
                                    cls.test_examples)) as fd:
            cls.data = json.loads(
                parse(fd.read()).children()[0].children()
                [0].initializer.to_ecma())
Ejemplo n.º 6
0
def extract_function_argument(text, f_name, f_argn, f_argt=ast.String):
    """
    Extract a specific argument from a specific function name.

    Arguments:

    text
        The source text.
    f_name
        The name of the function
    f_argn
        The argument number
    f_argt
        The argument type from slimit.ast; default: slimit.ast.String
    """

    tree = parse(text)
    return list(extract_function_argument_visitor(
        tree, f_name, f_argn, f_argt))
Ejemplo n.º 7
0
    def assemble_spec_config(self, **kw):
        # for the assemble related tests.
        tmpdir = utils.mkdtemp(self)
        build_dir = utils.mkdtemp(self)
        rjs = toolchain.RJSToolchain()

        export_target = join(build_dir, 'export.js')
        build_manifest_path = join(build_dir, 'build.js')
        node_config_js = join(build_dir, 'node_config.js')
        requirejs_config_js = join(build_dir, 'requirejs_config.js')

        with open(join(tmpdir, 'r.js'), 'w'):
            pass

        with open(join(build_dir, 'module1.js'), 'w') as fd:
            fd.write("define(['jquery', 'underscore', 'some.pylike.module'], "
                     "function(jquery, underscore, module) {"
                     "});")

        with open(join(build_dir, 'module2.js'), 'w') as fd:
            fd.write("define(['module1', 'underscore'], "
                     "function(module1, underscore) {"
                     "});")

        with open(join(build_dir, 'module3.js'), 'w') as fd:
            fd.write("'use strict';\n"
                     "var $ = require('jquery');\n"
                     "var _ = require('underscore');\n"
                     "var module2 = require('module2');\n")

        spec = Spec(
            build_dir=build_dir,
            export_target=export_target,
            build_manifest_path=build_manifest_path,
            node_config_js=node_config_js,
            requirejs_config_js=requirejs_config_js,
            transpiled_modpaths={
                'module1': 'module1',
                'module2': 'module2',
                'module3': 'module3',
            },
            # these are not actually transpiled sources, but will fit
            # with the purposes of this test.
            transpiled_targets={
                'module1': 'module1.js',
                'module2': 'module2.js',
                'module3': 'module3.js',
            },
            # the "bundled" names were specified to be omitted.
            bundled_modpaths={},
            bundled_targets={},
            plugins_modpaths={},
            plugins_targets={},
            export_module_names=['module1', 'module2', 'module3'],
            **kw)
        spec[rjs.rjs_bin_key] = join(tmpdir, 'r.js')
        rjs.assemble(spec)

        # the main config file
        # check that they all exists
        self.assertTrue(exists(build_manifest_path))
        self.assertTrue(exists(node_config_js))
        self.assertTrue(exists(requirejs_config_js))

        # only checking the build_manifest version, as the node config
        # version is not that much different.
        with open(build_manifest_path) as fd:
            build_tree = parse(fd.read())

        # this is the node for the json in the build file
        build_js = json.loads(build_tree.children()[0].children()[0].to_ecma())

        with open(requirejs_config_js) as fd:
            config_tree = parse(fd.read())

        # this is the node for json in the config file
        config_js = json.loads(
            config_tree.children()[0].children()[0].children()[0].children()
            [2].children()[0].children()[1].to_ecma())

        return build_js, config_js
Ejemplo n.º 8
0
 def append_tree(path, text):
     items.append((path, parse(text)))
Ejemplo n.º 9
0
def extract_defines_with_deps(text):
    tree = parse(text)
    return list(extract_defines_with_deps_visitor([('<text>', tree)]))