Exemplo n.º 1
0
def test_substitute_abstract_code_functions():
    def f(x):
        y = x * x
        return y

    def g(x):
        return f(x) + 1

    code = '''
    z = f(x)
    z = f(x)+f(y)
    w = f(z)
    h = f(f(w))
    p = g(g(x))
    '''
    funcs = [
        abstract_code_from_function(f),
        abstract_code_from_function(g),
    ]
    subcode = substitute_abstract_code_functions(code, funcs)
    for x, y in [(0, 1), (1, 0), (0.124323, 0.4549483)]:
        ns1 = {'x': x, 'y': y, 'f': f, 'g': g}
        ns2 = {'x': x, 'y': y}
        exec(deindent(code), ns1)
        exec(subcode, ns2)
        for k in ['z', 'w', 'h', 'p']:
            assert ns1[k] == ns2[k]
Exemplo n.º 2
0
def test_abstract_code_from_function():
    # test basic functioning
    def f(x):
        y = x + 1
        return y * y

    ac = abstract_code_from_function(f)
    assert ac.name == 'f'
    assert ac.args == ['x']
    assert ac.code.strip() == 'y = x + 1'
    assert ac.return_expr == 'y * y'

    # Check that unsupported features raise an error

    def f(x):
        return x[:]

    assert_raises(SyntaxError, abstract_code_from_function, f)

    def f(x, **kwarg):
        return x

    assert_raises(SyntaxError, abstract_code_from_function, f)

    def f(x, *args):
        return x

    assert_raises(SyntaxError, abstract_code_from_function, f)
Exemplo n.º 3
0
def test_substitute_abstract_code_functions():
    def f(x):
        y = x*x
        return y
    def g(x):
        return f(x)+1
    code = '''
    z = f(x)
    z = f(x)+f(y)
    w = f(z)
    h = f(f(w))
    p = g(g(x))
    '''
    funcs = [abstract_code_from_function(f),
             abstract_code_from_function(g),
             ]
    subcode = substitute_abstract_code_functions(code, funcs)
    for x, y in [(0, 1), (1, 0), (0.124323, 0.4549483)]:
        ns1 = {'x':x, 'y':y, 'f':f, 'g':g}
        ns2 = {'x':x, 'y':y}
        exec deindent(code) in ns1
        exec subcode in ns2
        for k in ['z', 'w', 'h', 'p']:
            assert ns1[k]==ns2[k]
Exemplo n.º 4
0
def test_abstract_code_from_function():
    # test basic functioning
    def f(x):
        y = x+1
        return y*y
    ac = abstract_code_from_function(f)
    assert ac.name=='f'
    assert ac.args==['x']
    assert ac.code.strip()=='y = x + 1'
    assert ac.return_expr=='y * y'
    # Check that unsupported features raise an error

    def f(x):
        return x[:]
    assert_raises(SyntaxError, abstract_code_from_function, f)

    def f(x, **kwarg):
        return x
    assert_raises(SyntaxError, abstract_code_from_function, f)

    def f(x, *args):
        return x
    assert_raises(SyntaxError, abstract_code_from_function, f)