def test_x():
    tmpxoptscript = tmpdir + '\\xopt.py'
    f = file(tmpxoptscript, "w")
    f.write("first line is garbage\nprint 2+2\n")
    f.close()
    TestCommandLine(('-x', tmpxoptscript), "4\n")
    nt.unlink(tmpxoptscript)
Exemple #2
0
def test_cp20174():
    cp20174_path = testpath.public_testdir + r"\cp20174"

    try:
        nt.mkdir(cp20174_path)

        cp20174_init = cp20174_path + r"\__init__.py"
        write_to_file(cp20174_init, "import a")

        cp20174_a = cp20174_path + r"\a.py"
        write_to_file(
            cp20174_a, """
from property import x
class C:
    def _get_x(self): return x
    x = property(_get_x)
""")

        cp20174_property = cp20174_path + r"\property.py"
        write_to_file(cp20174_property, "x=1")

        import cp20174
        AreEqual(cp20174.property.x, 1)

    finally:
        for x in nt.listdir(cp20174_path):
            nt.unlink(cp20174_path + "\\" + x)
        nt.rmdir(cp20174_path)
Exemple #3
0
def test_threading_waits_for_thread_exit():
    import os
    from iptest.process_util import launch
    f = file('temp.py', 'w+')
    try:
        f.write("""
import sys
def f():
    print 'bye bye'

def f(*args):
    print 'bye bye'

sys.exitfunc = f
from threading import Thread
def count(n):
    while n > 0:
            n -= 1
    print 'done'

t1 = Thread(target=count, args=(50000000,))
t1.start()
    """)
        f.close()
        stdin, stdout = os.popen2(sys.executable + ' temp.py')
        Assert('bye bye\n' in list(stdout))
    finally:
        import nt
        nt.unlink('temp.py')
Exemple #4
0
def test_threading_waits_for_thread_exit():
    import os
    from iptest.process_util import launch
    f = file('temp.py', 'w+')
    try:
        f.write("""
import sys
def f():
    print 'bye bye'

def f(*args):
    print 'bye bye'

sys.exitfunc = f
from threading import Thread
def count(n):
    while n > 0:
            n -= 1
    print 'done'

t1 = Thread(target=count, args=(50000000,))
t1.start()
    """)
        f.close()
        stdin, stdout = os.popen2(sys.executable +  ' temp.py')
        Assert('bye bye\n' in list(stdout))
    finally:
        import nt
        nt.unlink('temp.py')
Exemple #5
0
    def test_fsync(self):
        fsync_file_name = 'text_fsync.txt'
        fd = nt.open(fsync_file_name, nt.O_WRONLY | nt.O_CREAT)

        # negative test, make sure it raises on invalid (closed) fd
        try:
            nt.close(fd+1)
        except:
            pass
        self.assertRaises(OSError, nt.fsync, fd+1)

        # BUG (or implementation detail)
        # On a posix system, once written to a file descriptor
        # it can be read using another fd without any additional intervention.
        # In case of IronPython the data lingers in a stream which
        # is used to simulate file descriptor.
        fd2 = nt.open(fsync_file_name, nt.O_RDONLY)
        self.assertEqual(nt.read(fd2, 1), b'')

        nt.write(fd, b'1')
        if is_cli:
            self.assertEqual(nt.read(fd2, 1), b'') # this should be visible right away, but is not
        nt.fsync(fd)
        self.assertEqual(nt.read(fd2, 1), b'1')

        nt.close(fd)
        nt.close(fd2)

        # fsync on read file descriptor
        fd = nt.open(fsync_file_name, nt.O_RDONLY)
        if not is_cli:
            self.assertRaises(OSError, nt.fsync, fd)
        nt.close(fd)

        # fsync on rdwr file descriptor
        fd = nt.open(fsync_file_name, nt.O_RDWR)
        nt.fsync(fd)
        nt.close(fd)

        # fsync on derived fd
        if not is_cli:
            for mode in ('rb', 'r'):
                with open(fsync_file_name, mode) as f:
                    self.assertRaises(OSError, nt.fsync, f.fileno())

        for mode in ('wb', 'w'):
            with open(fsync_file_name, mode) as f:
                nt.fsync(f.fileno())

        nt.unlink(fsync_file_name)

        # fsync on pipe ends
        r,w = nt.pipe()
        if not is_cli:
            self.assertRaises(OSError, nt.fsync, r)
        nt.write(w, b'1')
        if False:
            nt.fsync(w) # this blocks
        nt.close(w)
        nt.close(r)
Exemple #6
0
def test_nonexistent_file():
    # Test invocation of a nonexistent file
    try:
        nt.unlink("nonexistent.py")
    except OSError:
        pass
    TestCommandLine(("nonexistent.py",), "File nonexistent.py does not exist.\n", 1)
def removefile(path):
    # checks that file is a FILE (not a directory) and the path contains "\\Vampire\\",
    # (or "\\"+moddir+"\\") otherwise it fails.
    if isFile(path) and path.find("\\" + moddir + "\\") > -1:
        nt.unlink(path)
    else:
        print "[Error] fileutil: removeFile called on invalid path: [%s]" % path
Exemple #8
0
def test_cp20174():
    cp20174_path = testpath.public_testdir + r"\cp20174"
    
    try:
        nt.mkdir(cp20174_path)
        
        cp20174_init = cp20174_path + r"\__init__.py"
        write_to_file(cp20174_init, "import a")
        
        cp20174_a = cp20174_path + r"\a.py"
        write_to_file(cp20174_a, """
from property import x
class C:
    def _get_x(self): return x
    x = property(_get_x)
""")
        
        cp20174_property = cp20174_path + r"\property.py"
        write_to_file(cp20174_property, "x=1")
        
        import cp20174
        AreEqual(cp20174.property.x, 1)
        
    finally:
        for x in nt.listdir(cp20174_path):
            nt.unlink(cp20174_path + "\\" + x)
        nt.rmdir(cp20174_path)
Exemple #9
0
def test_x():
    tmpxoptscript = tmpdir + '\\xopt.py'
    f = file(tmpxoptscript, "w")
    f.write("first line is garbage\nprint 2+2\n")
    f.close()
    TestCommandLine(('-x', tmpxoptscript), "4\n")
    nt.unlink(tmpxoptscript)
Exemple #10
0
def test_E():
    # Test the -E (suppress use of environment variables) option.
    
    # Re-use the generated site.py from above and verify that we can stop it being picked up from IRONPYTHONPATH
    # using -E.
    TestCommandLine(("-E", "-c", "import sys; print sys.foo"), ("lastline", "AttributeError: 'module' object has no attribute 'foo'"), 1)
    
    # Create an override startup script that exits right away
    tmpscript = tmpdir + "\\startupdie.py"
    f = file(tmpscript, "w")
    f.write("from System import Environment\nprint 'Boo!'\nEnvironment.Exit(27)\n")
    f.close()
    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript)
    TestCommandLine((), None, 27)
    
    tmpscript2 = tmpdir + "\\something.py"
    f = file(tmpscript2, "w")
    f.write("print 2+2\n")
    f.close()
    TestCommandLine(('-E', tmpscript2), "4\n")
    
    tmpscript3 = tmpdir + "\\startupdie.py"
    f = file(tmpscript3, "w")
    f.write("import sys\nprint 'Boo!'\nsys.exit(42)\n")
    f.close()
    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript3)
    TestCommandLine((), None, 42)
    
    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", "")
    nt.unlink(tmpscript)
    nt.unlink(tmpscript2)
Exemple #11
0
def test_nonexistent_file():
    # Test invocation of a nonexistent file
    try:
        nt.unlink("nonexistent.py")
    except OSError:
        pass
    TestCommandLine(("nonexistent.py",), "File nonexistent.py does not exist.\n", 1)
Exemple #12
0
def test_buffering_kwparam():
    #--Positive
    for x in [-2147483648, -1, 0, 1, 2, 1024, 2147483646, 2147483647]:
        f = file(name='some_test_file.txt', mode='w', buffering=x)
        f.close()
        nt.unlink('some_test_file.txt')

    if is_cpython:  #http://ironpython.codeplex.com/workitem/28214
        AssertErrorWithMessage(TypeError,
                               "integer argument expected, got float", file,
                               'some_test_file.txt', 'w', 3.14)
    else:
        f = file(name='some_test_file.txt', mode='w', buffering=3.14)
        f.close()
        nt.unlink('some_test_file.txt')

    #--Negative
    for x in [None, "abc", u"", [], tuple()]:
        AssertError(
            TypeError,  #"an integer is required",
            lambda: file(name='some_test_file.txt', mode='w', buffering=x))

    for x in [2147483648, -2147483649]:
        AssertError(
            OverflowError,  #"long int too large to convert to int",
            lambda: file(name='some_test_file.txt', mode='w', buffering=x))
def test_E():
    # Test the -E (suppress use of environment variables) option.

    # Re-use the generated site.py from above and verify that we can stop it being picked up from IRONPYTHONPATH
    # using -E.
    TestCommandLine(
        ("-E", "-c", "import sys; print sys.foo"),
        ("lastline", "AttributeError: 'module' object has no attribute 'foo'"),
        1)

    # Create an override startup script that exits right away
    tmpscript = tmpdir + "\\startupdie.py"
    f = file(tmpscript, "w")
    f.write(
        "from System import Environment\nprint 'Boo!'\nEnvironment.Exit(27)\n")
    f.close()
    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript)
    TestCommandLine((), None, 27)

    tmpscript2 = tmpdir + "\\something.py"
    f = file(tmpscript2, "w")
    f.write("print 2+2\n")
    f.close()
    TestCommandLine(('-E', tmpscript2), "4\n")

    tmpscript3 = tmpdir + "\\startupdie.py"
    f = file(tmpscript3, "w")
    f.write("import sys\nprint 'Boo!'\nsys.exit(42)\n")
    f.close()
    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", tmpscript3)
    TestCommandLine((), None, 42)

    Environment.SetEnvironmentVariable("IRONPYTHONSTARTUP", "")
    nt.unlink(tmpscript)
    nt.unlink(tmpscript2)
Exemple #14
0
def test_coverage():
    f = file(temp_file, 'w')
    Assert(str(f).startswith("<open file '%s', mode 'w'" % temp_file))
    Assert(f.fileno() <> -1)
    Assert(f.fileno() <> 0)

    # write
    AssertError(TypeError, f.writelines, [3])
    f.writelines(["firstline\n"])

    f.close()
    Assert(str(f).startswith("<closed file '%s', mode 'w'" % temp_file))

    # append
    f = file(temp_file, 'a+')
    f.writelines(['\n', 'secondline\n'])

    pos = len('secondline\n') + 1
    f.seek(-1 * pos, 1)

    f.writelines(['thirdline\n'])
    f.close()

    # read
    f = file(temp_file, 'r+', 512)
    f.seek(-1 * pos - 2, 2)

    AreEqual(f.readline(), 'e\n')
    AreEqual(f.readline(5), 'third')
    AreEqual(f.read(-1), 'line\n')
    AreEqual(f.read(-1), '')
    f.close()

    # read
    f = file(temp_file, 'rb', 512)
    f.seek(-1 * pos - 2, 2)

    AreEqual(f.readline(), 'e\r\n')
    AreEqual(f.readline(5), 'third')
    AreEqual(f.read(-1), 'line\r\n')
    AreEqual(f.read(-1), '')
    f.close()

    ## file op in nt
    nt.unlink(temp_file)

    fd = nt.open(temp_file, nt.O_CREAT | nt.O_WRONLY)
    nt.write(fd, "hello ")
    nt.close(fd)

    fd = nt.open(temp_file, nt.O_APPEND | nt.O_WRONLY)
    nt.write(fd, "world")
    nt.close(fd)

    fd = nt.open(temp_file, 0)
    AreEqual(nt.read(fd, 1024), "hello world")
    nt.close(fd)

    nt.unlink(temp_file)
Exemple #15
0
def test_coverage():
    f = file(temp_file, 'w')
    Assert(str(f).startswith("<open file '%s', mode 'w'" % temp_file))
    Assert(f.fileno() <> -1)
    Assert(f.fileno() <> 0)

    # write
    AssertError(TypeError, f.writelines, [3])
    f.writelines(["firstline\n"])

    f.close()
    Assert(str(f).startswith("<closed file '%s', mode 'w'" % temp_file))

    # append
    f = file(temp_file, 'a+')
    f.writelines(['\n', 'secondline\n'])

    pos = len('secondline\n') + 1
    f.seek(-1 * pos, 1)

    f.writelines(['thirdline\n'])
    f.close()

    # read
    f = file(temp_file, 'r+', 512)
    f.seek(-1 * pos - 2, 2)

    AreEqual(f.readline(), 'e\n')
    AreEqual(f.readline(5), 'third')
    AreEqual(f.read(-1), 'line\n')
    AreEqual(f.read(-1), '')
    f.close()

    # read
    f = file(temp_file, 'rb', 512)
    f.seek(-1 * pos - 2, 2)

    AreEqual(f.readline(), 'e\r\n')
    AreEqual(f.readline(5), 'third')
    AreEqual(f.read(-1), 'line\r\n')
    AreEqual(f.read(-1), '')
    f.close()

    ## file op in nt    
    nt.unlink(temp_file)

    fd = nt.open(temp_file, nt.O_CREAT | nt.O_WRONLY)
    nt.write(fd, "hello ")
    nt.close(fd)

    fd = nt.open(temp_file, nt.O_APPEND | nt.O_WRONLY)
    nt.write(fd, "world")
    nt.close(fd)

    fd = nt.open(temp_file, 0)
    AreEqual(nt.read(fd, 1024), "hello world")
    nt.close(fd)

    nt.unlink(temp_file)
Exemple #16
0
def delete_all_f(module_name):
    module = sys.modules[module_name]
    for x in dir(module):
        if x.startswith('_f_'):
            fn = getattr(module, x)
            if isinstance(fn, str):
                try:    nt.unlink(fn)
                except: pass
Exemple #17
0
def test_repr():
    class x(file):
        def __repr__(self): return 'abc'
        
    f = x('repr_does_not_exist', 'w')
    AreEqual(repr(f), 'abc')
    f.close()
    nt.unlink('repr_does_not_exist')
Exemple #18
0
def test_repr():
    class x(file):
        def __repr__(self): return 'abc'
        
    f = x('repr_does_not_exist', 'w')
    AreEqual(repr(f), 'abc')
    f.close()
    nt.unlink('repr_does_not_exist')
def delete_all_f(module_name):
    module = sys.modules[module_name]
    for x in dir(module):
        if x.startswith('_f_'):
            fn = getattr(module, x)
            if isinstance(fn, str):
                try:    nt.unlink(fn)
                except: pass
Exemple #20
0
 def test_utime(self):
     open('temp_file_does_not_exist.txt', 'w').close()
     import nt
     x = nt.stat('.')
     nt.utime('temp_file_does_not_exist.txt', (x[7], x[8]))
     y = nt.stat('temp_file_does_not_exist.txt')
     self.assertEqual(x[7], y[7])
     self.assertEqual(x[8], y[8])
     nt.unlink('temp_file_does_not_exist.txt')
Exemple #21
0
    def test_fsync(self):
        fsync_file_name = 'text_fsync.txt'
        fd = nt.open(fsync_file_name, nt.O_WRONLY | nt.O_CREAT)

        # negative test, make sure it raises on invalid (closed) fd
        try:
            nt.close(fd+1)
        except:
            pass
        self.assertRaises(OSError, nt.fsync, fd+1)

        # BUG (or implementation detail)
        # On a posix system, once written to a file descriptor
        # it can be read using another fd without any additional intervention.
        # In case of IronPython the data lingers in a stream which
        # is used to simulate file descriptor.
        fd2 = nt.open(fsync_file_name, nt.O_RDONLY)
        self.assertEqual(nt.read(fd2, 1), '')

        nt.write(fd, '1')
        self.assertEqual(nt.read(fd2, 1), '') # this should be visible right away, but is not
        nt.fsync(fd)
        self.assertEqual(nt.read(fd2, 1), '1')

        nt.close(fd)
        nt.close(fd2)

        # fsync on read file descriptor
        fd = nt.open(fsync_file_name, nt.O_RDONLY)
        self.assertRaises(OSError, nt.fsync, fd)
        nt.close(fd)

        # fsync on rdwr file descriptor
        fd = nt.open(fsync_file_name, nt.O_RDWR)
        nt.fsync(fd)
        nt.close(fd)

        # fsync on derived fd
        for mode in ('rb', 'r'):
            f = open(fsync_file_name, mode)
            self.assertRaises(OSError, nt.fsync, f.fileno())
            f.close()

        for mode in ('wb', 'w'):
            f = open(fsync_file_name, mode)
            nt.fsync(f.fileno())
            f.close()

        nt.unlink(fsync_file_name)

        # fsync on pipe ends
        r,w = nt.pipe()
        self.assertRaises(OSError, nt.fsync, r)
        nt.write(w, '1')
        nt.fsync(w)
        nt.close(w)
        nt.close(r)
Exemple #22
0
def test_modes():
    """test various strange mode combinations and error reporting"""
    try:
        x = file('test_file', 'w')
        AreEqual(x.mode, 'w')
        x.close()
        # don't allow empty modes
        AssertErrorWithMessage(ValueError, 'empty mode string', file, 'abc',
                               '')

        # mode must start with valid value
        AssertErrorWithMessage(
            ValueError,
            "mode string must begin with one of 'r', 'w', 'a' or 'U', not 'p'",
            file, 'abc', 'p')

        # allow anything w/ U but r and w
        AssertErrorWithMessage(
            ValueError,
            "universal newline mode can only be used with modes starting with 'r'",
            file, 'abc', 'Uw')
        AssertErrorWithMessage(
            ValueError,
            "universal newline mode can only be used with modes starting with 'r'",
            file, 'abc', 'Ua')
        AssertErrorWithMessage(
            ValueError,
            "universal newline mode can only be used with modes starting with 'r'",
            file, 'abc', 'Uw+')
        AssertErrorWithMessage(
            ValueError,
            "universal newline mode can only be used with modes starting with 'r'",
            file, 'abc', 'Ua+')

        if is_cli:
            #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21910
            x = file('test_file', 'pU')
            AreEqual(x.mode, 'pU')
            x.close()

            #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21910
            x = file('test_file', 'pU+')
            AreEqual(x.mode, 'pU+')
            x.close()

            #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21911
            # extra info can be passed and is retained
            x = file('test_file', 'rFOOBAR')
            AreEqual(x.mode, 'rFOOBAR')
            x.close()
        else:
            AssertError(IOError, file, 'test_file', 'pU')
            AssertError(IOError, file, 'test_file', 'pU+')
            AssertError(IOError, file, 'test_file', 'rFOOBAR')
    finally:
        nt.unlink('test_file')
Exemple #23
0
 def f():
     import nt
     f = file('temptest.py', 'w+')
     f.write('foo = 42')
     f.close()
     try:
         from temptest import *
     finally:
         nt.unlink('temptest.py')
     return foo
Exemple #24
0
def test_write_bytes():
    f = open("temp_ip", "w+")
    try:
        f.write(b"Hello\n")
        f.close()
        f = file('temp_ip')
        AreEqual(f.readlines(), ['Hello\n'])
        f.close()
    finally:
        nt.unlink('temp_ip')
Exemple #25
0
def test_inheritance_kwarg_override():
    class TEST(file):
        def __init__(self, fname, VERBOSITY=0):
            file.__init__(self, fname, "w", 1)
            self.VERBOSITY = VERBOSITY

    f = TEST(r'sometext.txt', VERBOSITY=1)
    AreEqual(f.VERBOSITY, 1)
    f.close()
    nt.unlink('sometext.txt')
Exemple #26
0
def test_utime():
    f = file('temp_file_does_not_exist.txt', 'w')
    f.close()
    import nt
    x = nt.stat('.')
    nt.utime('temp_file_does_not_exist.txt', (x[7], x[8]))
    y = nt.stat('temp_file_does_not_exist.txt')
    AreEqual(x[7], y[7])
    AreEqual(x[8], y[8])
    nt.unlink('temp_file_does_not_exist.txt')
 def f():
     import nt
     f = file('temptest.py', 'w+')
     f.write('foo = 42')
     f.close()
     try:
         exec(compile(open('temptest.py').read(), 'temptest.py', 'exec'))
     finally:
         nt.unlink('temptest.py')
     return foo
 def f():
     import nt
     f = file('temptest.py', 'w+')
     f.write('foo = 42')
     f.close()
     try:
         from temptest import *
     finally:
         nt.unlink('temptest.py')
     return foo
Exemple #29
0
def test_utime():
    f = file('temp_file_does_not_exist.txt', 'w')
    f.close()
    import nt
    x = nt.stat('.')
    nt.utime('temp_file_does_not_exist.txt', (x[7], x[8]))
    y = nt.stat('temp_file_does_not_exist.txt')
    AreEqual(x[7], y[7])
    AreEqual(x[8], y[8])
    nt.unlink('temp_file_does_not_exist.txt')
Exemple #30
0
def test_write_bytes():
    f = open("temp_ip", "w+")
    try:
        f.write(b"Hello\n")
        f.close()
        f = file('temp_ip')
        AreEqual(f.readlines(), ['Hello\n'])
        f.close()
    finally:
        nt.unlink('temp_ip')
Exemple #31
0
def test_inheritance_kwarg_override():
    class TEST(file):
        def __init__(self,fname,VERBOSITY=0):
            file.__init__(self,fname,"w",1)
            self.VERBOSITY = VERBOSITY
    
    f=TEST(r'sometext.txt',VERBOSITY=1)
    AreEqual(f.VERBOSITY, 1)
    f.close()
    nt.unlink('sometext.txt')
Exemple #32
0
def test_sharing():
    modes = ['w', 'w+', 'a+', 'r', 'w']
    for xx in modes:
        for yy in modes:
            x = file('tempfile.txt', xx)
            y = file('tempfile.txt', yy)
            
            x.close()
            y.close()
            
    nt.unlink('tempfile.txt')
Exemple #33
0
    def f():
        import nt

        f = file("temptest.py", "w+")
        f.write("foo = 42")
        f.close()
        try:
            from temptest import *
        finally:
            nt.unlink("temptest.py")
        return foo
Exemple #34
0
def test_imp_load_dynamic():
    #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
    if not is_cpython:
        AreEqual(imp.load_dynamic("", ""), None)
        try:
            _x_mod = path_combine(testpath.public_testdir, "x.py")
            write_to_file(_x_mod, "")
            with open(_x_mod, "r") as f:
                AreEqual(imp.load_dynamic("", "", f), None)
        finally:
            nt.unlink(_x_mod)        
Exemple #35
0
def test_sharing():
    modes = ['w', 'w+', 'a+', 'r', 'w']
    for xx in modes:
        for yy in modes:
            x = file('tempfile.txt', xx)
            y = file('tempfile.txt', yy)

            x.close()
            y.close()

    nt.unlink('tempfile.txt')
Exemple #36
0
def test_utime():
    f = file("temp_file_does_not_exist.txt", "w")
    f.close()
    import nt

    x = nt.stat(".")
    nt.utime("temp_file_does_not_exist.txt", (x[7], x[8]))
    y = nt.stat("temp_file_does_not_exist.txt")
    AreEqual(x[7], y[7])
    AreEqual(x[8], y[8])
    nt.unlink("temp_file_does_not_exist.txt")
Exemple #37
0
def test_imp_load_dynamic():
    #http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17459
    if not is_cpython:
        AreEqual(imp.load_dynamic("", ""), None)
        try:
            _x_mod = path_combine(testpath.public_testdir, "x.py")
            write_to_file(_x_mod, "")
            with open(_x_mod, "r") as f:
                AreEqual(imp.load_dynamic("", "", f), None)
        finally:
            nt.unlink(_x_mod)        
Exemple #38
0
def test___import___and_packages():
    try:
        mod_backup = dict(sys.modules)
        _f_module = path_combine(testpath.public_testdir, 'the_test.py')
        _f_dir    = path_combine(testpath.public_testdir, 'the_dir')
        _f_init   = path_combine(_f_dir, '__init__.py')
        _f_pkg_y  = path_combine(_f_dir, 'y.py')
        _f_y      = path_combine(testpath.public_testdir, 'y.py')
                
        # write the files
        ensure_directory_present(_f_dir)
        write_to_file(_f_module, 'import the_dir.y\n')
        write_to_file(_f_init, '')
        write_to_file(_f_pkg_y, 'a=1\ny = __import__("y")\nimport sys\n')
        write_to_file(_f_y, 'a=2\n')
        
        import y
        AreEqual(y.a, 2)
        
        sys.modules = mod_backup
        mod_backup = dict(sys.modules)
        
        y = __import__('y', globals(), locals())
        AreEqual(y.a, 2)
        
    finally:
        sys.modules = mod_backup
        nt.unlink(_f_module)
        nt.unlink(_f_init)
        nt.unlink(_f_pkg_y)
        nt.unlink(_f_y)
Exemple #39
0
def test_overwrite_readonly():
    filename = "tmp.txt"
    f = file(filename, "w+")
    f.write("I am read-only")
    f.close()
    nt.chmod(filename, 256)
    try:
        try:
            f = file(filename, "w+") # FAIL
        finally:
            nt.chmod(filename, 128)
            nt.unlink(filename)
    except IOError, e:
        pass
Exemple #40
0
def test_module_alias_cp19656():
    stuff_mod = path_combine(testpath.public_testdir, "stuff.py")
    check_mod = path_combine(testpath.public_testdir, "check.py")

    try:
        write_to_file(stuff_mod, "Keys = 3")
        write_to_file(check_mod, "def check(module):\n    return module.Keys")
        import stuff
        from check import check
        AreEqual(check(stuff), 3)
    finally:
        import nt
        nt.unlink(stuff_mod)
        nt.unlink(check_mod)
Exemple #41
0
def test___import___and_packages():
    try:
        mod_backup = dict(sys.modules)
        _f_module = path_combine(testpath.public_testdir, 'the_test.py')
        _f_dir = path_combine(testpath.public_testdir, 'the_dir')
        _f_init = path_combine(_f_dir, '__init__.py')
        _f_pkg_y = path_combine(_f_dir, 'y.py')
        _f_y = path_combine(testpath.public_testdir, 'y.py')

        # write the files
        ensure_directory_present(_f_dir)
        write_to_file(_f_module, 'import the_dir.y\n')
        write_to_file(_f_init, '')
        write_to_file(_f_pkg_y, 'a=1\ny = __import__("y")\nimport sys\n')
        write_to_file(_f_y, 'a=2\n')

        import y
        AreEqual(y.a, 2)

        sys.modules = mod_backup
        mod_backup = dict(sys.modules)

        y = __import__('y', globals(), locals())
        AreEqual(y.a, 2)

    finally:
        sys.modules = mod_backup
        nt.unlink(_f_module)
        nt.unlink(_f_init)
        nt.unlink(_f_pkg_y)
        nt.unlink(_f_y)
Exemple #42
0
    def test_remove_negative(self):
        import stat
        self.assertRaisesNumber(WindowsError, errno.ENOENT, lambda : nt.remove('some_file_that_does_not_exist'))
        try:
            open('some_test_file.txt', 'w').close()
            nt.chmod('some_test_file.txt', stat.S_IREAD)
            self.assertRaisesNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
            nt.chmod('some_test_file.txt', stat.S_IWRITE)

            with open('some_test_file.txt', 'w+'):
                self.assertRaisesNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
        finally:
            nt.chmod('some_test_file.txt', stat.S_IWRITE)
            nt.unlink('some_test_file.txt')
Exemple #43
0
def test_overwrite_readonly():
    filename = "tmp.txt"
    f = file(filename, "w+")
    f.write("I am read-only")
    f.close()
    nt.chmod(filename, 256)
    try:
        try:
            f = file(filename, "w+")  # FAIL
        finally:
            nt.chmod(filename, 128)
            nt.unlink(filename)
    except IOError, e:
        pass
Exemple #44
0
def test_module_alias_cp19656():
    stuff_mod = path_combine(testpath.public_testdir, "stuff.py")
    check_mod = path_combine(testpath.public_testdir, "check.py")
    
    try:
        write_to_file(stuff_mod, "Keys = 3")
        write_to_file(check_mod, "def check(module):\n    return module.Keys")
        import stuff
        from check import check
        AreEqual(check(stuff), 3)
    finally:
        import nt
        nt.unlink(stuff_mod)
        nt.unlink(check_mod)
Exemple #45
0
def test_import_globals():
    _f_dir = path_combine(testpath.public_testdir, "the_dir2")
    _f_x = path_combine(_f_dir, "x")
    _f_init = path_combine(_f_x, "__init__.py")
    _f_dir_init = path_combine(_f_dir, "__init__.py")
    _f_x_y = path_combine(_f_x, "y.py")
    _f_y = path_combine(_f_dir, "y.py")
    _f_test = path_combine(_f_dir, "test.py")

    backup = dict(sys.modules)
    try:
        write_to_file(_f_init, "")
        write_to_file(_f_dir_init, "")
        write_to_file(
            _f_x_y,
            """
import sys
a = 1

class mydict(object):
    def __init__(self, items):
        self.items = items
    def __getitem__(self, index):
        return self.items[index]

sys.test1 = __import__("y").a
sys.test2 = __import__("y", {'__name__' : 'the_dir2.x.y'}).a
sys.test3 = __import__("y", mydict({'__name__' : 'the_dir2.x.y'})).a
sys.test4 = __import__("y", {}, {'__name__' : 'the_dir2.x.y'}).a
""",
        )
        write_to_file(_f_y, "a = 2")
        write_to_file(_f_test, "import x.y\n")

        import the_dir2.test

        AreEqual(sys.test1, 2)
        AreEqual(sys.test2, 1)
        AreEqual(sys.test2, 1)
        AreEqual(sys.test2, 1)
    finally:
        sys.modules = backup
        import nt

        nt.unlink(_f_init)
        nt.unlink(_f_dir_init)
        nt.unlink(_f_x_y)
        nt.unlink(_f_y)
        nt.unlink(_f_test)
Exemple #46
0
def test_subclassing_builtins():
    class MyFile(file):
        myfield = 0

    f = MyFile('temporary.deleteme', 'w')
    AreEqual(f.myfield, 0)
    f.close()
    import nt
    nt.unlink('temporary.deleteme')

    class C(list):
        def __eq__(self, other):
            return 'Passed'

    AreEqual(C() == 1, 'Passed')
Exemple #47
0
def test_remove_negative():
    import stat
    AssertErrorWithNumber(WindowsError, errno.ENOENT, lambda : nt.remove('some_file_that_does_not_exist'))
    try:
        file('some_test_file.txt', 'w').close()
        nt.chmod('some_test_file.txt', stat.S_IREAD)
        AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
        nt.chmod('some_test_file.txt', stat.S_IWRITE)
        
        f = file('some_test_file.txt', 'w+')
        AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
        f.close()
    finally:
        nt.chmod('some_test_file.txt', stat.S_IWRITE)
        nt.unlink('some_test_file.txt')
Exemple #48
0
def test_remove_negative():
    import stat
    AssertErrorWithNumber(WindowsError, errno.ENOENT, lambda : nt.remove('some_file_that_does_not_exist'))
    try:
        file('some_test_file.txt', 'w').close()
        nt.chmod('some_test_file.txt', stat.S_IREAD)
        AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
        nt.chmod('some_test_file.txt', stat.S_IWRITE)
        
        f = file('some_test_file.txt', 'w+')
        AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
        f.close()
    finally:
        nt.chmod('some_test_file.txt', stat.S_IWRITE)
        nt.unlink('some_test_file.txt')
def test_imp_load_source():
    import nt
    try:
        _x_mod = path_combine(testpath.public_testdir, "x.py")
        write_to_file(_x_mod, """
'''some pydoc'''
X = 3.14
""")
        with open(_x_mod, "r") as f:
            x = imp.load_source("test_imp_load_source_x", _x_mod, f)
        AreEqual(x.__name__, "test_imp_load_source_x")
        AreEqual(x.X, 3.14)
        AreEqual(x.__doc__, '''some pydoc''')
    finally:
        nt.unlink(_x_mod)
Exemple #50
0
def test_buffering_kwparam():
    #--Positive
    for x in [-2147483648, -1, 0, 1, 2, 1024, 2147483646, 2147483647, 3.14]:
        f = file(name = 'some_test_file.txt', mode = 'w', buffering=x)
        f.close()
        nt.unlink('some_test_file.txt')
    
    #--Negative
    for x in [None, "abc", u"", [], tuple()]:
        AssertError(TypeError, #"an integer is required",
                   lambda: file(name = 'some_test_file.txt', mode = 'w', buffering=x))
    
    for x in [2147483648, -2147483649]:
        AssertError(OverflowError, #"long int too large to convert to int",
                    lambda: file(name = 'some_test_file.txt', mode = 'w', buffering=x))
Exemple #51
0
def test_ximp_load_module():
    mod = imp.new_module('my_module_test')
    mod.__file__ = 'does_not_exist.py'
    sys.modules['my_module_test'] = mod
    
    f = file('test.py', 'w+')
    f.write('x = 42')
    f.close()
    
    with file('test.py') as inp_file:
        imp.load_module('my_module_test', inp_file, 'does_not_exist.py', ('', 'U', 1))
        
    import nt
    nt.unlink('test.py')
        
    AreEqual(mod.x, 42)
Exemple #52
0
def test_ximp_load_module():
    mod = imp.new_module('my_module_test')
    mod.__file__ = 'does_not_exist.py'
    sys.modules['my_module_test'] = mod
    
    f = file('test.py', 'w+')
    f.write('x = 42')
    f.close()
    
    with file('test.py') as inp_file:
        imp.load_module('my_module_test', inp_file, 'does_not_exist.py', ('', 'U', 1))
        
    import nt
    nt.unlink('test.py')
        
    AreEqual(mod.x, 42)
Exemple #53
0
def test_overwrite_readonly():
    filename = "tmp.txt"
    f = file(filename, "w+")
    f.write("I am read-only")
    f.close()
    nt.chmod(filename, 256)
    try:
        try:
            f = file(filename, "w+") # FAIL
        finally:
            nt.chmod(filename, 128)
            nt.unlink(filename)
    except IOError as e:
        pass
    else:
        AssertUnreachable() # should throw
Exemple #54
0
def test_subclassing_builtins():
    class MyFile(file):
        myfield = 0
    
    f = MyFile('temporary.deleteme','w')
    AreEqual(f.myfield, 0)
    f.close()
    import nt
    nt.unlink('temporary.deleteme')
    
    
    class C(list):
        def __eq__(self, other):
            return 'Passed'
    
    AreEqual(C() == 1, 'Passed')
Exemple #55
0
def test_imp_load_source():
    import nt
    try:
        _x_mod = path_combine(testpath.public_testdir, "x.py")
        write_to_file(_x_mod, """
'''some pydoc'''
X = 3.14
""")
        with open(_x_mod, "r") as f:
            x = imp.load_source("test_imp_load_source_x",
                                _x_mod,
                                f)
        AreEqual(x.__name__, "test_imp_load_source_x")
        AreEqual(x.X, 3.14)
        AreEqual(x.__doc__, '''some pydoc''')
    finally:
        nt.unlink(_x_mod)
Exemple #56
0
    def test_open(self):
        file('temp.txt', 'w+').close()
        try:
            fd = nt.open('temp.txt', nt.O_WRONLY | nt.O_CREAT)
            nt.close(fd)

            self.assertRaisesNumber(OSError, 17, nt.open, 'temp.txt',
                                    nt.O_CREAT | nt.O_EXCL)
            for flag in [nt.O_EXCL, nt.O_APPEND]:
                fd = nt.open('temp.txt', nt.O_RDONLY | flag)
                nt.close(fd)

                fd = nt.open('temp.txt', nt.O_WRONLY | flag)
                nt.close(fd)

                fd = nt.open('temp.txt', nt.O_RDWR | flag)
                nt.close(fd)

            # sanity test
            tempfilename = "temp.txt"
            fd = nt.open(tempfilename, 256, 1)
            nt.close(fd)

            nt.unlink('temp.txt')

            f = nt.open('temp.txt', nt.O_TEMPORARY | nt.O_CREAT)
            nt.close(f)
            self.assertRaises(OSError, nt.stat, 'temp.txt')

            # TODO: These tests should probably test more functionality regarding O_SEQUENTIAL/O_RANDOM
            f = nt.open(
                'temp.txt',
                nt.O_TEMPORARY | nt.O_CREAT | nt.O_SEQUENTIAL | nt.O_RDWR)
            nt.close(f)
            self.assertRaises(OSError, nt.stat, 'temp.txt')

            f = nt.open('temp.txt',
                        nt.O_TEMPORARY | nt.O_CREAT | nt.O_RANDOM | nt.O_RDWR)
            nt.close(f)
            self.assertRaises(OSError, nt.stat, 'temp.txt')
        finally:
            try:
                # should fail if the file doesn't exist
                nt.unlink('temp.txt')
            except:
                pass
Exemple #57
0
def test_cp7766():
    if __name__=="__main__":
        AreEqual(type(__builtins__), type(sys))
    else:
        AreEqual(type(__builtins__), dict)
        
    try:
        _t_test = testpath.public_testdir + "\\cp7766.py"
        write_to_file(_t_test, "temp = __builtins__")
    
        import cp7766
        AreEqual(type(cp7766.temp), dict)
        Assert(cp7766.temp != __builtins__)
        
    finally:
        import nt
        nt.unlink(_t_test)
def test_cp11923_first():
    try:
        _t_test = testpath.public_testdir + "\\cp11923.py"
        write_to_file(_t_test, """def f():
    x = 'something bad'
    raise Exception(x)""")
        
        import cp11923
        for i in xrange(3):
            try:
                cp11923.f()
            except:
                assert_traceback([(Line263 + 11, 69, 'test_traceback.py', 'test_cp11923_first'), (3, 22, get_full_dir_name(_t_test).lower(), 'f')])
            reload(cp11923)
        
    finally:
        import nt
        nt.unlink(_t_test)
Exemple #59
0
def test_cp12009():
    import nt
    import shutil
    
    dir1 = "temp_test_stdmodules_dir"
    dir2 = dir1 + "2"
    
    nt.mkdir(dir1)
    f = open(dir1 + r"\stuff.txt", "w")
    f.close()
    
    try:
        shutil.copytree(dir1, dir2)
        Assert("stuff.txt" in nt.listdir(dir2))
    finally:
        for t_dir in [dir1, dir2]:
            nt.unlink(t_dir + r"\stuff.txt")
            nt.rmdir(t_dir)
Exemple #60
0
def test_access():
    f = file('new_file_name', 'w')
    f.close()
    
    AreEqual(nt.access('new_file_name', nt.F_OK), True)
    AreEqual(nt.access('does_not_exist.py', nt.F_OK), False)

    nt.chmod('new_file_name', 0x100) # S_IREAD
    AreEqual(nt.access('new_file_name', nt.W_OK), False)
    nt.chmod('new_file_name', 0x80)  # S_IWRITE
        
    nt.unlink('new_file_name')
    
    nt.mkdir('new_dir_name')
    AreEqual(nt.access('new_dir_name', nt.R_OK), True)
    nt.rmdir('new_dir_name')
    
    AssertError(TypeError, nt.access, None, 1)