# -*- coding: utf-8 -*-from__future__importwith_statementfrompypy.objspace.stdimportStdObjSpacefrompypy.tool.udirimportudirfrompypy.tool.pytest.objspaceimportgettestobjspacefrompypy.tool.autopathimportpypydirfrompypy.rpython.module.ll_osimportRegisterOsimportosimportpyimportsysimportsignaldefsetup_module(mod):ifos.name!='nt':mod.space=gettestobjspace(usemodules=['posix','fcntl','struct'])else:# On windows, os.popen uses the subprocess modulemod.space=gettestobjspace(usemodules=['posix','_rawffi','thread','struct'])mod.path=udir.join('posixtestfile.txt')mod.path.write("this is a test")mod.path2=udir.join('test_posix2-')pdir=udir.ensure('posixtestdir',dir=True)pdir.join('file1').write("test1")os.chmod(str(pdir.join('file1')),0600)pdir.join('file2').write("test2")pdir.join('another_longer_file_name').write("test3")mod.pdir=pdirunicode_dir=udir.ensure('fi\xc5\x9fier.txt',dir=True)unicode_dir.join('somefile').write('who cares?')unicode_dir.join('caf\xe9').write('who knows?')mod.unicode_dir=unicode_dir# in applevel tests, os.stat uses the CPython os.stat.# Be sure to return times with full precision# even when running on top of CPython 2.4.os.stat_float_times(True)# Initialize sys.filesystemencoding# space.call_method(space.getbuiltinmodule('sys'), 'getfilesystemencoding')defneed_sparse_files():ifsys.platform=='darwin':py.test.skip("no sparse files on default Mac OS X file system")ifos.name=='nt':py.test.skip("no sparse files on Windows")GET_POSIX="(): import %s as m ; return m"%os.nameclassAppTestPosix:defsetup_class(cls):cls.space=spacecls.w_posix=space.appexec([],GET_POSIX)cls.w_path=space.wrap(str(path))cls.w_path2=space.wrap(str(path2))cls.w_pdir=space.wrap(str(pdir))try:cls.w_unicode_dir=space.wrap(str(unicode_dir).decode(sys.getfilesystemencoding()))exceptUnicodeDecodeError:# filesystem encoding is not good enoughcls.w_unicode_dir=space.w_Noneifhasattr(os,'getuid'):cls.w_getuid=space.wrap(os.getuid())cls.w_geteuid=space.wrap(os.geteuid())ifhasattr(os,'getgid'):cls.w_getgid=space.wrap(os.getgid())ifhasattr(os,'getgroups'):cls.w_getgroups=space.newlist([space.wrap(e)foreinos.getgroups()])ifhasattr(os,'getpgid'):cls.w_getpgid=space.wrap(os.getpgid(os.getpid()))ifhasattr(os,'getsid'):cls.w_getsid0=space.wrap(os.getsid(0))ifhasattr(os,'sysconf'):sysconf_name=os.sysconf_names.keys()[0]cls.w_sysconf_name=space.wrap(sysconf_name)cls.w_sysconf_value=space.wrap(os.sysconf_names[sysconf_name])cls.w_sysconf_result=space.wrap(os.sysconf(sysconf_name))cls.w_SIGABRT=space.wrap(signal.SIGABRT)cls.w_python=space.wrap(sys.executable)ifhasattr(os,'major'):cls.w_expected_major_12345=space.wrap(os.major(12345))cls.w_expected_minor_12345=space.wrap(os.minor(12345))cls.w_udir=space.wrap(str(udir))defsetup_method(self,meth):ifgetattr(meth,'need_sparse_files',False):need_sparse_files()deftest_posix_is_pypy_s(self):assertself.posix.__file__deftest_some_posix_basic_operation(self):path=self.pathposix=self.posixfd=posix.open(path,posix.O_RDONLY,0777)fd2=posix.dup(fd)assertnotposix.isatty(fd2)s=posix.read(fd,1)asserts=='t'posix.lseek(fd,5,0)s=posix.read(fd,1)asserts=='i'st=posix.fstat(fd)posix.close(fd2)posix.close(fd)importsys,statassertst[0]==st.st_modeassertst[1]==st.st_inoassertst[2]==st.st_devassertst[3]==st.st_nlinkassertst[4]==st.st_uidassertst[5]==st.st_gidassertst[6]==st.st_sizeassertst[7]==int(st.st_atime)assertst[8]==int(st.st_mtime)assertst[9]==int(st.st_ctime)assertstat.S_IMODE(st.st_mode)&stat.S_IRUSRassertstat.S_IMODE(st.st_mode)&stat.S_IWUSRifnotsys.platform.startswith('win'):assertnot(stat.S_IMODE(st.st_mode)&stat.S_IXUSR)assertst.st_size==14assertst.st_nlink==1#if sys.platform.startswith('linux'):# # expects non-integer timestamps - it's unlikely that they are# # all three integers# assert ((st.st_atime, st.st_mtime, st.st_ctime) !=# (st[7], st[8], st[9]))# assert st.st_blksize * st.st_blocks >= st.st_sizeifsys.platform.startswith('linux'):asserthasattr(st,'st_rdev')deftest_stat_float_times(self):path=self.pathposix=self.posixcurrent=posix.stat_float_times()assertcurrentisTruetry:posix.stat_float_times(True)st=posix.stat(path)assertisinstance(st.st_mtime,float)assertst[7]==int(st.st_atime)posix.stat_float_times(False)st=posix.stat(path)assertisinstance(st.st_mtime,(int,long))assertst[7]==st.st_atimefinally:posix.stat_float_times(current)deftest_stat_result(self):st=self.posix.stat_result((0,0,0,0,0,0,0,41,42.1,43))assertst.st_atime==41assertst.st_mtime==42.1assertst.st_ctime==43deftest_stat_lstat(self):importstatst=self.posix.stat(".")assertstat.S_ISDIR(st.st_mode)st=self.posix.lstat(".")assertstat.S_ISDIR(st.st_mode)deftest_stat_exception(self):importsys,errnoforfnin[self.posix.stat,self.posix.lstat]:try:fn("nonexistentdir/nonexistentfile")exceptOSError,e:asserte.errno==errno.ENOENTasserte.filename=="nonexistentdir/nonexistentfile"# On Windows, when the parent directory does not exist,# the winerror is 3 (cannot find the path specified)# instead of 2 (cannot find the file specified)ifsys.platform=='win32':assertisinstance(e,WindowsError)asserte.winerror==3deftest_pickle(self):importpickle,osst=self.posix.stat(os.curdir)printtype(st).__module__s=pickle.dumps(st)printrepr(s)new=pickle.loads(s)assertnew==stasserttype(new)istype(st)deftest_open_exception(self):posix=self.posixtry:posix.open('qowieuqwoeiu',0,0)exceptOSError,e:asserte.filename=='qowieuqwoeiu'else:assert0deftest_filename_exception(self):forfnamein['unlink','remove','chdir','mkdir','rmdir','listdir','readlink','chroot']:ifhasattr(self.posix,fname):func=getattr(self.posix,fname)try:func('qowieuqw/oeiu')exceptOSError,e:asserte.filename=='qowieuqw/oeiu'else:assert0deftest_chmod_exception(self):try:self.posix.chmod('qowieuqw/oeiu',0)exceptOSError,e:asserte.filename=='qowieuqw/oeiu'else:assert0deftest_chown_exception(self):ifhasattr(self.posix,'chown'):try:self.posix.chown('qowieuqw/oeiu',0,0)exceptOSError,e:asserte.filename=='qowieuqw/oeiu'else:assert0deftest_utime_exception(self):forargin[None,(0,0)]:try:self.posix.utime('qowieuqw/oeiu',arg)exceptOSError,e:asserte.filename=='qowieuqw/oeiu'else:assert0deftest_functions_raise_error(self):defex(func,*args):try:func(*args)exceptOSError:passelse:raiseAssertionError("%s(%s) did not raise"%(func.__name__,", ".join([str(x)forxinargs])))UNUSEDFD=123123ex(self.posix.open,"qweqwe",0,0)ex(self.posix.lseek,UNUSEDFD,123,0)#apparently not posix-required: ex(self.posix.isatty, UNUSEDFD)ex(self.posix.read,UNUSEDFD,123)ex(self.posix.write,UNUSEDFD,"x")ex(self.posix.close,UNUSEDFD)#UMPF cpython raises IOError ex(self.posix.ftruncate, UNUSEDFD, 123)ex(self.posix.fstat,UNUSEDFD)ex(self.posix.stat,"qweqwehello")# how can getcwd() raise?ex(self.posix.dup,UNUSEDFD)deftest_fdopen(self):importerrnopath=self.pathposix=self.posixfd=posix.open(path,posix.O_RDONLY,0777)f=posix.fdopen(fd,"r")f.close()# Ensure that fcntl is not fakedtry:importfcntlexceptImportError:passelse:assertfcntl.__file__.endswith('pypy/module/fcntl')exc=raises(OSError,posix.fdopen,fd)assertexc.value.errno==errno.EBADFdeftest_fdopen_hackedbuiltins(self):"Same test, with __builtins__.file removed"_file=__builtins__.file__builtins__.file=Nonetry:path=self.pathposix=self.posixfd=posix.open(path,posix.O_RDONLY,0777)f=posix.fdopen(fd,"r")f.close()finally:__builtins__.file=_filedeftest_getcwd(self):assertisinstance(self.posix.getcwd(),str)assertisinstance(self.posix.getcwdu(),unicode)assertself.posix.getcwd()==self.posix.getcwdu()deftest_listdir(self):pdir=self.pdirposix=self.posixresult=posix.listdir(pdir)result.sort()assertresult==['another_longer_file_name','file1','file2']deftest_listdir_unicode(self):importsysunicode_dir=self.unicode_dirifunicode_dirisNone:skip("encoding not good enough")posix=self.posixresult=posix.listdir(unicode_dir)typed_result=[(type(x),x)forxinresult]assert(unicode,u'somefile')intyped_resulttry:u="caf\xe9".decode(sys.getfilesystemencoding())exceptUnicodeDecodeError:# Could not decode, listdir returned the byte stringassert(str,"caf\xe9")intyped_resultelse:assert(unicode,u)intyped_resultdeftest_access(self):pdir=self.pdir+'/file1'posix=self.posixassertposix.access(pdir,posix.R_OK)assertposix.access(pdir,posix.W_OK)importsysifsys.platform!="win32":assertnotposix.access(pdir,posix.X_OK)deftest_times(self):""" posix.times() should return a five-tuple giving float-representations (seconds, effectively) of the four fields from the underlying struct tms and the return value. """result=self.posix.times()assertisinstance(result,tuple)assertlen(result)==5forvalueinresult:assertisinstance(value,float)deftest_strerror(self):assertisinstance(self.posix.strerror(0),str)assertisinstance(self.posix.strerror(1),str)ifhasattr(__import__(os.name),"fork"):deftest_fork(self):os=self.posixpid=os.fork()ifpid==0:# childos._exit(4)pid1,status1=os.waitpid(pid,0)assertpid1==pidassertos.WIFEXITED(status1)assertos.WEXITSTATUS(status1)==4pass# <- please, inspect.getsource(), don't crashifhasattr(__import__(os.name),"openpty"):deftest_openpty(self):os=self.posixmaster_fd,slave_fd=os.openpty()assertisinstance(master_fd,int)assertisinstance(slave_fd,int)os.write(slave_fd,'x\n')data=os.read(master_fd,100)assertdata.startswith('x')ifhasattr(__import__(os.name),"forkpty"):deftest_forkpty(self):importsysif'freebsd'insys.platform:skip("hangs indifinitly on FreeBSD (also on CPython).")os=self.posixchildpid,master_fd=os.forkpty()assertisinstance(childpid,int)assertisinstance(master_fd,int)ifchildpid==0:data=os.read(0,100)ifdata.startswith('abc'):os._exit(42)else:os._exit(43)os.write(master_fd,'abc\n')_,status=os.waitpid(childpid,0)assertstatus>>8==42ifhasattr(__import__(os.name),"execv"):deftest_execv(self):os=self.posixifnothasattr(os,"fork"):skip("Need fork() to test execv()")pid=os.fork()ifpid==0:os.execv("/usr/bin/env",["env","python","-c","open('onefile', 'w').write('1')"])os.waitpid(pid,0)assertopen("onefile").read()=="1"os.unlink("onefile")deftest_execv_raising(self):os=self.posixraises(OSError,'os.execv("saddsadsadsadsa", ["saddsadsasaddsa"])')deftest_execv_no_args(self):os=self.posixraises(ValueError,os.execv,"notepad",[])raises(ValueError,os.execve,"notepad",[],{})deftest_execv_raising2(self):os=self.posixfornin3,[3,"a"]:try:os.execv("xxx",n)exceptTypeError,t:assertstr(t)=="execv() arg 2 must be an iterable of strings"else:py.test.fail("didn't raise")deftest_execv_unicode(self):os=self.posiximportsysifnothasattr(os,"fork"):skip("Need fork() to test execv()")try:output=u"caf\xe9\u1234\n".encode(sys.getfilesystemencoding())exceptUnicodeEncodeError:skip("encoding not good enough")pid=os.fork()ifpid==0:os.execv(u"/bin/sh",["sh","-c",u"echo caf\xe9\u1234 > onefile"])os.waitpid(pid,0)assertopen("onefile").read()==outputos.unlink("onefile")deftest_execve(self):os=self.posixifnothasattr(os,"fork"):skip("Need fork() to test execve()")pid=os.fork()ifpid==0:os.execve("/usr/bin/env",["env","python","-c","import os; open('onefile', 'w').write(os.environ['ddd'])"],{'ddd':'xxx'})os.waitpid(pid,0)assertopen("onefile").read()=="xxx"os.unlink("onefile")deftest_execve_unicode(self):os=self.posiximportsysifnothasattr(os,"fork"):skip("Need fork() to test execve()")try:output=u"caf\xe9\u1234\n".encode(sys.getfilesystemencoding())exceptUnicodeEncodeError:skip("encoding not good enough")pid=os.fork()ifpid==0:os.execve(u"/bin/sh",["sh","-c",u"echo caf\xe9\u1234 > onefile"],{'ddd':'xxx'})os.waitpid(pid,0)assertopen("onefile").read()==outputos.unlink("onefile")pass# <- please, inspect.getsource(), don't crashifhasattr(__import__(os.name),"spawnv"):deftest_spawnv(self):os=self.posiximportsysprintself.pythonret=os.spawnv(os.P_WAIT,self.python,['python','-c','raise(SystemExit(42))'])assertret==42ifhasattr(__import__(os.name),"spawnve"):deftest_spawnve(self):os=self.posixenv={'PATH':os.environ['PATH'],'FOOBAR':'42'}ret=os.spawnve(os.P_WAIT,self.python,['python','-c',"raise(SystemExit(int(__import__('os').environ['FOOBAR'])))"],env)assertret==42deftest_popen(self):os=self.posixforiinrange(5):stream=os.popen('echo 1')res=stream.read()assertres=='1\n'assertstream.close()isNonedeftest_popen_with(self):os=self.posixstream=os.popen('echo 1')withstreamasfp:res=fp.read()assertres=='1\n'ifhasattr(__import__(os.name),'_getfullpathname'):deftest__getfullpathname(self):# nt specificposix=self.posiximportossysdrv=os.getenv("SystemDrive","C:")# just see if it does anythingpath=sysdrv+'hubber'assertos.sepinposix._getfullpathname(path)deftest_utime(self):os=self.posixfromos.pathimportjoin# XXX utimes & float supportpath=join(self.pdir,"test_utime.txt")fh=open(path,"w")fh.write("x")fh.close()fromtimeimporttime,sleept0=time()sleep(1.1)os.utime(path,None)assertos.stat(path).st_atime>t0os.utime(path,(int(t0),int(t0)))assertint(os.stat(path).st_atime)==int(t0)deftest_utime_raises(self):os=self.posixraises(TypeError,"os.utime('xxx', 3)")raises(OSError,"os.utime('somefilewhichihopewouldneverappearhere', None)")fornameinRegisterOs.w_star:ifhasattr(os,name):values=[0,1,127,128,255]code=py.code.Source(""" def test_wstar(self): os = self.posix%s """%"\n ".join(["assert os.%s(%d) == %d"%(name,value,getattr(os,name)(value))forvalueinvalues]))d={}execcode.compile()indlocals()['test_'+name]=d['test_wstar']ifhasattr(os,'WIFSIGNALED'):deftest_wifsignaled(self):os=self.posixassertos.WIFSIGNALED(0)==Falseassertos.WIFSIGNALED(1)==Trueifhasattr(os,'uname'):deftest_os_uname(self):os=self.posixres=os.uname()assertlen(res)==5foriinres:assertisinstance(i,str)assertisinstance(res,tuple)ifhasattr(os,'getuid'):deftest_os_getuid(self):os=self.posixassertos.getuid()==self.getuidassertos.geteuid()==self.geteuidifhasattr(os,'setuid'):deftest_os_setuid_error(self):os=self.posixraises(OverflowError,os.setuid,-2**31-1)raises(OverflowError,os.setuid,2**32)ifhasattr(os,'getgid'):deftest_os_getgid(self):os=self.posixassertos.getgid()==self.getgidifhasattr(os,'getgroups'):deftest_os_getgroups(self):os=self.posixassertos.getgroups()==self.getgroupsifhasattr(os,'getpgid'):deftest_os_getpgid(self):os=self.posixassertos.getpgid(os.getpid())==self.getpgidraises(OSError,os.getpgid,1234567)ifhasattr(os,'setgid'):deftest_os_setgid_error(self):os=self.posixraises(OverflowError,os.setgid,-2**31-1)raises(OverflowError,os.setgid,2**32)ifhasattr(os,'getsid'):deftest_os_getsid(self):os=self.posixassertos.getsid(0)==self.getsid0raises(OSError,os.getsid,-100000)ifhasattr(os,'sysconf'):deftest_os_sysconf(self):os=self.posixassertos.sysconf(self.sysconf_value)==self.sysconf_resultassertos.sysconf(self.sysconf_name)==self.sysconf_resultassertos.sysconf_names[self.sysconf_name]==self.sysconf_valuedeftest_os_sysconf_error(self):os=self.posixraises(ValueError,os.sysconf,"!@#$%!#$!@#")ifhasattr(os,'fpathconf'):deftest_os_fpathconf(self):os=self.posixassertos.fpathconf(1,"PC_PIPE_BUF")>=128raises(OSError,os.fpathconf,-1,"PC_PIPE_BUF")raises(ValueError,os.fpathconf,1,"##")ifhasattr(os,'wait'):deftest_os_wait(self):os=self.posixexit_status=0x33ifnothasattr(os,"fork"):skip("Need fork() to test wait()")ifhasattr(os,"waitpid")andhasattr(os,"WNOHANG"):try:whileos.waitpid(-1,os.WNOHANG)[0]:passexceptOSError:# until we get "No child processes", hopefullypasschild=os.fork()ifchild==0:# in childos._exit(exit_status)else:pid,status=os.wait()assertchild==pidassertos.WIFEXITED(status)assertos.WEXITSTATUS(status)==exit_statusifhasattr(os,'getloadavg'):deftest_os_getloadavg(self):os=self.posixl0,l1,l2=os.getloadavg()asserttype(l0)isfloatandl0>=0.0asserttype(l1)isfloatandl0>=0.0asserttype(l2)isfloatandl0>=0.0ifhasattr(os,'major'):deftest_major_minor(self):os=self.posixassertos.major(12345)==self.expected_major_12345assertos.minor(12345)==self.expected_minor_12345assertos.makedev(self.expected_major_12345,self.expected_minor_12345)==12345ifhasattr(os,'fsync'):deftest_fsync(self):os=self.posixf=open(self.path2,"w")try:fd=f.fileno()os.fsync(fd)os.fsync(long(fd))os.fsync(f)# <- should also work with a file, or anythingfinally:# with a fileno() methodf.close()try:# May not raise anything with a buggy libc (or eatmydata)os.fsync(fd)exceptOSError:passraises(ValueError,os.fsync,-1)ifhasattr(os,'fdatasync'):deftest_fdatasync(self):os=self.posixf=open(self.path2,"w")try:fd=f.fileno()os.fdatasync(fd)finally:f.close()try:# May not raise anything with a buggy libc (or eatmydata)os.fdatasync(fd)exceptOSError:passraises(ValueError,os.fdatasync,-1)ifhasattr(os,'fchdir'):deftest_fchdir(self):os=self.posixlocaldir=os.getcwd()try:os.mkdir(self.path2+'dir')fd=os.open(self.path2+'dir',os.O_RDONLY)try:os.fchdir(fd)mypath=os.getcwd()finally:os.close(fd)assertmypath.endswith('test_posix2-dir')raises(OSError,os.fchdir,fd)raises(ValueError,os.fchdir,-1)finally:os.chdir(localdir)deftest_largefile(self):os=self.posixfd=os.open(self.path2+'test_largefile',os.O_RDWR|os.O_CREAT,0666)os.ftruncate(fd,10000000000L)res=os.lseek(fd,9900000000L,0)assertres==9900000000Lres=os.lseek(fd,-5000000000L,1)assertres==4900000000Lres=os.lseek(fd,-5200000000L,2)assertres==4800000000Los.close(fd)st=os.stat(self.path2+'test_largefile')assertst.st_size==10000000000Ltest_largefile.need_sparse_files=Truedeftest_write_buffer(self):os=self.posixfd=os.open(self.path2+'test_write_buffer',os.O_RDWR|os.O_CREAT,0666)defwriteall(s):whiles:count=os.write(fd,s)assertcount>0s=s[count:]writeall('hello, ')writeall(buffer('world!\n'))res=os.lseek(fd,0,0)assertres==0data=''whileTrue:s=os.read(fd,100)ifnots:breakdata+=sassertdata=='hello, world!\n'os.close(fd)deftest_write_unicode(self):os=self.posixfd=os.open(self.path2+'test_write_unicode',os.O_RDWR|os.O_CREAT,0666)os.write(fd,u'X')raises(UnicodeEncodeError,os.write,fd,u'\xe9')os.lseek(fd,0,0)data=os.read(fd,2)assertdata=='X'os.close(fd)ifhasattr(__import__(os.name),"fork"):deftest_abort(self):os=self.posixpid=os.fork()ifpid==0:os.abort()pid1,status1=os.waitpid(pid,0)assertpid1==pidassertos.WIFSIGNALED(status1)assertos.WTERMSIG(status1)==self.SIGABRTpass# <- please, inspect.getsource(), don't crashdeftest_closerange(self):os=self.posixifnothasattr(os,'closerange'):skip("missing os.closerange()")fds=[os.open(self.path+str(i),os.O_CREAT|os.O_WRONLY,0777)foriinrange(15)]fds.sort()start=fds.pop()stop=start+1whilelen(fds)>3andfds[-1]==start-1:start=fds.pop()os.closerange(start,stop)forfdinfds:os.close(fd)# should not have been closedforfdinrange(start,stop):raises(OSError,os.fstat,fd)# should have been closedifhasattr(os,'chown'):deftest_chown(self):os=self.posixos.unlink(self.path)raises(OSError,os.chown,self.path,os.getuid(),os.getgid())f=open(self.path,"w")f.write("this is a test")f.close()os.chown(self.path,os.getuid(),os.getgid())ifhasattr(os,'lchown'):deftest_lchown(self):os=self.posixos.unlink(self.path)raises(OSError,os.lchown,self.path,os.getuid(),os.getgid())os.symlink('foobar',self.path)os.lchown(self.path,os.getuid(),os.getgid())ifhasattr(os,'fchown'):deftest_fchown(self):os=self.posixf=open(self.path,"w")os.fchown(f.fileno(),os.getuid(),os.getgid())f.close()ifhasattr(os,'chmod'):deftest_chmod(self):os=self.posixos.unlink(self.path)raises(OSError,os.chmod,self.path,0600)f=open(self.path,"w")f.write("this is a test")f.close()os.chmod(self.path,0200)assert(os.stat(self.path).st_mode&0777)==0200ifhasattr(os,'fchmod'):deftest_fchmod(self):os=self.posixf=open(self.path,"w")os.fchmod(f.fileno(),0200)assert(os.fstat(f.fileno()).st_mode&0777)==0200f.close()assert(os.stat(self.path).st_mode&0777)==0200ifhasattr(os,'mkfifo'):deftest_mkfifo(self):os=self.posixos.mkfifo(self.path2+'test_mkfifo',0666)st=os.lstat(self.path2+'test_mkfifo')importstatassertstat.S_ISFIFO(st.st_mode)ifhasattr(os,'mknod'):deftest_mknod(self):importstatos=self.posix# os.mknod() may require root priviledges to work at alltry:# not very useful: os.mknod() without specifying 'mode'os.mknod(self.path2+'test_mknod-1')exceptOSError,e:skip("os.mknod(): got %r"%(e,))st=os.lstat(self.path2+'test_mknod-1')assertstat.S_ISREG(st.st_mode)# os.mknod() with S_IFIFOos.mknod(self.path2+'test_mknod-2',0600|stat.S_IFIFO)st=os.lstat(self.path2+'test_mknod-2')assertstat.S_ISFIFO(st.st_mode)deftest_mknod_with_ifchr(self):# os.mknod() with S_IFCHR# -- usually requires root priviledges --os=self.posixifhasattr(os.lstat('.'),'st_rdev'):importstattry:os.mknod(self.path2+'test_mknod-3',0600|stat.S_IFCHR,0x105)exceptOSError,e:skip("os.mknod() with S_IFCHR: got %r"%(e,))else:st=os.lstat(self.path2+'test_mknod-3')assertstat.S_ISCHR(st.st_mode)assertst.st_rdev==0x105ifhasattr(os,'nice')andhasattr(os,'fork')andhasattr(os,'waitpid'):deftest_nice(self):os=self.posixmyprio=os.nice(0)#pid=os.fork()ifpid==0:# in the childres=os.nice(3)os._exit(res)#pid1,status1=os.waitpid(pid,0)assertpid1==pidassertos.WIFEXITED(status1)assertos.WEXITSTATUS(status1)==myprio+3ifhasattr(os,'symlink'):deftest_symlink(self):posix=self.posixunicode_dir=self.unicode_dirifunicode_dirisNone:skip("encoding not good enough")dest=u"%s/file.txt"%unicode_dirposix.symlink(u"%s/somefile"%unicode_dir,dest)withopen(dest)asf:data=f.read()assertdata=="who cares?"try:os.getlogin()except(AttributeError,OSError):passelse:deftest_getlogin(self):assertisinstance(self.posix.getlogin(),str)# How else could we test that getlogin is properly# working?deftest_tmpfile(self):os=self.posixf=os.tmpfile()f.write("xxx")f.flush()f.seek(0,0)assertisinstance(f,file)assertf.read()=='xxx'deftest_tmpnam(self):importstat,oss1=os.tmpnam()s2=os.tmpnam()asserts1!=s2defisdir(s):try:returnstat.S_ISDIR(os.stat(s).st_mode)exceptOSError:return-1assertisdir(s1)==-1assertisdir(s2)==-1assertisdir(os.path.dirname(s1))==1assertisdir(os.path.dirname(s2))==1deftest_tempnam(self):importstat,osfordirin[None,self.udir]:forprefixin[None,'foobar']:s1=os.tempnam(dir,prefix)s2=os.tempnam(dir,prefix)asserts1!=s2defisdir(s):try:returnstat.S_ISDIR(os.stat(s).st_mode)exceptOSError:return-1assertisdir(s1)==-1assertisdir(s2)==-1assertisdir(os.path.dirname(s1))==1assertisdir(os.path.dirname(s2))==1ifdir:assertos.path.dirname(s1)==dirassertos.path.dirname(s2)==dirassertos.path.basename(s1).startswith(prefixor'tmp')assertos.path.basename(s2).startswith(prefixor'tmp')deftest_tmpnam_warning(self):importwarnings,os#deff_tmpnam_warning():os.tmpnam()# a single line#withwarnings.catch_warnings(record=True)asw:warnings.simplefilter("always")f_tmpnam_warning()assertlen(w)==1assertissubclass(w[-1].category,RuntimeWarning)assert"potential security risk"instr(w[-1].message)# check that the warning points to the call to os.tmpnam(),# not to some code inside app_posix.pyassertw[-1].lineno==f_tmpnam_warning.func_code.co_firstlinenodeftest_has_kill(self):importosasserthasattr(os,'kill')deftest_pipe_flush(self):os=self.posixffd,gfd=os.pipe()f=os.fdopen(ffd,'r')g=os.fdopen(gfd,'w')g.write('he')g.flush()x=f.read(1)assertx=='h'f.flush()x=f.read(1)assertx=='e'deftest_urandom(self):os=self.posixs=os.urandom(5)assertisinstance(s,bytes)assertlen(s)==5forxinrange(50):ifs!=os.urandom(5):breakelse:assertFalse,"urandom() always returns the same string"# Or very unluckyclassAppTestEnvironment(object):defsetup_class(cls):cls.space=spacecls.w_posix=space.appexec([],"(): import %s as m ; return m"%os.name)cls.w_os=space.appexec([],"(): import os; return os")cls.w_path=space.wrap(str(path))deftest_environ(self):posix=self.posixos=self.osassertposix.environ['PATH']delposix.environ['PATH']deffn():posix.environ['PATH']raises(KeyError,fn)ifhasattr(__import__(os.name),"unsetenv"):deftest_unsetenv_nonexisting(self):os=self.osos.unsetenv("XYZABC")#does not raisetry:os.environ["ABCABC"]exceptKeyError:passelse:raiseAssertionError("did not raise KeyError")os.environ["ABCABC"]="1"assertos.environ["ABCABC"]=="1"os.unsetenv("ABCABC")cmd='''python -c "import os, sys; sys.exit(int('ABCABC' in os.environ))" '''res=os.system(cmd)assertres==0classAppTestPosixUnicode:defsetup_class(cls):cls.space=spacecls.w_posix=space.appexec([],GET_POSIX)ifcls.runappdirect:# Can't change encodingtry:u"ą".encode(sys.getfilesystemencoding())exceptUnicodeEncodeError:py.test.skip("encoding not good enough")else:cls.save_fs_encoding=space.sys.filesystemencodingspace.sys.filesystemencoding="utf-8"defteardown_class(cls):try:cls.space.sys.filesystemencoding=cls.save_fs_encodingexceptAttributeError:passdeftest_stat_unicode(self):# test that passing unicode would not raise UnicodeDecodeErrortry:self.posix.stat(u"ą")exceptOSError:passdeftest_open_unicode(self):# Ensure passing unicode doesn't raise UnicodeEncodeErrortry:self.posix.open(u"ą",self.posix.O_WRONLY)exceptOSError:passdeftest_remove_unicode(self):# See 2 above ;)try:self.posix.remove(u"ą")exceptOSError:passclassAppTestUnicodeFilename:defsetup_class(cls):ufilename=(unicode(udir.join('test_unicode_filename_'))+u'\u65e5\u672c.txt')# "Japan"try:f=file(ufilename,'w')exceptUnicodeEncodeError:py.test.skip("encoding not good enough")f.write("test")f.close()cls.space=spacecls.w_filename=space.wrap(ufilename)cls.w_posix=space.appexec([],GET_POSIX)deftest_open(self):fd=self.posix.open(self.filename,self.posix.O_RDONLY)try:content=self.posix.read(fd,50)finally:self.posix.close(fd)assertcontent=="test"classTestPexpect(object):# XXX replace with AppExpectTest class as soon as possibledefsetup_class(cls):try:importpexpectexceptImportError:py.test.skip("pexpect not found")def_spawn(self,*args,**kwds):importpexpectkwds.setdefault('timeout',600)print'SPAWN:',args,kwdschild=pexpect.spawn(*args,**kwds)child.logfile=sys.stdoutreturnchilddefspawn(self,argv):py_py=py.path.local(pypydir).join('bin','py.py')returnself._spawn(sys.executable,[str(py_py)]+argv)deftest_ttyname(self):source=py.code.Source(""" import os, sys assert os.ttyname(sys.stdin.fileno()) print 'ok!' """)f=udir.join("test_ttyname.py")f.write(source)child=self.spawn([str(f)])child.expect('ok!')