Exemple #1
0
    def setUp(self):
        super(TokenCategorizerTest, self).setUp()
        self.load_iron_python_test()

        from IronPython.Hosting import Python
        from Microsoft.Scripting import SourceLocation

        self.engine = Python.CreateEngine()
        self.From, self.To, self.t = SourceLocation, SourceLocation, TokenBuilder()
Exemple #2
0
    def setUp(self):
        super(ErrorListenerTest, self).setUp()
        self.load_iron_python_test()

        from Microsoft.Scripting import Severity, SourceLocation
        from IronPython.Hosting import Python
        self.engine = Python.CreateEngine()

        self.From, self.To = SourceLocation, SourceLocation
        self.Warning, self.Error, self.FatalError = Severity.Warning, Severity.Error, Severity.FatalError
Exemple #3
0
 def run_script(self, data):
     script = Encoding.UTF8.GetString(Convert.FromBase64String(data))
     stream = MuhStream()
     engine = Python.CreateEngine()
     engine.Runtime.IO.SetOutput(stream, Encoding.UTF8)
     engine.Runtime.IO.SetErrorOutput(stream, Encoding.UTF8)
     #scope = engine.CreateScope()
     #scope.SetVariable("client", self)
     engine.Execute(script)
     return stream.string
Exemple #4
0
    def __init__(self, printer, context, root):
        self._input_data = []
        self.original_context = context
        self.printer = printer
        self.prompt = root.prompt
        self.root = root
        self.done_first_run = False
        self._sync = ManualResetEvent(False)
        self.ff3 = False

        self.FontSize = 15
        self.Margin = Thickness(0)
        self.FontFamily = FontFamily(
            "Consolas, Monaco, Lucida Console, Global Monospace")
        self.AcceptsReturn = True
        self.BorderThickness = Thickness(0)
        self.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
        self.MinWidth = 300

        def reset():
            "Clear the console, its history and the execution context."
            self._reset_needed = True
            return 'resetting'

        def input(prompt='Input:'):
            'input([prompt]) -> value\n\nEquivalent to eval(raw_input(prompt)).'
            return eval(self.context['raw_input'](prompt), self.context,
                        self.context)

        self.original_context['reset'] = reset
        self.original_context['gohome'] = gohome
        self.original_context['exit'] = 'There is no escape...'
        self.original_context['raw_input'] = self.raw_input
        self.original_context['input'] = input

        # for debugging only!
        self.original_context['root'] = root

        self.context = {}
        self.history = None
        self._reset_needed = False
        self._thread = None
        self._thread_reset = None
        self._raw_input_text = ''
        self._temp_context = None
        self.engine = Python.CreateEngine()
        self.scope = self.engine.CreateScope()

        self._original_caret = None
        if hasattr(self, 'CaretBrush'):
            self._original_caret = self.CaretBrush
        self._disabled = SolidColorBrush(Colors.White)

        self.KeyDown += self.handle_key
        self.TextChanged += self.text_changed
Exemple #5
0
def test_formatexception_exceptiondetail():
    import Microsoft.Scripting
    from IronPython.Hosting import Python

    pe = Python.CreateEngine({'ExceptionDetail': True})

    try:
        x = System.Collections.Generic.Dictionary[object, object]()
        x[None] = 42
    except System.Exception, e:
        pass
Exemple #6
0
    def run_ipy_script(self, args):
        engine_stream = EngineStream()

        engine = Python.CreateEngine()
        engine.Runtime.IO.SetOutput(engine_stream, Encoding.UTF8)
        engine.Runtime.IO.SetErrorOutput(engine_stream, Encoding.UTF8)
        #scope = engine.CreateScope()
        #scope.SetVariable("client", self)

        engine.Execute(args)
        return engine_stream.string
Exemple #7
0
def test_cp27547():
    import clr
    clr.AddReference('IronPython')
    clr.AddReference('Microsoft.Scripting')
    from IronPython.Hosting import Python
    from Microsoft.Scripting import SourceCodeKind, ScriptCodeParseResult
    engine = Python.CreateEngine()
    scope = engine.CreateScope()
    text = 'lambda'
    source = engine.CreateScriptSourceFromString(
        text, 'stdin', SourceCodeKind.InteractiveCode)
    result = source.GetCodeProperties()
    AreEqual(result, ScriptCodeParseResult.IncompleteToken)
Exemple #8
0
def test_formatexception_showclrexceptions():
    import Microsoft.Scripting
    from IronPython.Hosting import Python
    pe = Python.CreateEngine({'ShowClrExceptions': True})

    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(System.Exception("first",
                                                    System.Exception("second",
                                                                     System.Exception())))
    AreEqual(exc_string, "Traceback (most recent call last):[NEWLINE]Exception: first[NEWLINE]CLR Exception: [NEWLINE]    Exception[NEWLINE]: [NEWLINE]first[NEWLINE]    Exception[NEWLINE]: [NEWLINE]second[NEWLINE]    Exception[NEWLINE]: [NEWLINE]Exception of type 'System.Exception' was thrown.[NEWLINE]".replace("[NEWLINE]", System.Environment.NewLine))
    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(c())
    
    AreEqual(exc_string.count(" File "), 4)
    AreEqual(exc_string.count(" line "), 4)
    Assert(exc_string.endswith("CLR Exception: [NEWLINE]    Exception[NEWLINE]: [NEWLINE]first[NEWLINE]    Exception[NEWLINE]: [NEWLINE]second[NEWLINE]    Exception[NEWLINE]: [NEWLINE]Exception of type 'System.Exception' was thrown.[NEWLINE]".replace("[NEWLINE]", System.Environment.NewLine)))
def test_formatexception_showclrexceptions():
    import Microsoft.Scripting
    from IronPython.Hosting import Python
    pe = Python.CreateEngine({'ShowClrExceptions': True})

    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(System.Exception("first",
                                                    System.Exception("second",
                                                                     System.Exception())))
    AreEqual(exc_string, "Traceback (most recent call last):\r\nException: first\r\nCLR Exception: \r\n    Exception\r\n: \r\nfirst\r\n    Exception\r\n: \r\nsecond\r\n    Exception\r\n: \r\nException of type 'System.Exception' was thrown.\r\n")
    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(c())
    
    AreEqual(exc_string.count(" File "), 4)
    AreEqual(exc_string.count(" line "), 4)
    Assert(exc_string.endswith("CLR Exception: \r\n    Exception\r\n: \r\nfirst\r\n    Exception\r\n: \r\nsecond\r\n    Exception\r\n: \r\nException of type 'System.Exception' was thrown.\r\n"))
Exemple #10
0
def test_formatexception_exceptiondetail():
    import Microsoft.Scripting
    from IronPython.Hosting import Python
            
    pe = Python.CreateEngine({'ExceptionDetail': True})

    try:
        x = System.Collections.Generic.Dictionary[object, object]()
        x[None] = 42
    except System.Exception as e:
        pass
    
    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(System.Exception("first", e))
    Assert(exc_string.startswith("first"))
    Assert(exc_string.find('Insert') >= 0) 
    exc_string = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(c())
    Assert(exc_string.endswith("Exception: first[NEWLINE]".replace("[NEWLINE]", System.Environment.NewLine)))
Exemple #11
0
def test_formatexception():
    try:
        import Microsoft.Scripting
        from IronPython.Hosting import Python
        pe = Python.CreateEngine()
        
        service = pe.GetService[Microsoft.Scripting.Hosting.ExceptionOperations]()
        AssertError(TypeError, service.FormatException, None)
    
        exc_string = service.FormatException(System.Exception("first",
                                                        System.Exception("second",
                                                                         System.Exception())))
        AreEqual(exc_string, 'Traceback (most recent call last):[NEWLINE]Exception: first[NEWLINE]'.replace('[NEWLINE]',  System.Environment.NewLine))
        exc_string = service.FormatException(c())
        AreEqual(exc_string.count(" File "), 4)
        AreEqual(exc_string.count(" line "), 4)
    finally:
        pass
Exemple #12
0
def test_formatexception_exceptiondetail():
    import Microsoft.Scripting
    from IronPython.Hosting import Python

    pe = Python.CreateEngine({'ExceptionDetail': True})

    try:
        x = System.Collections.Generic.Dictionary[object, object]()
        x[None] = 42
    except System.Exception as e:
        pass
    import re

    exc_string = pe.GetService[
        Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(
            System.Exception("first", e))
    Assert(exc_string.startswith("first"))
    Assert(
        re.match(
            "first\r\n(   at .*ThrowArgumentNullException.*\n)?   at .*Insert.*\n(   at .*\n)*",
            exc_string) is not None)
    exc_string = pe.GetService[
        Microsoft.Scripting.Hosting.ExceptionOperations]().FormatException(c())
    Assert(exc_string.endswith("Exception: first"))
Exemple #13
0
def test_import_clr():
    from IronPython.Hosting import Python
    eng = Python.CreateEngine()
    mod = Python.ImportModule(eng, 'clr')
    Assert('ToString' not in eng.Operations.GetMemberNames(42))
    def test_assembly_resolve_isolation(self):
        import clr, os
        clr.AddReference("IronPython")
        clr.AddReference("Microsoft.Scripting")
        from IronPython.Hosting import Python
        from Microsoft.Scripting import SourceCodeKind
        tmp = self.temporary_dir
        tmp1 = os.path.join(tmp, 'resolve1')
        tmp2 = os.path.join(tmp, 'resolve2')

        if not os.path.exists(tmp1):
            os.mkdir(tmp1)
        if not os.path.exists(tmp2):
            os.mkdir(tmp2)
        
        code1a = """
using System;

public class ResolveTestA {
    public static string Test() {
        ResolveTestB test = new ResolveTestB();
        return test.DoSomething();
    }
}
    """
        
        code1b = """
using System;

public class ResolveTestB {
    public string DoSomething() {
        return "resolve test 1";
    }
}
    """
        
        code2a = """
using System;

public class ResolveTestA {
    public static string Test() {
        ResolveTestB test = new ResolveTestB();
        return test.DoSomething();
    }
}
    """
        
        code2b = """
using System;

public class ResolveTestB {
    public string DoSomething() {
        return "resolve test 2";
    }
}
    """
        
        script_code = """import clr
clr.AddReferenceToFile("ResolveTestA")
from ResolveTestA import Test
result = Test()
    """
        
        test1a_cs, test1a_dll, test1b_cs, test1b_dll = map(
            lambda x: os.path.join(tmp1, x),
            ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll']
        )
        
        test2a_cs, test2a_dll, test2b_cs, test2b_dll = map(
            lambda x: os.path.join(tmp2, x),
            ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll']
        )

        self.write_to_file(test1a_cs, code1a)
        self.write_to_file(test1b_cs, code1b)
        self.write_to_file(test2a_cs, code2a)
        self.write_to_file(test2b_cs, code2b)
        
        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test1b_dll + ' ' + test1b_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /r:" + test1b_dll + " /out:" + test1a_dll + ' ' + test1a_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /out:" + test2b_dll + ' ' + test2b_cs), 0)
        self.assertEqual(self.run_csc("/nologo /target:library /r:" + test2b_dll + " /out:" + test2a_dll + ' ' + test2a_cs), 0)
        
        engine1 = Python.CreateEngine()
        paths1 = engine1.GetSearchPaths()
        paths1.Add(tmp1)
        engine1.SetSearchPaths(paths1)
        scope1 = engine1.CreateScope()
        script1 = engine1.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements)
        script1.Execute(scope1)
        result1 = scope1.GetVariable("result")
        self.assertEqual(result1, "resolve test 1")
        
        engine2 = Python.CreateEngine()
        paths2 = engine2.GetSearchPaths()
        paths2.Add(tmp2)
        engine2.SetSearchPaths(paths2)
        scope2 = engine2.CreateScope()
        script2 = engine2.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements)
        script2.Execute(scope2)
        result2 = scope2.GetVariable("result")
        self.assertEqual(result2, "resolve test 2")
skiptest("win32")

load_iron_python_test()

import Microsoft.Scripting.Hosting
from Microsoft.Scripting import Severity, SourceCodeKind, SourceSpan, SourceLocation
from Microsoft.Scripting.Hosting import ErrorListener, ScriptSource, ScriptRuntime
from IronPython.Hosting import Python

From, To = SourceLocation, SourceLocation
Warning, Error, FatalError = Severity.Warning, Severity.Error, Severity.FatalError

#------------------------------------------------------------------------------
# Globals
engine = Python.CreateEngine()


#------------------------------------------------------------------------------
# Utils
class MyErrorListener(ErrorListener):
    def __init__(self):
        self.__errors = []

    errors = property(lambda obj: obj.__errors)

    def ErrorReported(self, src, msg, span, errorCode, severity):
        line = src.GetCodeLine(span.Start.Line)
        if line \
            and span.Start.Line == span.End.Line \
            and span.Start.Column != span.End.Column:
Exemple #16
0
def test_assembly_resolve_isolation():
    # CodePlex issue 23506. This feature only works with .NET 4.0
    # builds of IronPython
    if not is_dlr_in_ndp:
        return
    
    import os
    clr.AddReference("IronPython.dll")
    clr.AddReference("Microsoft.Scripting.dll")
    from IronPython.Hosting import Python
    from Microsoft.Scripting import SourceCodeKind
    tmp = testpath.temporary_dir
    tmp1 = path_combine(tmp, 'resolve1')
    tmp2 = path_combine(tmp, 'resolve2')

    if not os.path.exists(tmp1):
        nt.mkdir(tmp1)
    if not os.path.exists(tmp2):
        nt.mkdir(tmp2)
    
    code1a = """
using System;

public class ResolveTestA {
    public static string Test() {
        ResolveTestB test = new ResolveTestB();
        return test.DoSomething();
    }
}
"""
    
    code1b = """
using System;

public class ResolveTestB {
    public string DoSomething() {
        return "resolve test 1";
    }
}
"""
    
    code2a = """
using System;

public class ResolveTestA {
    public static string Test() {
        ResolveTestB test = new ResolveTestB();
        return test.DoSomething();
    }
}
"""
    
    code2b = """
using System;

public class ResolveTestB {
    public string DoSomething() {
        return "resolve test 2";
    }
}
"""
    
    script_code = """import clr
clr.AddReferenceToFile("ResolveTestA")
from ResolveTestA import Test
result = Test()
"""
    
    test1a_cs, test1a_dll, test1b_cs, test1b_dll = [path_combine(tmp1, x) for x in ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll']]
    
    test2a_cs, test2a_dll, test2b_cs, test2b_dll = [path_combine(tmp2, x) for x in ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll']]

    write_to_file(test1a_cs, code1a)
    write_to_file(test1b_cs, code1b)
    write_to_file(test2a_cs, code2a)
    write_to_file(test2b_cs, code2b)
    
    AreEqual(run_csc("/nologo /target:library /out:" + test1b_dll + ' ' + test1b_cs), 0)
    AreEqual(run_csc("/nologo /target:library /r:" + test1b_dll + " /out:" + test1a_dll + ' ' + test1a_cs), 0)
    AreEqual(run_csc("/nologo /target:library /out:" + test2b_dll + ' ' + test2b_cs), 0)
    AreEqual(run_csc("/nologo /target:library /r:" + test2b_dll + " /out:" + test2a_dll + ' ' + test2a_cs), 0)
    
    engine1 = Python.CreateEngine()
    paths1 = engine1.GetSearchPaths()
    paths1.Add(tmp1)
    engine1.SetSearchPaths(paths1)
    scope1 = engine1.CreateScope()
    script1 = engine1.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements)
    script1.Execute(scope1)
    result1 = scope1.GetVariable("result")
    AreEqual(result1, "resolve test 1")
    
    engine2 = Python.CreateEngine()
    paths2 = engine2.GetSearchPaths()
    paths2.Add(tmp2)
    engine2.SetSearchPaths(paths2)
    scope2 = engine2.CreateScope()
    script2 = engine2.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements)
    script2.Execute(scope2)
    result2 = scope2.GetVariable("result")
    AreEqual(result2, "resolve test 2")