Exemplo n.º 1
0
 def test_global_and_nonlocal(self):
     assert py2js('nonlocal foo;foo = 3').strip() == 'foo = 3;'
     assert py2js('global foo;foo = 3').strip() == 'foo = 3;'
     
     def func1():
         def inner():
             x = 3
         x = 2
         inner()
         return x
     
     def func2():
         def inner():
             global x
             x = 3
         x = 2
         inner()
         return x
     
     def func3():
         def inner():
             nonlocal x
             x = 3
         x = 2
         inner()
         return x
     
     assert evaljs(py2js(func1)+'func1()') == '2'
     assert evaljs(py2js(func2)+'func2()') == '3'
     assert evaljs(py2js(func3)+'func3()') == '3'
Exemplo n.º 2
0
    def test_comparisons(self):

        assert py2js("4 > 3") == "4 > 3;"
        assert py2js("4 is 3") == "4 === 3;"

        assert evalpy("4 > 4") == "false"
        assert evalpy("4 >= 4") == "true"
        assert evalpy("4 < 3") == "false"
        assert evalpy("4 <= 4") == "true"
        assert evalpy("4 == 3") == "false"
        assert evalpy("4 != 3") == "true"

        assert evalpy('4 == "4"') == "true"  # yuck!
        assert evalpy('4 is "4"') == "false"
        assert evalpy('4 is not "4"') == "true"

        assert evalpy('"c" in "abcd"') == "true"
        assert evalpy('"x" in "abcd"') == "false"
        assert evalpy('"x" not in "abcd"') == "true"

        assert evalpy("3 in [1,2,3,4]") == "true"
        assert evalpy("9 in [1,2,3,4]") == "false"
        assert evalpy("9 not in [1,2,3,4]") == "true"

        assert evalpy('"bar" in {"foo": 3}') == "false"
        assert evalpy('"foo" in {"foo": 3}') == "true"

        # was a bug
        assert evalpy("not (1 is null and 1 is null)") == "true"
Exemplo n.º 3
0
 def test_comparisons(self):
     
     assert py2js('4 > 3') == '4 > 3;'
     assert py2js('4 is 3') == '4 === 3;'
     
     assert evalpy('4 > 4') == 'false'
     assert evalpy('4 >= 4') == 'true'
     assert evalpy('4 < 3') == 'false'
     assert evalpy('4 <= 4') == 'true'
     assert evalpy('4 == 3') == 'false'
     assert evalpy('4 != 3') == 'true'
     
     assert evalpy('4 == "4"') == 'true'  # yuck!
     assert evalpy('4 is "4"') == 'false'
     assert evalpy('4 is not "4"') == 'true'
     
     assert evalpy('"c" in "abcd"') == 'true'
     assert evalpy('"x" in "abcd"') == 'false'
     assert evalpy('"x" not in "abcd"') == 'true'
     
     assert evalpy('3 in [1,2,3,4]') == 'true'
     assert evalpy('9 in [1,2,3,4]') == 'false'
     assert evalpy('9 not in [1,2,3,4]') == 'true'
     
     assert evalpy('"bar" in {"foo": 3}') == 'false'
     assert evalpy('"foo" in {"foo": 3}') == 'true'
     
     # was a bug
     assert evalpy('not (1 is null and 1 is null)') == 'true'
Exemplo n.º 4
0
 def test_import(self):
     with raises(JSError):
         py2js('import time')
     
     # But we do support special time funcs
     import time
     assert abs(float(evalpy('time()')) - time.time()) < 0.5
     evalpy('t0=perf_counter(); t1=perf_counter(); (t1-t0)').startswith('0.0')
Exemplo n.º 5
0
 def test_raw_js_overloading(self):
     # more RawJS tests in test_parser3.py
     s1 = 'a=3; b=4; c=1; a + b - c'
     s2 = 'a=3; b=4; c=1; RawJS("a + b") - c'
     assert evalpy(s1) == '6'
     assert evalpy(s2) == '6'
     assert 'pyfunc' in py2js(s1)
     assert 'pyfunc' not in py2js(s2)
Exemplo n.º 6
0
 def test_funcion_call(self):
     jscode = 'var foo = function (x, y) {return x+y;};'
     assert evaljs(jscode + py2js('foo(2,2)')) == '4'
     assert evaljs(jscode + py2js('foo("so ", True)')) == 'so true'
     assert evaljs(jscode + py2js('a=[1,2]; foo(*a)')) == '3'
     
     # Test super (is tested for real in test_parser3.py
     assert evalpy('d={"_base_class": console};d._base_class.log(4)') == '4'
     assert evalpy('d={"_base_class": console};d._base_class.log()') == ''
Exemplo n.º 7
0
 def test_assert(self):
     
     assert 'throw' in py2js('assert True')
     evalpy('assert true; 7') == '7'
     evalpy('assert true, "msg"; 7') == '7'
     
     catcher = 'try { %s } catch(err) { console.log(err); }'
     assert evaljs(catcher % py2js('assert false')).count('AssertionError')
     assert evaljs(catcher % py2js('assert false, "foo"')).count('foo')
Exemplo n.º 8
0
 def test_inheritance_and_super(self):
     
     class MyClass1:
         def __init__(self):
             self.bar = 7
         def add(self, x=1):
             self.bar += x
         def addTwo(self):
             self.bar += 2
     
     class MyClass2(MyClass1):
         def addTwo(self):
             super().addTwo()
             self.bar += 1  # haha, we add three!
     
     class MyClass3(MyClass2):
         def addTwo(self):
             super().addTwo()
             self.bar += 1  # haha, we add four!
         def addFour(self):
             super().add(4)
     
     code = py2js(MyClass1) + py2js(MyClass2) + py2js(MyClass3)
     code += 'var m1=new MyClass1(), m2=new MyClass2(), m3=new MyClass3();'
     
     # m1
     assert evaljs(code + 'm1.bar;') == '7'
     assert evaljs(code + 'm1.add();m1.bar;') == '8'
     assert evaljs(code + 'm1.addTwo();m1.bar;') == '9'
     # m2
     assert evaljs(code + 'm2.bar;') == '7'
     assert evaljs(code + 'm2.add();m2.bar;') == '8'
     assert evaljs(code + 'm2.addTwo();m2.bar;') == '10'
     # m3
     assert evaljs(code + 'm3.bar;') == '7'
     assert evaljs(code + 'm3.add();m3.bar;') == '8'
     assert evaljs(code + 'm3.addTwo();m3.bar;') == '11'
     assert evaljs(code + 'm3.addFour();m3.bar;') == '11'  # super with args
     
     # Inhertance m1
     assert evaljs(code + 'm1 instanceof MyClass3;') == 'false'
     assert evaljs(code + 'm1 instanceof MyClass2;') == 'false'
     assert evaljs(code + 'm1 instanceof MyClass1;') == 'true'
     assert evaljs(code + 'm1 instanceof Object;') == 'true'
     
     # Inhertance m2
     assert evaljs(code + 'm2 instanceof MyClass3;') == 'false'
     assert evaljs(code + 'm2 instanceof MyClass2;') == 'true'
     assert evaljs(code + 'm2 instanceof MyClass1;') == 'true'
     assert evaljs(code + 'm2 instanceof Object;') == 'true'
     
     # Inhertance m3
     assert evaljs(code + 'm3 instanceof MyClass3;') == 'true'
     assert evaljs(code + 'm3 instanceof MyClass2;') == 'true'
     assert evaljs(code + 'm3 instanceof MyClass1;') == 'true'
     assert evaljs(code + 'm3 instanceof Object;') == 'true'
Exemplo n.º 9
0
 def test_listcomp_regressions(self):
     
     code1 = 'a = [i for i in range(the_iter)]'
     js = py2js(code1)
     assert 'the_iter' in js.meta['vars_unknown']
     assert 'i' not in js.meta['vars_unknown']
     
     code1 = 'corners = [[(p[i] + 0.5) for i in range(3)] for p in corners_local]'
     js = py2js(code1)
     assert 'p' not in js.meta['vars_unknown']
Exemplo n.º 10
0
 def test_isinstance(self):
     # The resulting code is not particularly pretty, so we just
     # test outcome
     
     assert evalpy('isinstance(3.0, list) == True') == 'false'
     assert evalpy('isinstance(3.0, float) == True') == 'true'
     
     assert evalpy('x={}; isinstance(x.foo, "undefined")') == 'true'
     
     assert evalpy('isinstance(None, "null")') == 'true'
     assert evalpy('isinstance(undefined, "undefined")') == 'true'
     #
     assert evalpy('isinstance(None, "undefined")') == 'false'
     assert evalpy('isinstance(undefined, "null")') == 'false'
     
     assert evalpy('isinstance(3, float)') == 'true'
     assert evalpy('isinstance(3, (int, float))') == 'true'
     assert evalpy('isinstance(3, "number")') == 'true'
     #
     #assert evalpy('isinstance(3, int)') == 'false'  # int is not defined
     
     assert evalpy('isinstance("", str)') == 'true'
     assert evalpy('isinstance("", "string")') == 'true'
     #
     assert evalpy('isinstance("", list)') == 'false'
     
     assert evalpy('isinstance(True, bool)') == 'true'
     assert evalpy('isinstance(True, "boolean")') == 'true'
     #
     assert evalpy('isinstance(True, float)') == 'false'
     
     assert evalpy('isinstance([], list)') == 'true'
     assert evalpy('isinstance([], "array")') == 'true'
     #
     assert evalpy('isinstance([], "object")') == 'false'
     assert evalpy('isinstance([], "Object")') == 'false'
     assert evalpy('isinstance([], dict)') == 'false'
     
     assert evalpy('isinstance({}, dict)') == 'true'
     assert evalpy('isinstance({}, "object")') == 'true'
     #
     assert evalpy('isinstance({}, list)') == 'false'
     assert evalpy('isinstance({}, "array")') == 'false'
     
     assert evalpy('isinstance(eval, types.FunctionType)') == 'true'
     assert evalpy('isinstance(eval, FunctionType)') == 'true'
     assert evalpy('isinstance(3, types.FunctionType)') == 'false'
     
     # own class
     code = 'function MyClass () {return this;}\nx = new MyClass();\n'
     assert evaljs(code + py2js('isinstance(x, "object")')) == 'true'
     assert evaljs(code + py2js('isinstance(x, "Object")')) == 'true'
     assert evaljs(code + py2js('isinstance(x, "MyClass")')) == 'true'
     assert evaljs(code + py2js('isinstance(x, MyClass)')) == 'true'
Exemplo n.º 11
0
def test_py2js_on_function():
    
    def foo():
        pass
    
    # normal
    jscode = py2js(foo)
    assert jscode.startswith('var foo')
    assert jscode.meta['pycode'].startswith('def foo')
    
    # renamed
    jscode = py2js(foo, 'bar')
    assert jscode.meta['pycode'].startswith('def foo')
    assert 'foo' not in jscode
    assert jscode.startswith('var bar')
    assert 'bar = function ' in jscode
    
    # renamed 2
    jscode = py2js(foo, 'bar.bla')
    assert jscode.meta['pycode'].startswith('def foo')
    assert 'foo' not in jscode
    assert not 'var bar.bla' in jscode
    assert 'bar.bla = function ' in jscode
    
    
    # Skip decorators
    stub1 = lambda x: x
    stub2 = lambda x=None: stub1
    
    @stub1
    @stub1
    def foo1():
        pass
    
    @stub2(
    )
    def foo2():
        pass
    
    @py2js
    def foo3():
        pass
    
    @py2js(indent=1)
    def foo4():
        pass
    
    assert callable(foo1)
    assert callable(foo2)
    assert py2js(foo1).meta['pycode'].startswith('def foo')
    assert py2js(foo2).meta['pycode'].startswith('def foo')
    assert foo3.startswith('var foo3')
    assert foo4.startswith('    var foo4')
Exemplo n.º 12
0
 def test_nonlocal(self):
     assert py2js('nonlocal foo;foo = 3').strip() == 'foo = 3;'
     
     func3_code = """def func3():
         def inner():
             nonlocal x
             x = 3
         x = 2
         inner()
         return x
     """
     assert evaljs(py2js(func3_code)+'func3()') == '3'
Exemplo n.º 13
0
 def test_assignments(self):
     assert py2js('foo = 3') == 'var foo;\nfoo = 3;'  # with var
     assert py2js('foo.bar = 3') == 'foo.bar = 3;'  # without var
     
     code = py2js('foo = 3; bar = 4')  # define both
     assert code.count('var') == 1
     code = py2js('foo = 3; foo = 4')  # only define first time
     assert code.count('var') == 1
     
     code = py2js('foo = bar = 3')  # multiple assignment
     assert 'foo = bar = 3' in code
     assert 'var bar, foo' in code  # alphabetic order
     
     # self -> this
     assert py2js('self') == 'this;'
     assert py2js('self.foo') == 'this.foo;'
     
     # Indexing
     assert evalpy('a=[0,0]\na[0]=2\na[1]=3\na', False) == '[2,3]'
     
     # Tuple unpacking
     evalpy('x=[1,2,3]\na, b, c = x\nb', False) == '2'
     evalpy('a,b,c = [1,2,3]\nc,b,a = a,b,c\n[a,b,c]', False) == '[3,2,1]'
     
     # Class variables don't get a var
     code = py2js('class Foo:\n  bar=3\n  bar = bar + 1')
     assert code.count('bar') == 3
     assert code.count('Foo.prototype.bar') == 3
Exemplo n.º 14
0
    def test_assignments(self):
        assert py2js("foo = 3") == "var foo;\nfoo = 3;"  # with var
        assert py2js("foo.bar = 3") == "foo.bar = 3;"  # without var

        code = py2js("foo = 3; bar = 4")  # define both
        assert code.count("var") == 1
        code = py2js("foo = 3; foo = 4")  # only define first time
        assert code.count("var") == 1

        code = py2js("foo = bar = 3")  # multiple assignment
        assert "foo = bar = 3" in code
        assert "var bar, foo" in code  # alphabetic order

        # self -> this
        assert py2js("self") == "this;"
        assert py2js("self.foo") == "this.foo;"

        # Indexing
        assert evalpy("a=[0,0]\na[0]=2\na[1]=3\na", False) == "[2,3]"

        # Tuple unpacking
        evalpy("x=[1,2,3]\na, b, c = x\nb", False) == "2"
        evalpy("a,b,c = [1,2,3]\nc,b,a = a,b,c\n[a,b,c]", False) == "[3,2,1]"

        # Class variables don't get a var
        code = py2js("class Foo:\n  bar=3\n  bar = bar + 1")
        assert code.count("bar") == 3
        assert code.count("Foo.prototype.bar") == 3
Exemplo n.º 15
0
def test_py2js_on_function():
    def foo():
        pass

    # normal
    jscode = py2js(foo)
    assert jscode.startswith("var foo")
    assert jscode.pycode.startswith("def foo")

    # renamed
    jscode = py2js(foo, "bar")
    assert jscode.pycode.startswith("def foo")
    assert "foo" not in jscode
    assert jscode.startswith("var bar")
    assert "bar = function " in jscode

    # renamed 2
    jscode = py2js(foo, "bar.bla")
    assert jscode.pycode.startswith("def foo")
    assert "foo" not in jscode
    assert not "var bar.bla" in jscode
    assert "bar.bla = function " in jscode

    # Skip decorators
    stub1 = lambda x: x
    stub2 = lambda x=None: stub1

    @stub1
    @stub1
    def foo1():
        pass

    @stub2()
    def foo2():
        pass

    @py2js
    def foo3():
        pass

    @py2js(indent=1)
    def foo4():
        pass

    assert callable(foo1)
    assert callable(foo2)
    assert py2js(foo1).pycode.startswith("def foo")
    assert py2js(foo2).pycode.startswith("def foo")
    assert foo3.startswith("var foo3")
    assert foo4.startswith("    var foo4")
Exemplo n.º 16
0
def test_stdlib_full_and_partial():
    code = stdlib.get_full_std_lib()
    assert isinstance(code, str)
    assert 'var %shasattr =' % stdlib.FUNCTION_PREFIX in code
    assert 'var %slist =' % stdlib.FUNCTION_PREFIX in code
    assert code.count('var') > 10
    
    code = stdlib.get_partial_std_lib(['hasattr'], [], []) 
    assert isinstance(code, str)
    assert 'var %shasattr =' % stdlib.FUNCTION_PREFIX in code
    assert 'var %slist =' % stdlib.FUNCTION_PREFIX not in code
    assert code.count('var') == 1
    
    assert '_hasattr = function' in py2js('hasattr(x, "foo")')
    assert '_hasattr = function' not in py2js('hasattr(x, "foo")', inline_stdlib=False)
Exemplo n.º 17
0
 def test_while(self):
     
     # Test code output
     line = nowhitespace(py2js('while(True): pass'))
     assert line == 'while(true){}'
     line = nowhitespace(py2js('while(not ok): pass'))
     assert 'while' in line
     
     # Test break and continue
     for9 = 'i=-1\nwhile(i<8):\n  i+=1\n  '
     assert evalpy(for9 + 'if i==4:break\n  print(i)\n0') == '0\n1\n2\n3\n0'
     assert evalpy(for9 + 'if i<6:continue\n  print(i)\n0') == '6\n7\n8\n0'
     # Test else
     assert evalpy(for9 + 'if i==3:break\nelse: print(99)\n0') == '0'
     assert evalpy(for9 + 'if i==30:break\nelse: print(99)\n0') == '99\n0'
Exemplo n.º 18
0
    def test_basic_types(self):
        assert py2js("True") == "true;"
        assert py2js("False") == "false;"
        assert py2js("None") == "null;"

        assert py2js('"bla\\"bla"') == "'bla\"bla';"
        assert py2js("3") == "3;"
        assert py2js("3.1415") == "3.1415;"

        assert py2js("[1,2,3]") == "[1, 2, 3];"
        assert py2js("(1,2,3)") == "[1, 2, 3];"
        assert py2js("{foo: 3, bar: 4}") == "{foo: 3, bar: 4};"
Exemplo n.º 19
0
 def test_basic_types(self):
     assert py2js('True') == 'true;'
     assert py2js('False') == 'false;'
     assert py2js('None') == 'null;'
     
     assert py2js('"bla\\"bla"') == '"bla\\"bla";'
     assert py2js('3') == '3;'
     assert py2js('3.1415') == '3.1415;'
     
     assert py2js('[1,2,3]') == '[1, 2, 3];'
     assert py2js('(1,2,3)') == '[1, 2, 3];'
     assert py2js('{foo: 3, bar: 4}') == '{foo: 3, bar: 4};'
Exemplo n.º 20
0
    def test_self_becomes_this(self):
        def func(self):
            return self.foo

        code = py2js(func)
        lines = [line.strip() for line in code.split('\n') if line]
        assert 'return this.foo;' in lines
Exemplo n.º 21
0
    def test_scope(self):
        def func(self):
            def foo(z):
                y = 2
                stub = False  # noqa
                only_here = 1  # noqa
                return x + y + z

            x = 1
            y = 0
            y = 1  # noqa
            z = 1  # noqa
            res = foo(3)
            stub = True  # noqa
            return res + y  # should return 1+2+3+1 == 7

        # Find function start
        code = py2js(func)
        i = code.splitlines().index('var func;')
        assert i >= 0

        # Find first lines of functions, where the vars are defined
        vars1 = code.splitlines()[i + 2]
        vars2 = code.splitlines()[i + 4]
        assert vars1.strip().startswith('var ')
        assert vars2.strip().startswith('var ')

        assert 'y' in vars1 and 'y' in vars2
        assert 'stub' in vars1 and 'stub' in vars2
        assert 'only_here' in vars2 and 'only_here' not in vars1
        assert evaljs(code + 'func()') == '7'
Exemplo n.º 22
0
    def test_bound_funcs_in_methods(self):
        class MyClass16:
            def foo1(self):
                self.a = 3
                f = lambda i: self.a
                return f()

            def foo2(self):
                self.a = 3

                def bar():
                    return self.a

                return bar()

            def foo3(self):
                self.a = 3

                def bar(self):
                    return self.a

                return bar()

        code = py2js(MyClass16)
        assert evaljs(code + 'var m = new MyClass16(); m.foo1()') == '3'
        assert evaljs(code + 'var m = new MyClass16(); m.foo2()') == '3'
        assert evaljs(
            code +
            'var m = new MyClass16(); try {m.foo3();} catch (err) {"ok"}'
        ) == 'ok'
Exemplo n.º 23
0
 def test_scope(self):
     
     def func(self):
         def foo(z):
             y = 2
             stub = False  # noqa
             only_here = 1  # noqa
             return x + y + z
         x = 1
         y = 0
         y = 1  # noqa
         z = 1  # noqa
         res = foo(3)
         stub = True  # noqa
         return res + y  # should return 1+2+3+1 == 7
     
     # Find function start
     code = py2js(func)
     i = code.splitlines().index('var func;')
     assert i >= 0
     
     # Find first lines of functions, where the vars are defined
     vars1 = code.splitlines()[i+2]
     vars2 = code.splitlines()[i+4]
     assert vars1.strip().startswith('var ')
     assert vars2.strip().startswith('var ')
     
     assert 'y' in vars1 and 'y' in vars2
     assert 'stub' in vars1 and 'stub' in vars2
     assert 'only_here' in vars2 and 'only_here' not in vars1
     assert evaljs(code + 'func()') == '7'
Exemplo n.º 24
0
def py2js_tickformatter(formatter, msg=''):
    """
    Uses flexx.pyscript to compile a python tick formatter to JS code
    """
    try:
        from flexx.pyscript import py2js
    except ImportError:
        param.main.param.warning(
            msg+'Ensure Flexx is installed ("conda install -c bokeh flexx" '
            'or "pip install flexx")')
        return
    try:
        jscode = py2js(formatter, 'formatter')
    except Exception as e:
        error = 'Pyscript raised an error: {0}'.format(e)
        error = error.replace('%', '%%')
        param.main.param.warning(msg+error)
        return

    args = _getargspec(formatter).args
    arg_define = 'var %s = tick;' % args[0] if args else ''
    return_js = 'return formatter();\n'
    jsfunc = '\n'.join([arg_define, jscode, return_js])
    match = re.search('(formatter \= function \(.*\))', jsfunc )
    return jsfunc[:match.start()] + 'formatter = function ()' + jsfunc[match.end():]
Exemplo n.º 25
0
    def __init__(self, data, callback, popup=None):
        from jinja2 import Template
        super(MarkerClusterScript, self).__init__([])
        self._name = 'Density'
        self._data = data
        self._popup = popup
        if callable(callback):
            from flexx.pyscript import py2js
            self._callback = py2js(callback, new_name="callback")
        else:
            self._callback = "var callback = {};".format(_callback)

        self._template = Template(u"""
            {% macro script(this, kwargs) %}
            (function(){
                var data = {{this._data}};
                var map = {{this._parent.get_name()}};
                var cluster = L.markerClusterGroup();
                {{this._callback}}

                for (var i = 0; i < data.length; i++) {
                    var row = data[i];
                    var marker = callback(row, popup='names');
                    marker.addTo(cluster);
                }

                cluster.addTo(map);
            })();
            {% endmacro %}
                        """)
Exemplo n.º 26
0
def py2js_tickformatter(formatter, msg=''):
    """
    Uses flexx.pyscript to compile a python tick formatter to JS code
    """
    try:
        from flexx.pyscript import py2js
    except ImportError:
        param.main.warning(msg + 'Ensure Flexx is installed '
                           '("conda install -c bokeh flexx" or '
                           '"pip install flexx")')
        return
    try:
        jscode = py2js(formatter, 'formatter')
    except Exception as e:
        error = 'Pyscript raised an error: {0}'.format(e)
        error = error.replace('%', '%%')
        param.main.warning(msg + error)
        return

    args = inspect.getargspec(formatter).args
    arg_define = 'var %s = tick;' % args[0] if args else ''
    return_js = 'return formatter();\n'
    jsfunc = '\n'.join([arg_define, jscode, return_js])
    match = re.search('(function \(.*\))', jsfunc)
    return jsfunc[:match.start()] + 'function ()' + jsfunc[match.end():]
Exemplo n.º 27
0
 def test_scope(self):
     
     def func(self):
         def foo(z):
             y = 2
             stub = False  # noqa
             only_here = 1  # noqa
             return x + y + z
         x = 1
         y = 0
         y = 1  # noqa
         z = 1  # noqa
         res = foo(3)
         stub = True  # noqa
         return res + y  # should return 1+2+3+1 == 7
     
     code = py2js(func)
     vars1 = code.splitlines()[2]
     vars2 = code.splitlines()[4]
     assert vars1.strip().startswith('var ')
     assert vars2.strip().startswith('var ')
     
     assert 'y' in vars1 and 'y' in vars2
     assert 'stub' in vars1 and 'stub' in vars2
     assert 'only_here' in vars2 and 'only_here' not in vars1
     assert evaljs(code + 'func()') == '7'
Exemplo n.º 28
0
 def test_var_args2(self):
     
     def func(self, foo, *args):
         return args
     
     code1 = py2js(func)
     #lines = [line for line in code1.split('\n') if line]
     
     code2 = py2js('func(0, 2, 3)')
     assert evaljs(code1 + code2, False) == '[2,3]'
     code2 = py2js('func(0)')
     assert evaljs(code1 + code2, False) == '[]'
     code2 = py2js('a=[0,2,3]\nfunc(*a)')
     assert evaljs(code1 + code2, False) == '[2,3]'
     code2 = py2js('a=[2,3]\nfunc(0,1,2,*a)')
     assert evaljs(code1 + code2, False) == '[1,2,2,3]'
Exemplo n.º 29
0
 def test_func1(self):
     code = py2js(func1)
     lines = [line for line in code.split('\n') if line]
     
     assert len(lines) == 4  # only three lines + definition
     assert lines[1] == 'func1 = function flx_func1 () {'  # no args
     assert lines[2].startswith('  ')  # indented
     assert lines[3] == '};'  # dedented
Exemplo n.º 30
0
 def test_bound_methods(self):
     
     class MyClass14:
         def __init__(self):
             self.a = 1
         def add2(self):
             self.a += 2
     
     class MyClass15(MyClass14):
         def add3(self):
             self.a += 3
     
     code = py2js(MyClass14) + py2js(MyClass15)
     assert evaljs(code + 'var m = new MyClass14(); m.add2(); m.add2(); m.a') == '5'
     assert evaljs(code + 'var m = new MyClass14(); var f = m.add2; f(); f(); m.a') == '5'
     assert evaljs(code + 'var m = new MyClass15(); var f = m.add3; f(); f(); m.a') == '7'
     assert evaljs(code + 'var m = new MyClass15(); var f2 = m.add2, f3 = m.add3; f2(); f3(); m.a') == '6'
Exemplo n.º 31
0
 def test_method1(self):
     code = py2js(self.method1)
     lines = [line for line in code.split('\n') if line]
     
     assert len(lines) == 4  # only three lines + definition
     assert lines[1] == 'method1 = function () {'  # no args, no self/this
     assert lines[2].startswith('  ')  # indented
     assert lines[3] == '};'  # dedented
Exemplo n.º 32
0
 def test_bound_methods(self):
     
     class MyClass14:
         def __init__(self):
             self.a = 1
         def add2(self):
             self.a += 2
     
     class MyClass15(MyClass14):
         def add3(self):
             self.a += 3
     
     code = py2js(MyClass14) + py2js(MyClass15)
     assert evaljs(code + 'var m = new MyClass14(); m.add2(); m.add2(); m.a') == '5'
     assert evaljs(code + 'var m = new MyClass14(); var f = m.add2; f(); f(); m.a') == '5'
     assert evaljs(code + 'var m = new MyClass15(); var f = m.add3; f(); f(); m.a') == '7'
     assert evaljs(code + 'var m = new MyClass15(); var f2 = m.add2, f3 = m.add3; f2(); f3(); m.a') == '6'
Exemplo n.º 33
0
 def test_method1(self):
     code = py2js(self.method1)
     lines = [line for line in code.split('\n') if line]
     
     assert len(lines) == 4  # only three lines + definition
     assert lines[1] == 'method1 = function () {'  # no args, no self/this
     assert lines[2].startswith('  ')  # indented
     assert lines[3] == '};'  # dedented
Exemplo n.º 34
0
 def test_self_becomes_this(self):
     
     def func(self):
         return self.foo
     
     code = py2js(func)
     lines = [line.strip() for line in code.split('\n') if line]
     assert 'return this.foo;' in lines
Exemplo n.º 35
0
 def test_func1(self):
     code = py2js(func1)
     lines = [line for line in code.split('\n') if line]
     
     assert len(lines) == 4  # only three lines + definition
     assert lines[1] == 'func1 = function flx_func1 () {'  # no args
     assert lines[2].startswith('  ')  # indented
     assert lines[3] == '};'  # dedented
Exemplo n.º 36
0
 def test_var_args2(self):
     
     @js
     def func(self, foo, *args):
         return args
     
     code1 = 'var x = ' + func.jscode
     lines = [line for line in code1.split('\n') if line]
     
     code2 = py2js('x(0, 2, 3)')
     assert evaljs(code1 + code2, False) == '[2,3]'
     code2 = py2js('x(0)')
     assert evaljs(code1 + code2, False) == '[]'
     code2 = py2js('a=[0,2,3]\nx(*a)')
     assert evaljs(code1 + code2, False) == '[2,3]'
     code2 = py2js('a=[2,3]\nx(0,1,2,*a)')
     assert evaljs(code1 + code2, False) == '[1,2,2,3]'
Exemplo n.º 37
0
 def test_scope2(self):
     # Avoid regression for bug with lambda and scoping
     
     def func1(self):
         x = 1
     
     def func2(self):
         x = 1
         y = lambda : None
     
     def func3(self):
         x = 1
         def y():
             pass
     
     assert 'var x' in py2js(func1)
     assert 'var x' in py2js(func2)
     assert 'var x' in py2js(func3)
Exemplo n.º 38
0
 def test_when_funcs_do_parse_kwargs(self):
     
     # We do for **kwargs
     code = py2js('def foo(a, **c): pass')
     assert 'parse_kwargs' in code
     assert 'kw_values' not in code
     
     # We do for keyword only args
     if sys.version_info > (3, ):
         code = py2js('def foo(a, *, b=1, c="foo"): pass')
         assert 'parse_kwargs' in code
         assert 'kw_values' in code
     
     # We do for keyword only args and **kwargs
     if sys.version_info > (3, ):
         code = py2js('def foo(a, *, b=1, c="foo", **d): pass')
         assert 'parse_kwargs' in code
         assert 'kw_values' in code
Exemplo n.º 39
0
 def test_rawJS(self):
     
     code = py2js(foo)
     assert 'pyfunc' not in code
     assert '    x =' in code
     assert '    for' in code
     assert '        y +=' in code
     assert '    while' in code
     assert '        y -=' in code
Exemplo n.º 40
0
 def test_scope2(self):
     # Avoid regression for bug with lambda and scoping
     
     def func1(self):
         x = 1
     
     def func2(self):
         x = 1
         y = lambda : None
     
     def func3(self):
         x = 1
         def y():
             pass
     
     assert 'var x' in py2js(func1)
     assert 'var x' in py2js(func2)
     assert 'var x' in py2js(func3)
Exemplo n.º 41
0
def test_dotted_unknowns():
    
    def func1():
        x = ui._layouts.SomeLayout()
        y = ui.SomeLayout.YYY
        z = ui.SomeOtherLayout
    
    js = py2js(func1)
    assert js.meta['vars_unknown'] == set(['ui._layouts.SomeLayout', 'ui.SomeLayout.YYY', 'ui.SomeOtherLayout'])
Exemplo n.º 42
0
    def test_catching2(self):
        def catchtest(x):
            try:
                raise ValueError('foo')
            except Exception as err:
                print(err.message)
            return undefined

        assert evaljs(py2js(catchtest, 'f') + 'f(1)').endswith('foo')
Exemplo n.º 43
0
 def test_catching2(self):
     
     def catchtest(x):
         try:
             raise ValueError('foo')
         except Exception as err:
             print(err.message)
     
     assert evaljs(py2js(catchtest, 'f') + 'f(1)').endswith('foo')
Exemplo n.º 44
0
 def test_with_exception(self):
     
     def contexttest(x):
         c = dict(__enter__=lambda: print('enter'),
                  __exit__=lambda et, ev, tb: print(et))
         try:
             with c:
                 print(42)
                 if x != 1:
                     raise AttributeError('fooerror')
                 print(43)
         except Exception as e:
             print(e.message)
         print('.')
         return undefined
     
     assert evaljs(py2js(contexttest, 'f') + 'f(1)') == 'enter\n42\n43\nnull\n.'
     s = 'enter\n42\nAttributeError\nAttributeError: fooerror\n.'
     assert evaljs(py2js(contexttest, 'f') + 'f(0)') == s
Exemplo n.º 45
0
 def test_assert_catch(self):
     
     def catchtest(x):
         try:
             assert False
         except AssertionError:
             print('assertion-error')
         return undefined
     
     assert evaljs(py2js(catchtest, 'f') + 'f(1)') == 'assertion-error'
Exemplo n.º 46
0
    def test_inheritance_super_more(self):
        class MyClass4:
            def foo(self):
                return self

        class MyClass5(MyClass4):
            def foo(self, test):
                return super().foo()

        def foo():
            return super().foo()

        code = py2js(MyClass4) + py2js(MyClass5)
        code += py2js(foo).replace('super()', 'MyClass4.prototype')
        code += 'var m4=new MyClass4(), m5=new MyClass5();'

        assert evaljs(code + 'm4.foo() === m4') == 'true'
        assert evaljs(code + 'm4.foo() === m4') == 'true'
        assert evaljs(code + 'foo.call(m4) === m4') == 'true'
Exemplo n.º 47
0
 def test_ensure_use_new(self):
     class MyClass13:
         def __init__(self):
            pass
     code = py2js(MyClass13)
     err = 'Class constructor is called as a function.'
     assert evaljs(code + 'try { var m = new MyClass13(); "ok"} catch (err) { err; }') == 'ok'
     assert evaljs(code + 'try { var m = MyClass13();} catch (err) { err; }') == err
     assert evaljs(code + 'try { MyClass13.apply(global);} catch (err) { err; }') == err
     assert evaljs(code + 'var window = global;try { MyClass13.apply(window);} catch (err) { err; }') == err
Exemplo n.º 48
0
 def test_instantiation(self):
     # Test creating instances
     assert 'new' in py2js('a = Foo()')
     assert 'new' in py2js('a = x.Foo()')
     assert 'new' not in py2js('a = foo()')
     assert 'new' not in py2js('a = _foo()')
     assert 'new' not in py2js('a = _Foo()')
     assert 'new' not in py2js('a = this.Foo()')
     assert 'new' not in py2js('a = JSON.stringify(x)')
     
     jscode = 'function Foo() {this.x = 3}\nx=1;\n'
     assert evaljs(jscode + py2js('a=Foo()\nx')) == '1'
Exemplo n.º 49
0
 def test_raise(self):
     
     assert 'throw' in py2js('raise MyException("foo")')
     assert 'MyException' in py2js('raise MyException("foo")')
     assert 'foo' in py2js('raise MyException("foo")')
     
     catcher = 'try { %s } catch(err) { console.log(err); }'
     assert evaljs(catcher % py2js('raise "foo"')) == 'foo'
     assert evaljs(catcher % py2js('raise 42')) == '42'
     assert evaljs(catcher % py2js('raise ValueError')).count('ValueError')
     assert evaljs(catcher % py2js('raise ValueError("foo")')).count('foo')
     assert evaljs(catcher % py2js('xx = "bar"; raise xx;')).count('bar')
Exemplo n.º 50
0
def test_functickformatter_from_py_func():
    def convert_to_minutes(seconds):
        return seconds * 60

    formatter = FuncTickFormatter.from_py_func(convert_to_minutes)
    js_code = pyscript.py2js(convert_to_minutes, 'formatter')

    function_wrapper = formatter.code.replace(js_code, '')

    assert function_wrapper == "function (seconds) {return formatter(seconds)};"
Exemplo n.º 51
0
def test_raw_js():
    def func(a, b):
        """
        var c = 3;
        return a + b + c;
        """

    code = py2js(func)
    assert evaljs(code + 'func(100, 10)') == '113'
    assert evaljs(code + 'func("x", 10)') == 'x103'
Exemplo n.º 52
0
def test_js():

    code = py2js(Serializer)
    code += py2js(Foo)

    code += 'var serializer = new Serializer();\n'
    code += 'var foo1 = new Foo(42), foo2 = new Foo(7), foo3 = new Foo(null);\n'
    code += 'var s1 = {"a": foo1, "b": [foo2, foo3]};\n'
    code += 'var text = serializer.saves(s1);\n'
    code += 'var s2 = serializer.loads(text);\n'
    code += 'text + "|" + (s2.a.val + s2.b[0].val);\n'

    result = evaljs(code)
    text, res = result.split('|')

    s3 = serializer.loads(text)

    assert s1 == s3
    assert res == '49'
Exemplo n.º 53
0
 def test_if(self):
     # Normal if
     assert evalpy('if True: 4\nelse: 5') == '4'
     assert evalpy('if False: 4\nelse: 5') == '5'
     assert evalpy('x=4\nif x>3: 13\nelif x > 2: 12\nelse: 10') == '13'
     assert evalpy('x=3\nif x>3: 13\nelif x > 2: 12\nelse: 10') == '12'
     assert evalpy('x=1\nif x>3: 13\nelif x > 2: 12\nelse: 10') == '10'
     
     # One-line if
     line = py2js('3 if True else 4').replace(')', '').replace('(', '')
     assert line == 'true? 3 : 4;'
     #
     assert evalpy('4 if True else 5') == '4'
     assert evalpy('4 if False else 5') == '5'
     assert evalpy('3+1 if 0+2/1 else 4+1') == '4'
     assert evalpy('3+1 if 4/2-2 else 4+1') == '5'
     
     # If with this_is_js()
     assert '5' in py2js('if this_is_js_xx(): 4\nelse: 5')
     assert '5' not in py2js('if this_is_js(): 4\nelse: 5')
Exemplo n.º 54
0
 def test_with_simple(self):
     
     def contexttest():
         c = dict(__enter__=lambda: print('enter'),
                  __exit__=lambda: print('exit'))
         with c:
             print(42)
         print('.')
         return undefined
     
     assert evaljs(py2js(contexttest, 'f') + 'f()') == 'enter\n42\nexit\n.'
Exemplo n.º 55
0
 def test_global(self):
     assert py2js('global foo;foo = 3').strip() == 'foo = 3;'
     
     def func1():
         def inner():
             x = 3
         x = 2
         inner()
         return x
     
     def func2():
         def inner():
             global x
             x = 3
         x = 2
         inner()
         return x
 
     assert evaljs(py2js(func1)+'func1()') == '2'
     assert evaljs(py2js(func2)+'func2()') == '3'
Exemplo n.º 56
0
    def test_catching(self):
        def catchtest(x):
            try:
                if x == 1:
                    raise ValueError('foo')
                elif x == 2:
                    raise RuntimeError('foo')
                else:
                    raise "oh crap"
            except ValueError:
                print('value-error')
            except RuntimeError:
                print('runtime-error')
            except Exception:
                print('other-error')
            return undefined

        assert evaljs(py2js(catchtest, 'f') + 'f(1)') == 'value-error'
        assert evaljs(py2js(catchtest, 'f') + 'f(2)') == 'runtime-error'
        assert evaljs(py2js(catchtest, 'f') + 'f(3)') == 'other-error'
Exemplo n.º 57
0
    def test_basic_types(self):
        assert py2js('True') == 'true;'
        assert py2js('False') == 'false;'
        assert py2js('None') == 'null;'

        assert py2js('"bla\\"bla"') == '"bla\\"bla";'
        assert py2js('3') == '3;'
        assert py2js('3.1415') == '3.1415;'

        assert py2js('[1,2,3]') == '[1, 2, 3];'
        assert py2js('(1,2,3)') == '[1, 2, 3];'

        assert py2js('{"foo": 3, "bar": 4}') == '({foo: 3, bar: 4});'
        assert evalpy('a={"foo": 3, "bar": 4};a') == '{ foo: 3, bar: 4 }'
        with raises(JSError):
            assert evalpy(
                'bla="foo";a={bla: 3, bar: 4};a') == '{ foo: 3, bar: 4 }'
Exemplo n.º 58
0
 def test_simple_funcs_dont_parse_kwargs(self):
     
     # Simplest function does not parse kwargs
     code = py2js('def foo(): pass')
     assert 'parse_kwargs' not in code
     assert 'kw_values' not in code
     
     # Also not with positional args
     code = py2js('def foo(a, b, c): pass')
     assert 'parse_kwargs' not in code
     assert 'kw_values' not in code
     
     # Also not with varargs
     code = py2js('def foo(a, *c): pass')
     assert 'parse_kwargs' not in code
     assert 'kw_values' not in code
     
     # Also not with positional args that have defaults
     code = py2js('def foo(a, b=1, c="foo"): pass')
     assert 'parse_kwargs' not in code
     assert 'kw_values' not in code
Exemplo n.º 59
0
 def test_docstring(self):
     # And that its not interpreted as raw js
     
     def func(a, b):
         """ docstring """
         return a + b
     
     code = py2js(func)
     assert evaljs(code + 'func(100, 10)') == '110'
     assert evaljs(code + 'func("x", 10)') == 'x10'
     
     assert code.count('// docstring') == 1