Exemplo n.º 1
0
    def test_file_coding(self):
        try:
            import os
            f = file('test_coding_mod.py', 'wb+')
            f.write("# coding: utf-8\nx = '\xe6ble'\n")
            f.close()
            with path_modifier('.'):
                import test_coding_mod
                self.assertEqual(test_coding_mod.x[0], '\xe6')
        finally:
            os.unlink('test_coding_mod.py')

        try:
            f = file('test_coding_2.py', 'wb+')
            f.write("\xef\xbb\xbf# -*- coding: utf-8 -*-\n")
            f.write("x = u'ABCDE'\n")
            f.close()
            with path_modifier('.'):
                import test_coding_2
                self.assertEqual(test_coding_2.x, 'ABCDE')
        finally:
            os.unlink('test_coding_2.py')

        try:
            f = file('test_coding_3.py', 'wb+')
            f.write("# -*- coding: utf-8 -*-\n")
            f.write("raise Exception()")
            f.close()
            try:
                with path_modifier('.'):
                    import test_coding_3
            except Exception as e:
                self.assertEqual(sys.exc_info()[2].tb_next.tb_lineno, 2)
        finally:
            os.unlink('test_coding_3.py')
Exemplo n.º 2
0
    def test_modified_module(self):
        import clr

        test_name = "test_modified_module.py"

        try:
            #create the file
            with open(test_name, "w") as f:
                f.writelines('''A=1; print "First Run"''')
            
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])

            #run checks
            self.assertEqual(output.messages, ["First Run"])
            self.assertEqual(new_module.A, 1)

            #--Do everything again with different values...
            #recreate the file
            with open(test_name, "w") as f:
                f.writelines('''A=2; print "Second Run"''')
            
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])

            #run checks
            self.assertEqual(output.messages, [])
            self.assertEqual(new_module.A, 1)
        finally:
            #cleanup
            try:
                os.remove(test_name)
            except: pass
Exemplo n.º 3
0
    def test_modified_module(self):
        import clr

        test_name = "test_modified_module.py"

        try:
            #create the file
            with open(test_name, "w") as f:
                f.writelines('''A=1; print "First Run"''')
            
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])

            #run checks
            self.assertEqual(output.messages, ["First Run"])
            self.assertEqual(new_module.A, 1)

            #--Do everything again with different values...
            #recreate the file
            with open(test_name, "w") as f:
                f.writelines('''A=2; print "Second Run"''')
            
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])

            #run checks
            self.assertEqual(output.messages, [])
            self.assertEqual(new_module.A, 1)
        finally:
            #cleanup
            try:
                os.remove(test_name)
            except: pass
Exemplo n.º 4
0
    def test_cp13686(self):
        with path_modifier(self.test_dir) as p:
            import toimport
            import sys
            mod_list = [toimport, sys]
            if is_posix:
                import posix
                mod_list.append(posix)
            else:
                import nt
                mod_list.append(nt)

            mod_names = {}
            for mod in mod_list:
                mod_names[mod] = mod.__name__

            for mod in mod_list:
                self.assertRaises(AttributeError, getattr, mod, "name")
                setattr(mod, "name", "xyz")
                self.assertEqual(getattr(mod, "name"), "xyz")

                self.assertEqual(getattr(mod, "__name__"), mod_names[mod])
                setattr(mod, "__name__", "badname")
                self.assertEqual(getattr(mod, "__name__"), "badname")

            if is_cli:
                import System
                self.assertRaises(AttributeError, setattr, System, "name", "xyz")
Exemplo n.º 5
0
    def test_cp24381(self):
        import sys
        orig_sys_trace_func = sys.gettrace()
        def f(*args):
            global CP24381_MESSAGES
            CP24381_MESSAGES += args[1:]
            return f

        cp24381_file_name = "cp24381.py"
        cp24381_contents  = """
print 'a'
print 'b'
print 'c'

def f():
    print 'hi'

f()
"""

        try:
            self.write_to_file(cp24381_file_name, cp24381_contents)
            sys.settrace(f)
            with path_modifier('.'):
                import cp24381
        finally:
            sys.settrace(orig_sys_trace_func)
            os.unlink(cp24381_file_name)

        self.assertEqual(CP24381_MESSAGES,
                ['call', None, 'line', None, 'line', None, 'line', None, 'line',
                None, 'line', None, 'call', None, 'line', None, 'return', None,
                'return', None])
Exemplo n.º 6
0
    def test_cp13686(self):
        with path_modifier(self.test_dir) as p:
            import toimport
            import sys
            mod_list = [toimport, sys]
            if is_posix:
                import posix
                mod_list.append(posix)
            else:
                import nt
                mod_list.append(nt)

            mod_names = {}
            for mod in mod_list:
                mod_names[mod] = mod.__name__

            for mod in mod_list:
                self.assertRaises(AttributeError, getattr, mod, "name")
                setattr(mod, "name", "xyz")
                self.assertEqual(getattr(mod, "name"), "xyz")

                self.assertEqual(getattr(mod, "__name__"), mod_names[mod])
                setattr(mod, "__name__", "badname")
                self.assertEqual(getattr(mod, "__name__"), "badname")

            if is_cli:
                import System
                self.assertRaises(AttributeError, setattr, System, "name",
                                  "xyz")
Exemplo n.º 7
0
    def test_cp7007(self):
        file_contents = '''
called = 3.14
    '''
    
        strange_module_names = [    "+",
                                    "+a",
                                    "a+",
                                    "++",
                                    "+++",
                                    "-",
                                    "=",
                                    "$",
                                    "^",
                                ]
        
        strange_file_names = [ os.path.join(self.test_dir, "cp7007", x + ".py") for x in strange_module_names ]
        
        for x in strange_file_names: self.write_to_file(x, file_contents)
        
        try:
            with path_modifier(os.path.join(self.test_dir, 'cp7007')) as p:
                for x in strange_module_names:
                    temp_mod = __import__(x)
                    self.assertEqual(temp_mod.called, 3.14)
        finally:
            self.clean_directory(os.path.join(self.test_dir, "cp7007"))
Exemplo n.º 8
0
    def test_cli_subclasses(self):
        import clr

        self.assertTrue(issubclass(int, int))
        self.assertTrue(not issubclass(str, int))
        self.assertTrue(not issubclass(int, (str, str)))
        self.assertTrue(issubclass(int, (str, int)))

        self.assertTrue(issubclass(bytes, basestring))
        self.assertTrue(issubclass(str, basestring))
        self.assertTrue(issubclass(unicode, basestring))
        self.assertTrue(issubclass(basestring, basestring))

        class basestring_subclass(basestring):
            pass

        self.assertTrue(issubclass(basestring_subclass, basestring))

        self.assertTrue(str(None) == "None")
        self.assertTrue(issubclass(type(None), type(None)))
        self.assertTrue(str(type(None)) == "<type 'NoneType'>")
        self.assertTrue(str(1) == "1")
        self.assertTrue('__str__' in dir(None))

        def tryAssignToNoneAttr():
            None.__doc__ = "Nothing!"

        def tryAssignToNoneNotAttr():
            None.notanattribute = ""

        self.assertRaises(AttributeError, tryAssignToNoneAttr)
        self.assertRaises(AttributeError, tryAssignToNoneNotAttr)
        v = None.__doc__
        v = None.__new__
        v = None.__hash__
        self.assertEqual("<type 'NoneType'>", str(type(None)))

        import sys
        self.assertEqual(str(sys), "<module 'sys' (built-in)>")

        import time
        with path_modifier(self.test_dir):
            import toimport

        m = [type(sys), type(time), type(toimport)]
        for i in m:
            for j in m:
                self.assertTrue(issubclass(i, j))

        self.assertRaises(TypeError, type, None, None,
                          None)  # arg 1 must be string
        self.assertRaises(TypeError, type, "NewType", None,
                          None)  # arg 2 must be tuple
        self.assertRaises(TypeError, type, "NewType", (),
                          None)  # arg 3 must be dict

        def splitTest():
            "string".split('')

        self.assertRaises(ValueError, splitTest)
Exemplo n.º 9
0
    def test_cp7007(self):
        file_contents = '''
called = 3.14
    '''
    
        strange_module_names = [    "+",
                                    "+a",
                                    "a+",
                                    "++",
                                    "+++",
                                    "-",
                                    "=",
                                    "$",
                                    "^",
                                ]
        
        strange_file_names = [ os.path.join(self.test_dir, "cp7007", x + ".py") for x in strange_module_names ]
        
        for x in strange_file_names: self.write_to_file(x, file_contents)
        
        try:
            with path_modifier(os.path.join(self.test_dir, 'cp7007')) as p:
                for x in strange_module_names:
                    temp_mod = __import__(x)
                    self.assertEqual(temp_mod.called, 3.14)
        finally:
            self.clean_directory(os.path.join(self.test_dir, "cp7007"))
Exemplo n.º 10
0
 def test_encoded_module(self):
     """https://github.com/IronLanguages/ironpython2/issues/129"""
     with path_modifier(os.path.join(self.test_dir, 'gh129.zip')):
         import something
         self.assertEqual(
             something.test(),
             u'\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440!')
Exemplo n.º 11
0
    def test_cp24381(self):
        import sys
        orig_sys_trace_func = sys.gettrace()
        def f(*args):
            global CP24381_MESSAGES
            CP24381_MESSAGES += args[1:]
            return f
        
        cp24381_file_name = "cp24381.py"
        cp24381_contents  = """
print 'a'
print 'b'
print 'c'

def f():
    print 'hi'

f()
"""

        try:
            self.write_to_file(cp24381_file_name, cp24381_contents)
            sys.settrace(f)
            with path_modifier('.'):
                import cp24381
        finally:
            sys.settrace(orig_sys_trace_func)
            os.unlink(cp24381_file_name)

        self.assertEqual(CP24381_MESSAGES,
                ['call', None, 'line', None, 'line', None, 'line', None, 'line', 
                None, 'line', None, 'call', None, 'line', None, 'return', None, 
                'return', None])
Exemplo n.º 12
0
    def test_always_true(self):
        always_true(self)

        try:
            import sys
            with path_modifier(self.temporary_dir):
                for code in (code1, code2) :
                    self.write_to_file(self.tempfile, code)
                    
                    f1(self.tempfile)
                    always_true(self)
                    f2(code, self.tempfile)
                    always_true(self)
                    f3(code)
                    always_true(self)

                ## test import from file
                for code in (code0, code2):
                    self.write_to_file(self.tempfile, code)
                    
                    import temp_future
                    always_true(self)
                    reloaded_temp_future = reload(temp_future)
                    always_true(self)
        finally:
            self.delete_files(self.tempfile)
Exemplo n.º 13
0
    def test_module_doc_cp21360(self):
        temp_filename_empty = "cp21360_empty.py"
        temp_filename = "cp21360.py"
        try:
            with path_modifier('.'):
                self.write_to_file(temp_filename_empty, "")
                import cp21360_empty
                self.assertEqual(cp21360_empty.__doc__, None)

            with path_modifier('.'):
                self.write_to_file(temp_filename, "x = 3.14")
                import cp21360
                self.assertEqual(cp21360.__doc__, None)
                self.assertEqual(cp21360.x, 3.14)

        finally:
            self.delete_files(temp_filename, temp_filename_empty)
Exemplo n.º 14
0
    def test_module_doc_cp21360(self):
        temp_filename_empty = "cp21360_empty.py"
        temp_filename = "cp21360.py"
        try:
            with path_modifier('.'):
                self.write_to_file(temp_filename_empty, "")
                import cp21360_empty
                self.assertEqual(cp21360_empty.__doc__, None)

            with path_modifier('.'):
                self.write_to_file(temp_filename, "x = 3.14")
                import cp21360
                self.assertEqual(cp21360.__doc__, None)
                self.assertEqual(cp21360.x, 3.14)
        
        finally:
            self.delete_files(temp_filename, temp_filename_empty)
Exemplo n.º 15
0
 def f():
     import os
     with open('temptest.py', 'w+') as f:
         f.write('foo = 42')
     try:
         with path_modifier('.'):
             from temptest import foo
     finally:
         os.unlink('temptest.py')
     return foo
Exemplo n.º 16
0
 def f():
     import os
     with open('temptest.py', 'w+') as f:
         f.write('foo = 42')
     try:
         with path_modifier('.'):
             from temptest import foo
     finally:
         os.unlink('temptest.py')
     return foo
Exemplo n.º 17
0
    def test_cli_subclasses(self):
        import clr
        
        self.assertTrue(issubclass(int, int))
        self.assertTrue(not issubclass(str, int))
        self.assertTrue(not issubclass(int, (str, str)))
        self.assertTrue(issubclass(int, (str, int)))

        self.assertTrue(issubclass(bytes, basestring))
        self.assertTrue(issubclass(str, basestring))
        self.assertTrue(issubclass(unicode, basestring))
        self.assertTrue(issubclass(basestring, basestring))
        class basestring_subclass(basestring):
            pass
        self.assertTrue(issubclass(basestring_subclass, basestring))

        self.assertTrue(str(None) == "None")
        self.assertTrue(issubclass(type(None),type(None)))
        self.assertTrue(str(type(None)) == "<type 'NoneType'>")
        self.assertTrue(str(1) == "1")
        self.assertTrue('__str__' in dir(None))
        
        def tryAssignToNoneAttr():
            None.__doc__ = "Nothing!"
        
        def tryAssignToNoneNotAttr():
            None.notanattribute = "";
        
        self.assertRaises(AttributeError, tryAssignToNoneAttr)
        self.assertRaises(AttributeError, tryAssignToNoneNotAttr)
        v = None.__doc__
        v = None.__new__
        v = None.__hash__
        self.assertEqual("<type 'NoneType'>", str(type(None)))
        
        import sys
        self.assertEqual(str(sys), "<module 'sys' (built-in)>")
        
        import time
        with path_modifier(self.test_dir):
            import toimport
        
        m = [type(sys), type(time), type(toimport)]
        for i in m:
            for j in m:
                self.assertTrue(issubclass(i,j))
        
        self.assertRaises(TypeError, type, None, None, None) # arg 1 must be string
        self.assertRaises(TypeError, type, "NewType", None, None) # arg 2 must be tuple
        self.assertRaises(TypeError, type, "NewType", (), None) # arg 3 must be dict
        
        
        def splitTest():
            "string".split('')
        self.assertRaises(ValueError, splitTest)
Exemplo n.º 18
0
    def simpleTester(self, a, b, c):
        global SIMPLE_TEST_COUNT

        import clr

        test_name = "clrusetest{}.py".format(SIMPLE_TEST_COUNT)
        SIMPLE_TEST_COUNT += 1
        expected_stdout = '''OK...'''

        #create the file
        test_text = SIMPLE_TEST % (str(a), str(c))
        with open(test_name, "w") as f:
            f.writelines(test_text)

        try:
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])

            #run a few easy checks
            self.assertEqual(len(output.messages), 3)
            self.assertEqual(output.messages[0], expected_stdout)
            self.assertEqual(output.messages[2], "b= 42")
            self.assertEqual(new_module.A, a)
            self.assertEqual(new_module.aFunc(None), c)
            self.assertTrue(isinstance(new_module.K, new_module.Klass))
            self.assertEqual(new_module.K.Member, 72)
            new_module.K.Member = "foo"
            self.assertEqual(new_module.K.Member, "foo")
            new_module.K.NewMember = 33
            self.assertEqual(new_module.K.NewMember, 33)
            new_module.K = None
            self.assertEqual(new_module.K, None)

            #negative checks
            self.assertRaises(TypeError, new_module.aFunc)
            self.assertRaises(TypeError, new_module.aFunc, 1, 2)
            self.assertRaises(TypeError, new_module.aFunc, 1, 2, 3)
            self.assertTrue(not hasattr(new_module, "a"))
            self.assertTrue(not hasattr(new_module, "simpleTester"))
            try:
                aFunc(7)
                self.fail("Should never get this far")
            except:
                pass

            #hard test
            real_module = __import__(test_name.split(".py")[0])
            #for key in dir(real_module): self.assertEqual(real_module.__dict__[key], new_module.__dict__[key])
        finally:
            #cleanup
            try:
                os.remove(test_name)
            except:
                pass
Exemplo n.º 19
0
 def f():
     import os
     module_name = 'temptest_%d' % os.getpid()
     fname = module_name + '.py'
     with open(fname, 'w+') as f:
         f.write('foo = 42')
     try:
         with path_modifier('.'):
             foo = __import__(module_name).foo
     finally:
         os.unlink(fname)
     return foo
Exemplo n.º 20
0
    def simpleTester(self, a, b, c):
        global SIMPLE_TEST_COUNT

        import clr
        
        test_name = "clrusetest{}.py".format(SIMPLE_TEST_COUNT)
        SIMPLE_TEST_COUNT += 1
        expected_stdout = '''OK...'''
        
        #create the file
        test_text = SIMPLE_TEST % (str(a), str(c))
        with open(test_name, "w") as f:
            f.writelines(test_text)
        
        try:
            with path_modifier('.') as p:
                with stdout_trapper() as output:
                    new_module = clr.Use(test_name.split(".py")[0])
            
            #run a few easy checks
            self.assertEqual(len(output.messages), 3)
            self.assertEqual(output.messages[0], expected_stdout)
            self.assertEqual(output.messages[2], "b= 42")
            self.assertEqual(new_module.A, a)
            self.assertEqual(new_module.aFunc(None), c)
            self.assertTrue(isinstance(new_module.K, new_module.Klass))
            self.assertEqual(new_module.K.Member, 72)
            new_module.K.Member = "foo"
            self.assertEqual(new_module.K.Member, "foo")
            new_module.K.NewMember = 33
            self.assertEqual(new_module.K.NewMember, 33)
            new_module.K = None
            self.assertEqual(new_module.K, None)
            
            #negative checks
            self.assertRaises(TypeError, new_module.aFunc)
            self.assertRaises(TypeError, new_module.aFunc, 1, 2)
            self.assertRaises(TypeError, new_module.aFunc, 1, 2, 3)
            self.assertTrue(not hasattr(new_module, "a"))
            self.assertTrue(not hasattr(new_module, "simpleTester"))
            try:
                aFunc(7)
                self.fail("Should never get this far")
            except:
                pass
            
            #hard test
            real_module = __import__(test_name.split(".py")[0])
            #for key in dir(real_module): self.assertEqual(real_module.__dict__[key], new_module.__dict__[key])
        finally:
            pass
Exemplo n.º 21
0
    def test_file_coding(self):
        try:
            import os
            with open('test_coding_mod.py', 'wb+') as f:
                f.write(b"# coding: utf-8\nx = '\xc3\xa6ble'\n")
            with path_modifier('.'):
                import test_coding_mod
                self.assertEqual(test_coding_mod.x[0], '\xe6')
        finally:
            os.unlink('test_coding_mod.py')

        try:
            with open('test_coding_2.py', 'wb+') as f:
                f.write(b"\xef\xbb\xbf# -*- coding: utf-8 -*-\n")
                f.write(b"x = u'ABCDE'\n")
            with path_modifier('.'):
                import test_coding_2
                self.assertEqual(test_coding_2.x, 'ABCDE')
        finally:
            os.unlink('test_coding_2.py')

        try:
            with open('test_coding_3.py', 'wb+') as f:
                f.write(b"# -*- coding: utf-8 -*-\n")
                f.write(b"raise Exception()")
            f.close()
            try:
                with path_modifier('.'):
                    import test_coding_3
            except Exception as e:
                tb = sys.exc_info()[2].tb_next
                if is_cli:
                    while tb.tb_next is not None:
                        tb = tb.tb_next  # importlib has a longer traceback
                self.assertEqual(tb.tb_lineno, 2)
        finally:
            os.unlink('test_coding_3.py')
Exemplo n.º 22
0
 def test_file_coding(self):
     try:
         import os
         f = file('test_coding_mod.py', 'wb+')
         f.write("# coding: utf-8\nx = '\xe6ble'\n")
         f.close()
         with path_modifier('.'):
             import test_coding_mod
             self.assertEqual(test_coding_mod.x[0], '\xe6')
     finally:
         os.unlink('test_coding_mod.py')
     
     try:
         f = file('test_coding_2.py', 'wb+')
         f.write("\xef\xbb\xbf# -*- coding: utf-8 -*-\n")
         f.write("x = u'ABCDE'\n")
         f.close()
         with path_modifier('.'):
             import test_coding_2
             self.assertEqual(test_coding_2.x, 'ABCDE')
     finally:
         os.unlink('test_coding_2.py')
         
         
     try:
         f = file('test_coding_3.py', 'wb+')
         f.write("# -*- coding: utf-8 -*-\n")
         f.write("raise Exception()")
         f.close()
         try:
             with path_modifier('.'):
                 import test_coding_3
         except Exception, e:
             self.assertEqual(sys.exc_info()[2].tb_next.tb_lineno, 2)
     finally:
         os.unlink('test_coding_3.py')
Exemplo n.º 23
0
    def test_cp16519(self):
        __main__ = __import__(__name__)
        __main__.Dict = {"1": "a"}
        self.assertEqual(__main__.Dict["1"], "a")
        del __main__.Dict

        import sys
        sys.Dict = {"1": "b"}
        self.assertEqual(sys.Dict["1"], "b")
        del sys.Dict

        with path_modifier(os.path.join(source_root(), 'Tests')):
            import testpkg1
            testpkg1.Dict = {"1": "c"}
            self.assertEqual(testpkg1.Dict["1"], "c")
            del testpkg1.Dict
Exemplo n.º 24
0
    def test_cp16519(self):
        __main__ = __import__(__name__)
        __main__.Dict = {"1": "a"}
        self.assertEqual(__main__.Dict["1"], "a")
        del __main__.Dict

        import sys
        sys.Dict = {"1": "b"}
        self.assertEqual(sys.Dict["1"], "b")
        del sys.Dict

        with path_modifier(os.path.join(source_root(), 'Tests')):
            import testpkg1
            testpkg1.Dict = {"1": "c"}
            self.assertEqual(testpkg1.Dict["1"], "c")
            del testpkg1.Dict
Exemplo n.º 25
0
    def test_simple(self):
        always_true(self)
        try:
            import sys
            with path_modifier(self.temporary_dir):
                for code in (code1, code2):
                    self.write_to_file(self.tempfile, code)

                    f1(self.tempfile)
                    always_true(self)
                    f2(code, self.tempfile)
                    always_true(self)
                    f3(code)
                    always_true(self)
        finally:
            self.delete_files(self.tempfile)
Exemplo n.º 26
0
 def test_simple(self):
     always_true(self)
     try:
         import sys
         with path_modifier(self.temporary_dir):
             for code in (code1, code2) :
                 self.write_to_file(self.tempfile, code)
                 
                 f1(self.tempfile)
                 always_true(self)
                 f2(code, self.tempfile)
                 always_true(self)
                 f3(code)
                 always_true(self)
     finally:
         self.delete_files(self.tempfile)
Exemplo n.º 27
0
    def test_imp_module(self):
        self.write_to_file(self._f_module, "value = 'imp test module'")
        pf, pp, (px, pm, pt) = imp.find_module("imptestmod", [self._imptestdir])
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf is not None)
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()

        with path_modifier(self._imptestdir) as p:
            fm = imp.find_module("imptestmod")
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf != None)
        self.assertEqual(px, ".py")
        self.assertEqual(pm, "r")
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()
Exemplo n.º 28
0
    def test_imp_package(self):
        self.write_to_file(self._f_init, "my_name = 'imp package test'")
        pf, pp, (px, pm, pt) = imp.find_module(self._testdir, [self.test_dir])
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertTrue(self._testdir in sys.modules)
        self.assertEqual(module.my_name, 'imp package test')

        with path_modifier(self.test_dir):
            fm = imp.find_module(self._testdir)
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertEqual(module.my_name, 'imp package test')
Exemplo n.º 29
0
    def test_imp_package(self):
        self.write_to_file(self._f_init, "my_name = 'imp package test'")
        pf, pp, (px, pm, pt) = imp.find_module(self._testdir, [self.test_dir])
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertTrue(self._testdir in sys.modules)
        self.assertEqual(module.my_name, 'imp package test')

        with path_modifier(self.test_dir):
            fm = imp.find_module(self._testdir)
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PKG_DIRECTORY)
        self.assertEqual(pf, None)
        self.assertEqual(px, "")
        self.assertEqual(pm, "")
        module = imp.load_module(self._testdir, pf, pp, (px, pm, pt))
        self.assertEqual(module.my_name, 'imp package test')
Exemplo n.º 30
0
    def test_imp_module(self):
        self.write_to_file(self._f_module, "value = 'imp test module'")
        pf, pp, (px, pm, pt) = imp.find_module("imptestmod", [self._imptestdir])
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf != None)
        self.assertTrue(isinstance(pf, file))
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()

        with path_modifier(self._imptestdir) as p:
            fm = imp.find_module("imptestmod")
        # unpack the result obtained above
        pf, pp, (px, pm, pt) = fm
        self.assertEqual(pt, imp.PY_SOURCE)
        self.assertTrue(pf != None)
        self.assertTrue(isinstance(pf, file))
        self.assertEqual(px, ".py")
        self.assertEqual(pm, "U")
        module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
        self.assertEqual(module.value, 'imp test module')
        pf.close()
Exemplo n.º 31
0
    def test_cp24381(self):
        CP24381_MESSAGES = []

        import sys
        orig_sys_trace_func = sys.gettrace()

        def f(*args):
            CP24381_MESSAGES.extend(args[1:])
            return f

        cp24381_module = "cp24381_%d" % os.getpid()
        cp24381_file_name = cp24381_module + ".py"
        cp24381_contents = """
print('a')
print('b')
print('c')

def f():
    print('hi')

f()
"""

        try:
            self.write_to_file(cp24381_file_name, cp24381_contents)
            sys.settrace(f)
            with path_modifier('.'):
                __import__(cp24381_module)
        finally:
            sys.settrace(orig_sys_trace_func)
            os.unlink(cp24381_file_name)

        self.assertEqual(CP24381_MESSAGES, [
            'call', None, 'line', None, 'line', None, 'line', None, 'line',
            None, 'line', None, 'call', None, 'line', None, 'return', None,
            'return', None
        ])
Exemplo n.º 32
0
    def test_cp15803(self):
        _testdir = 'cp15803'
        pickle_file = os.path.join(self.test_dir,
                                   "cp15803_%d.pickle" % os.getpid())

        module_txt = """
class K%s(object):
    static_member = 1
    def __init__(self):
        self.member = 2

%s = K%s()
"""

        _testdir_init = os.path.join(self.test_dir, _testdir, '__init__.py')
        self.write_to_file(_testdir_init, module_txt % ("", "FROM_INIT", ""))

        _testdir_mod = os.path.join(self.test_dir, _testdir, 'mod.py')
        self.write_to_file(
            _testdir_mod, module_txt % ("Mod", "FROM_MOD", "Mod") + """
from cp15803 import K
FROM_INIT_IN_MOD = K()
""")

        _testdir_sub = os.path.join(self.test_dir, _testdir, 'sub')
        _testdir_sub_init = os.path.join(_testdir_sub, '__init__.py')
        self.write_to_file(_testdir_sub_init)

        _testdir_sub_submod = os.path.join(_testdir_sub, 'submod.py')
        self.write_to_file(
            _testdir_sub_submod,
            module_txt % ("SubMod", "FROM_SUB_MOD", "SubMod") + """
from cp15803 import mod
FROM_MOD_IN_SUBMOD = mod.KMod()
""")

        try:
            with path_modifier(self.test_dir) as p:
                import cp15803
                import cp15803.mod
                import cp15803.sub.submod
                import cp15803.sub.submod as newname

                for x in [
                        cp15803.K(),
                        cp15803.FROM_INIT,
                        cp15803.mod.KMod(),
                        cp15803.mod.FROM_MOD,
                        cp15803.mod.K(),
                        cp15803.mod.FROM_INIT_IN_MOD,
                        cp15803.sub.submod.KSubMod(),
                        cp15803.sub.submod.FROM_SUB_MOD,
                        cp15803.sub.submod.FROM_MOD_IN_SUBMOD,
                        cp15803.sub.submod.mod.KMod(),
                        cp15803.sub.submod.mod.FROM_MOD,
                        cp15803.sub.submod.mod.K(),
                        cp15803.sub.submod.mod.FROM_INIT_IN_MOD,
                        newname.KSubMod(),
                        newname.FROM_SUB_MOD,
                        newname.FROM_MOD_IN_SUBMOD,
                        newname.mod.KMod(),
                        newname.mod.FROM_MOD,
                        newname.mod.K(),
                        newname.mod.FROM_INIT_IN_MOD,
                ]:
                    with open(pickle_file, "wb") as f:
                        cPickle.dump(x, f)

                    with open(pickle_file, "rb") as f:
                        x_unpickled = cPickle.load(f)

                        self.assertEqual(x.__class__.__name__,
                                         x_unpickled.__class__.__name__)
                        self.assertEqual(x.static_member,
                                         x_unpickled.static_member)
                        self.assertEqual(x.member, x_unpickled.member)

        finally:
            try:
                os.unlink(pickle_file)
                self.clean_directory(os.path.join(self.test_dir, _testdir))
            except:
                pass
Exemplo n.º 33
0
    def test_cp15803(self):
        import os
        _testdir = 'cp15803'
        pickle_file = os.path.join(self.test_dir, "cp15803.pickle")

        module_txt = """
class K%s(object):
    static_member = 1
    def __init__(self):
        self.member = 2

%s = K%s()
"""

        _testdir_init       = os.path.join(self.test_dir, _testdir, '__init__.py')
        self.write_to_file(_testdir_init, module_txt % ("", "FROM_INIT", ""))

        _testdir_mod        = os.path.join(self.test_dir, _testdir, 'mod.py')
        self.write_to_file(_testdir_mod, module_txt % ("Mod", "FROM_MOD", "Mod") + """
from cp15803 import K
FROM_INIT_IN_MOD = K()
"""
        )

        _testdir_sub        = os.path.join(self.test_dir, _testdir, 'sub')
        _testdir_sub_init   = os.path.join(_testdir_sub, '__init__.py')
        self.write_to_file(_testdir_sub_init)

        _testdir_sub_submod = os.path.join(_testdir_sub, 'submod.py')
        self.write_to_file(_testdir_sub_submod, module_txt % ("SubMod", "FROM_SUB_MOD", "SubMod") + """
from cp15803 import mod
FROM_MOD_IN_SUBMOD = mod.KMod()
"""
        )

        with path_modifier(self.test_dir) as p:
            import cp15803
            import cp15803.mod
            import cp15803.sub.submod
            import cp15803.sub.submod as newname

            try:
                for x in [
                            cp15803.K(), cp15803.FROM_INIT,
                            cp15803.mod.KMod(), cp15803.mod.FROM_MOD, cp15803.mod.K(), cp15803.mod.FROM_INIT_IN_MOD,
                            cp15803.sub.submod.KSubMod(), cp15803.sub.submod.FROM_SUB_MOD, cp15803.sub.submod.FROM_MOD_IN_SUBMOD,
                            cp15803.sub.submod.mod.KMod(), cp15803.sub.submod.mod.FROM_MOD, cp15803.sub.submod.mod.K(), cp15803.sub.submod.mod.FROM_INIT_IN_MOD,

                            newname.KSubMod(), newname.FROM_SUB_MOD, newname.FROM_MOD_IN_SUBMOD,
                            newname.mod.KMod(), newname.mod.FROM_MOD, newname.mod.K(), newname.mod.FROM_INIT_IN_MOD,
                            ]:
                    with open(pickle_file, "w") as f:
                        cPickle.dump(x, f)

                    with open(pickle_file, "r") as f:
                        x_unpickled = cPickle.load(f)

                        self.assertEqual(x.__class__.__name__, x_unpickled.__class__.__name__)
                        self.assertEqual(x.static_member, x_unpickled.static_member)
                        self.assertEqual(x.member, x_unpickled.member)

            finally:
                import os
                try:
                    os.unlink(pickle_file)
                    self.clean_directory(os.path.join(self.test_dir, _testdir))
                except:
                    pass
import unittest

from iptest import path_modifier, run_test, skipUnlessIronPython, source_root

def gen_testcase(exc_name):
    def test(self):
        import IronPython.Runtime.Exceptions as IRE
        e0 = eval("IRE.%s()" % exc_name)
        e2 = eval("IRE.%s('msg', e0)" % exc_name)
        self.assertEqual(e0.Message, e2.InnerException.Message)
        self.assertEqual("msg", e2.Message)
    return test

@skipUnlessIronPython()
class ExceptionsGeneratedTest(unittest.TestCase):
    def setUp(self):
        super(ExceptionsGeneratedTest, self).setUp()
        import clr
        clr.AddReference("IronPython")


with path_modifier(os.path.join(source_root(), 'Src', 'Scripts')):
    from generate_exceptions import pythonExcs as test_cases
test_cases = [x.replace('Error', '') + 'Exception' for x in test_cases]
for exc_name in test_cases:
    test_name = 'test_%s' % exc_name
    test = gen_testcase(exc_name)
    setattr(ExceptionsGeneratedTest, test_name, test)

run_test(__name__)
import sys
import unittest

from iptest import path_modifier, run_test, skipUnlessIronPython, source_root

def gen_testcase(exc_name):
    def test(self):
        import IronPython.Runtime.Exceptions as IRE
        e0 = eval("IRE.%s()" % exc_name)
        e2 = eval("IRE.%s('msg', e0)" % exc_name)
        self.assertEqual(e0.Message, e2.InnerException.Message)
        self.assertEqual("msg", e2.Message)
    return test

@skipUnlessIronPython()
class ExceptionsGeneratedTest(unittest.TestCase):
    def setUp(self):
        super(ExceptionsGeneratedTest, self).setUp()
        import clr
        clr.AddReference("IronPython")


with path_modifier(os.path.join(source_root(), 'Src', 'Scripts')):
    from generate_exceptions import pythonExcs as test_cases
test_cases = [x.replace('Error', '') + 'Exception' for x in test_cases]
for exc_name in test_cases:
    test_name = 'test_%s' % exc_name
    test = gen_testcase(exc_name)
    setattr(ExceptionsGeneratedTest, test_name, test)

run_test(__name__)
Exemplo n.º 36
0
 def test_encoded_module(self):
     """https://github.com/IronLanguages/ironpython2/issues/129"""
     with path_modifier(os.path.join(self.test_dir, 'gh129.zip')):
         import something
         self.assertEqual(something.test(), u'\u041f\u0440\u0438\u0432\u0435\u0442 \u043c\u0438\u0440!')