PageRenderTime 55ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/Languages/IronPython/Tests/modules/system_related/nt_test.py

http://github.com/IronLanguages/main
Python | 1185 lines | 1018 code | 77 blank | 90 comment | 16 complexity | 98c0f369084c94fed71e4e461c61fe35 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. #####################################################################################
  2. #
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. #
  5. # This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6. # copy of the license can be found in the License.html file at the root of this distribution. If
  7. # you cannot locate the Apache License, Version 2.0, please send an email to
  8. # ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9. # by the terms of the Apache License, Version 2.0.
  10. #
  11. # You must not remove this notice, or any other, from this software.
  12. #
  13. #
  14. #####################################################################################
  15. from iptest.assert_util import *
  16. skiptest("silverlight", "posix")
  17. from iptest.file_util import *
  18. import _random
  19. from exceptions import IOError
  20. import nt
  21. import errno
  22. AreEqual(nt.environ.has_key('COMPUTERNAME') or nt.environ.has_key('computername'), True)
  23. # mkdir,listdir,rmdir,getcwd
  24. def test_mkdir():
  25. nt.mkdir('dir_create_test')
  26. AreEqual(nt.listdir(nt.getcwd()).count('dir_create_test'), 1)
  27. nt.rmdir('dir_create_test')
  28. AreEqual(nt.listdir(nt.getcwd()).count('dir_create_test'), 0)
  29. def test_mkdir_negative():
  30. nt.mkdir("dir_create_test")
  31. try:
  32. nt.mkdir("dir_create_test")
  33. AssertUnreachable("Cannot create the same directory twice")
  34. except WindowsError, e:
  35. AreEqual(e.errno, 17)
  36. #if it fails once...it should fail again
  37. AssertError(WindowsError, nt.mkdir, "dir_create_test")
  38. nt.rmdir('dir_create_test')
  39. nt.mkdir("dir_create_test")
  40. AssertError(WindowsError, nt.mkdir, "dir_create_test")
  41. nt.rmdir('dir_create_test')
  42. def test_listdir():
  43. AssertError(TypeError, nt.listdir, None)
  44. AreEqual(nt.listdir(nt.getcwd()), nt.listdir('.'))
  45. # stat,lstat
  46. def test_stat():
  47. # stat
  48. AssertError(nt.error, nt.stat, 'doesnotexist.txt')
  49. #lstat
  50. AssertError(nt.error, nt.lstat, 'doesnotexist.txt')
  51. AssertErrorWithNumber(WindowsError, 2, nt.stat, 'doesnotexist.txt')
  52. AssertErrorWithNumber(WindowsError, 22, nt.stat, 'bad?path.txt')
  53. # stat should accept bytes as argument
  54. def test_stat_cp34910():
  55. AreEqual(nt.stat('/'), nt.stat(b'/'))
  56. AreEqual(nt.lstat('/'), nt.lstat(b'/'))
  57. # getcwdu test
  58. def test_getcwdu():
  59. AreEqual(nt.getcwd(),nt.getcwdu())
  60. nt.mkdir('dir_create_test')
  61. AreEqual(nt.listdir(nt.getcwdu()).count('dir_create_test'), 1)
  62. nt.rmdir('dir_create_test')
  63. # getpid test
  64. def test_getpid():
  65. result = None
  66. result = nt.getpid()
  67. Assert(result>=0,
  68. "processPID should not be less than zero")
  69. result2 = nt.getpid()
  70. Assert(result2 == result,
  71. "The processPID in one process should be same")
  72. # environ test
  73. def test_environ():
  74. non_exist_key = "_NOT_EXIST_"
  75. iron_python_string = "Iron_pythoN"
  76. try:
  77. nt.environ[non_exist_key]
  78. raise AssertionError
  79. except KeyError:
  80. pass
  81. # set
  82. nt.environ[non_exist_key] = iron_python_string
  83. AreEqual(nt.environ[non_exist_key], iron_python_string)
  84. import sys
  85. if is_cli:
  86. import System
  87. AreEqual(System.Environment.GetEnvironmentVariable(non_exist_key), iron_python_string)
  88. # update again
  89. swapped = iron_python_string.swapcase()
  90. nt.environ[non_exist_key] = swapped
  91. AreEqual(nt.environ[non_exist_key], swapped)
  92. if is_cli:
  93. AreEqual(System.Environment.GetEnvironmentVariable(non_exist_key), swapped)
  94. # remove
  95. del nt.environ[non_exist_key]
  96. if is_cli :
  97. AreEqual(System.Environment.GetEnvironmentVariable(non_exist_key), None)
  98. AreEqual(type(nt.environ), type({}))
  99. # startfile
  100. def test_startfile():
  101. AssertError(OSError, nt.startfile, "not_exist_file.txt")
  102. AssertError(WindowsError, nt.startfile, 'test_nt.py', 'bad')
  103. # chdir tests
  104. def test_chdir():
  105. currdir = nt.getcwd()
  106. nt.mkdir('tsd')
  107. nt.chdir('tsd')
  108. AreEqual(currdir+'\\tsd', nt.getcwd())
  109. nt.chdir(currdir)
  110. AreEqual(currdir, nt.getcwd())
  111. nt.rmdir('tsd')
  112. # the directory is empty or does not exist
  113. AssertErrorWithNumber(WindowsError, 22, lambda:nt.chdir(''))
  114. AssertErrorWithNumber(WindowsError, 2, lambda:nt.chdir('tsd'))
  115. # fdopen tests
  116. def test_fdopen():
  117. fd_lambda = lambda x: nt.dup(x)
  118. # fd = 0
  119. result = None
  120. result = nt.fdopen(fd_lambda(0),"r",1024)
  121. Assert(result!=None,"1,The file object was not returned correctly")
  122. result = None
  123. result = nt.fdopen(fd_lambda(0),"w",2048)
  124. Assert(result!=None,"2,The file object was not returned correctly")
  125. result = None
  126. result = nt.fdopen(fd_lambda(0),"a",512)
  127. Assert(result!=None,"3,The file object was not returned correctly")
  128. # fd = 1
  129. result = None
  130. result = nt.fdopen(fd_lambda(1),"a",1024)
  131. Assert(result!=None,"4,The file object was not returned correctly")
  132. result = None
  133. result = nt.fdopen(fd_lambda(1),"r",2048)
  134. Assert(result!=None,"5,The file object was not returned correctly")
  135. result = None
  136. result = nt.fdopen(fd_lambda(1),"w",512)
  137. Assert(result!=None,"6,The file object was not returned correctly")
  138. # fd = 2
  139. result = None
  140. result = nt.fdopen(fd_lambda(2),"r",1024)
  141. Assert(result!=None,"7,The file object was not returned correctly")
  142. result = None
  143. result = nt.fdopen(fd_lambda(2),"a",2048)
  144. Assert(result!=None,"8,The file object was not returned correctly")
  145. result = None
  146. result = nt.fdopen(fd_lambda(2),"w",512)
  147. Assert(result!=None,"9,The file object was not returned correctly")
  148. if not is_cli:
  149. result.close()
  150. # The file descriptor is not valid
  151. AssertError(OSError,nt.fdopen,3000)
  152. AssertError(OSError,nt.fdopen,-1)
  153. AssertError(OSError,nt.fdopen,3000, "w")
  154. AssertError(OSError,nt.fdopen,3000, "w", 1024)
  155. # The file mode does not exist
  156. AssertError(ValueError,nt.fdopen,0,"p")
  157. stuff = "\x00a\x01\x02b\x03 \x04 \x05\n\x06_\0xFE\0xFFxyz"
  158. name = "cp5633.txt"
  159. fd = nt.open(name, nt.O_CREAT | nt.O_BINARY | nt.O_TRUNC | nt.O_WRONLY)
  160. f = nt.fdopen(fd, 'wb')
  161. f.write(stuff)
  162. f.close()
  163. f = file(name, 'rb')
  164. try:
  165. AreEqual(stuff, f.read())
  166. finally:
  167. f.close()
  168. nt.remove(name)
  169. # fstat,unlink tests
  170. def test_fstat():
  171. result = nt.fstat(1)
  172. Assert(result!=0,"0,The file stat object was not returned correctly")
  173. result = None
  174. tmpfile = "tmpfile1.tmp"
  175. f = open(tmpfile, "w")
  176. result = nt.fstat(f.fileno())
  177. Assert(result!=None,"0,The file stat object was not returned correctly")
  178. f.close()
  179. nt.unlink(tmpfile)
  180. # stdxx file descriptor
  181. AreEqual(10, len(nt.fstat(0)))
  182. AreEqual(10, len(nt.fstat(1)))
  183. AreEqual(10, len(nt.fstat(2)))
  184. # invalid file descriptor
  185. AssertError(OSError,nt.fstat,3000)
  186. AssertError(OSError,nt.fstat,-1)
  187. def test_chmod():
  188. # chmod tests:
  189. # BUG 828,830
  190. nt.mkdir('tmp2')
  191. nt.chmod('tmp2', 256) # NOTE: change to flag when stat is implemented
  192. AssertError(OSError, lambda:nt.rmdir('tmp2'))
  193. nt.chmod('tmp2', 128)
  194. nt.rmdir('tmp2')
  195. # /BUG
  196. ################################################################################################
  197. # popen/popen2/popen3/unlink tests
  198. def test_popen():
  199. # open a pipe just for reading...
  200. pipe_modes = [["ping 127.0.0.1 -n 1", "r"],
  201. ["ping 127.0.0.1 -n 1"]]
  202. if is_cli:
  203. pipe_modes.append(["ping 127.0.0.1 -n 1", ""])
  204. for args in pipe_modes:
  205. x = nt.popen(*args)
  206. text = x.read()
  207. Assert(text.lower().index('pinging') != -1)
  208. AreEqual(x.close(), None)
  209. # write to a pipe
  210. x = nt.popen('sort', 'w')
  211. x.write('hello\nabc\n')
  212. x.close()
  213. # bug 1146
  214. #x = nt.popen('sort', 'w')
  215. #x.write('hello\nabc\n')
  216. #AreEqual(x.close(), None)
  217. # once w/ default mode
  218. AssertError(ValueError, nt.popen, "ping 127.0.0.1 -n 1", "a")
  219. # popen uses cmd.exe to run stuff -- at least sometimes
  220. dir_pipe = nt.popen('dir')
  221. dir_pipe.read()
  222. dir_pipe.close()
  223. # once w/ no mode
  224. stdin, stdout = nt.popen2('sort')
  225. stdin.write('hello\nabc\n')
  226. AreEqual(stdin.close(), None)
  227. AreEqual(stdout.read(), 'abc\nhello\n')
  228. AreEqual(stdout.close(), None)
  229. # bug 1146
  230. # and once w/ each mode
  231. #for mode in ['b', 't']:
  232. # stdin, stdout = nt.popen2('sort', mode)
  233. # stdin.write('hello\nabc\n')
  234. # AreEqual(stdin.close(), None)
  235. # AreEqual(stdout.read(), 'abc\nhello\n')
  236. # AreEqual(stdout.close(), None)
  237. # popen3: once w/ no mode
  238. stdin, stdout, stderr = nt.popen3('sort')
  239. stdin.write('hello\nabc\n')
  240. AreEqual(stdin.close(), None)
  241. AreEqual(stdout.read(), 'abc\nhello\n')
  242. AreEqual(stdout.close(), None)
  243. AreEqual(stderr.read(), '')
  244. AreEqual(stderr.close(), None)
  245. # bug 1146
  246. # popen3: and once w/ each mode
  247. #for mode in ['b', 't']:
  248. # stdin, stdout, stderr = nt.popen3('sort', mode)
  249. # stdin.write('hello\nabc\n')
  250. # AreEqual(stdin.close(), None)
  251. # AreEqual(stdout.read(), 'abc\nhello\n')
  252. # AreEqual(stdout.close(), None)
  253. # AreEqual(stderr.read(), '')
  254. # AreEqual(stderr.close(), None)
  255. tmpfile = 'tmpfile.tmp'
  256. f = open(tmpfile, 'w')
  257. f.close()
  258. nt.unlink(tmpfile)
  259. try:
  260. nt.chmod('tmpfile.tmp', 256)
  261. except Exception:
  262. pass #should throw when trying to access file deleted by unlink
  263. else:
  264. Assert(False,"Error! Trying to access file deleted by unlink should have thrown.")
  265. try:
  266. tmpfile = "tmpfile2.tmp"
  267. f = open(tmpfile, "w")
  268. f.write("testing chmod")
  269. f.close()
  270. nt.chmod(tmpfile, 256)
  271. AssertError(OSError, nt.unlink, tmpfile)
  272. nt.chmod(tmpfile, 128)
  273. nt.unlink(tmpfile)
  274. AssertError(IOError, file, tmpfile)
  275. finally:
  276. try:
  277. nt.chmod(tmpfile, 128)
  278. nt.unlink(tmpfile)
  279. except Exception, e:
  280. print "exc", e
  281. # verify that nt.stat reports times in seconds, not ticks...
  282. import time
  283. tmpfile = 'tmpfile.tmp'
  284. f = open(tmpfile, 'w')
  285. f.close()
  286. t = time.time()
  287. mt = nt.stat(tmpfile).st_mtime
  288. nt.unlink(tmpfile) # this deletes the file
  289. Assert(abs(t-mt) < 60, "time differs by too much " + str(abs(t-mt)))
  290. tmpfile = 'tmpfile.tmp' # need to open it again since we deleted it with 'unlink'
  291. f = open(tmpfile, 'w')
  292. f.close()
  293. nt.chmod('tmpfile.tmp', 256)
  294. nt.chmod('tmpfile.tmp', 128)
  295. nt.unlink('tmpfile.tmp')
  296. # utime tests
  297. def test_utime():
  298. f = file('temp_file_does_not_exist.txt', 'w')
  299. f.close()
  300. import nt
  301. x = nt.stat('.')
  302. nt.utime('temp_file_does_not_exist.txt', (x[7], x[8]))
  303. y = nt.stat('temp_file_does_not_exist.txt')
  304. AreEqual(x[7], y[7])
  305. AreEqual(x[8], y[8])
  306. nt.unlink('temp_file_does_not_exist.txt')
  307. def test_tempnam_broken_prefixes():
  308. for prefix in ["pre", None]:
  309. AreEqual(type(nt.tempnam("", prefix)), str)
  310. def test_tempnam():
  311. '''
  312. '''
  313. #sanity checks
  314. AreEqual(type(nt.tempnam()), str)
  315. AreEqual(type(nt.tempnam("garbage name should still work")), str)
  316. #Very basic case
  317. joe = nt.tempnam()
  318. last_dir = joe.rfind("\\")
  319. temp_dir = joe[:last_dir+1]
  320. Assert(directory_exists(temp_dir))
  321. Assert(not file_exists(joe))
  322. #Basic case where we give it an existing directory and ensure
  323. #it uses that directory
  324. joe = nt.tempnam(get_temp_dir())
  325. last_dir = joe.rfind("\\")
  326. temp_dir = joe[:last_dir+1]
  327. Assert(directory_exists(temp_dir))
  328. Assert(not file_exists(joe))
  329. # The next line is not guaranteed to be true in some scenarios.
  330. #AreEqual(nt.stat(temp_dir.strip("\\")), nt.stat(get_temp_dir()))
  331. #few random prefixes
  332. prefix_names = ["", "a", "1", "_", ".", "sillyprefix",
  333. " ",
  334. "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  335. ]
  336. #test a few directory names that shouldn't really work
  337. dir_names = ["b", "2", "_", ".", "anotherprefix",
  338. "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
  339. None]
  340. for dir_name in dir_names:
  341. #just try the directory name on it's own
  342. joe = nt.tempnam(dir_name)
  343. last_dir = joe.rfind("\\")
  344. temp_dir = joe[:last_dir+1]
  345. Assert(directory_exists(temp_dir))
  346. Assert(not file_exists(joe))
  347. Assert(temp_dir != dir_name)
  348. #now try every prefix
  349. for prefix_name in prefix_names:
  350. joe = nt.tempnam(dir_name, prefix_name)
  351. last_dir = joe.rfind("\\")
  352. temp_dir = joe[:last_dir+1]
  353. file_name = joe[last_dir+1:]
  354. Assert(directory_exists(temp_dir))
  355. Assert(not file_exists(joe))
  356. Assert(temp_dir != dir_name)
  357. Assert(file_name.startswith(prefix_name))
  358. @skip("cli", "silverlight") #CodePlex 24299
  359. def test_tempnam_warning():
  360. with stderr_trapper() as trapper:
  361. temp = nt.tempnam()
  362. Assert(trapper.messages[0].endswith("RuntimeWarning: tempnam is a potential security risk to your program"), trapper.messages)
  363. # BUG 8777,Should IronPython throw a warning when tmpnam is called ?
  364. # tmpnam test
  365. def test_tmpnam():
  366. str = nt.tmpnam()
  367. AreEqual(isinstance(str,type("string")),True)
  368. if is_cli:
  369. Assert(str.find(colon)!=-1,
  370. "1,the returned path is invalid")
  371. Assert(str.find(separator)!=-1,
  372. "2,the returned path is invalid")
  373. # times test
  374. def test_times():
  375. '''
  376. '''
  377. #simple sanity check
  378. utime, stime, zero1, zero2, zero3 = nt.times()
  379. Assert(utime>=0)
  380. Assert(stime>=0)
  381. AreEqual(zero1, 0)
  382. AreEqual(zero2, 0)
  383. #BUG - according to the specs this should be 0 for Windows
  384. #AreEqual(zero3, 0)
  385. # putenv tests
  386. def test_putenv():
  387. '''
  388. '''
  389. #simple sanity check
  390. nt.putenv("IPY_TEST_ENV_VAR", "xyz")
  391. #ensure it really does what it claims to do
  392. Assert(not nt.environ.has_key("IPY_TEST_ENV_VAR"))
  393. #negative cases
  394. AssertError(TypeError, nt.putenv, None, "xyz")
  395. #BUG
  396. #AssertError(TypeError, nt.putenv, "ABC", None)
  397. AssertError(TypeError, nt.putenv, 1, "xyz")
  398. AssertError(TypeError, nt.putenv, "ABC", 1)
  399. # unsetenv tests
  400. def test_unsetenv():
  401. #CPython nt has no unsetenv function
  402. #simple sanity check
  403. if is_cli:
  404. nt.putenv("ipy_test_env_var", "xyz")
  405. nt.unsetenv("ipy_test_env_var_unset")
  406. Assert(not nt.environ.has_key("ipy_test_env_var_unset"))
  407. # remove tests
  408. def test_remove():
  409. # remove an existing file
  410. handler = open("create_test_file.txt","w")
  411. handler.close()
  412. path1 = nt.getcwd()
  413. nt.remove(path1+'\\create_test_file.txt')
  414. AreEqual(nt.listdir(nt.getcwd()).count('create_test_file.txt'), 0)
  415. AssertErrorWithNumber(OSError, 2, nt.remove, path1+'\\create_test_file2.txt')
  416. AssertErrorWithNumber(OSError, 2, nt.unlink, path1+'\\create_test_file2.txt')
  417. AssertErrorWithNumber(OSError, 22, nt.remove, path1+'\\create_test_file?.txt')
  418. AssertErrorWithNumber(OSError, 22, nt.unlink, path1+'\\create_test_file?.txt')
  419. # the path is a type other than string
  420. AssertError(TypeError, nt.remove, 1)
  421. AssertError(TypeError, nt.remove, True)
  422. AssertError(TypeError, nt.remove, None)
  423. def test_remove_negative():
  424. import stat
  425. AssertErrorWithNumber(WindowsError, errno.ENOENT, lambda : nt.remove('some_file_that_does_not_exist'))
  426. try:
  427. file('some_test_file.txt', 'w').close()
  428. nt.chmod('some_test_file.txt', stat.S_IREAD)
  429. AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
  430. nt.chmod('some_test_file.txt', stat.S_IWRITE)
  431. f = file('some_test_file.txt', 'w+')
  432. AssertErrorWithNumber(WindowsError, errno.EACCES, lambda : nt.remove('some_test_file.txt'))
  433. f.close()
  434. finally:
  435. nt.chmod('some_test_file.txt', stat.S_IWRITE)
  436. nt.unlink('some_test_file.txt')
  437. # rename tests
  438. def test_rename():
  439. # normal test
  440. handler = open("oldnamefile.txt","w")
  441. handler.close()
  442. str_old = "oldnamefile.txt"
  443. dst = "newnamefile.txt"
  444. nt.rename(str_old,dst)
  445. AreEqual(nt.listdir(nt.getcwd()).count(dst), 1)
  446. AreEqual(nt.listdir(nt.getcwd()).count(str_old), 0)
  447. nt.remove(dst)
  448. # the destination name is a directory
  449. handler = open("oldnamefile.txt","w")
  450. handler.close()
  451. str_old = "oldnamefile.txt"
  452. dst = "newnamefile.txt"
  453. nt.mkdir(dst)
  454. AssertError(OSError, nt.rename,str_old,dst)
  455. nt.rmdir(dst)
  456. nt.remove(str_old)
  457. # the dst already exists
  458. handler1 = open("oldnamefile.txt","w")
  459. handler1.close()
  460. handler2 = open("newnamefile.txt","w")
  461. handler2.close()
  462. str_old = "oldnamefile.txt"
  463. dst = "newnamefile.txt"
  464. AssertError(OSError, nt.rename,str_old,dst)
  465. nt.remove(str_old)
  466. nt.remove(dst)
  467. # the source file specified does not exist
  468. str_old = "oldnamefile.txt"
  469. dst = "newnamefile.txt"
  470. AssertError(OSError, nt.rename,str_old,dst)
  471. # spawnle tests
  472. def test_spawnle():
  473. '''
  474. '''
  475. #BUG?
  476. #CPython nt has no spawnle function
  477. if is_cli == False:
  478. return
  479. ping_cmd = get_environ_variable("windir") + "\system32\ping"
  480. #simple sanity check
  481. nt.spawnle(nt.P_WAIT, ping_cmd , "ping", "/?", {})
  482. #BUG - the first parameter of spawnle should be "ping"
  483. #nt.spawnle(nt.P_WAIT, ping_cmd , "ping", "127.0.0.1", {})
  484. #BUG - even taking "ping" out, multiple args do not work
  485. #pid = nt.spawnle(nt.P_NOWAIT, ping_cmd , "-n", "15", "-w", "1000", "127.0.0.1", {})
  486. #negative cases
  487. AssertError(TypeError, nt.spawnle, nt.P_WAIT, ping_cmd , "ping", "/?", None)
  488. AssertError(TypeError, nt.spawnle, nt.P_WAIT, ping_cmd , "ping", "/?", {1: "xyz"})
  489. AssertError(TypeError, nt.spawnle, nt.P_WAIT, ping_cmd , "ping", "/?", {"abc": 1})
  490. # spawnl tests
  491. def test_spawnl():
  492. if is_cli == False:
  493. return
  494. #sanity check
  495. #CPython nt has no spawnl function
  496. pint_cmd = ping_cmd = get_environ_variable("windir") + "\system32\ping.exe"
  497. nt.spawnl(nt.P_WAIT, ping_cmd , "ping","127.0.0.1","-n","1")
  498. nt.spawnl(nt.P_WAIT, ping_cmd , "ping","/?")
  499. nt.spawnl(nt.P_WAIT, ping_cmd , "ping")
  500. # negative case
  501. cmd = pint_cmd+"oo"
  502. AssertError(OSError,nt.spawnl,nt.P_WAIT,cmd,"ping","/?")
  503. # spawnve tests
  504. def test_spawnv():
  505. #sanity check
  506. ping_cmd = get_environ_variable("windir") + "\system32\ping"
  507. nt.spawnv(nt.P_WAIT, ping_cmd , ["ping"])
  508. nt.spawnv(nt.P_WAIT, ping_cmd , ["ping","127.0.0.1","-n","1"])
  509. # spawnve tests
  510. def test_spawnve():
  511. '''
  512. '''
  513. ping_cmd = get_environ_variable("windir") + "\system32\ping"
  514. #simple sanity checks
  515. nt.spawnve(nt.P_WAIT, ping_cmd, ["ping", "/?"], {})
  516. nt.spawnve(nt.P_WAIT, ping_cmd, ["ping", "127.0.0.1"], {})
  517. nt.spawnve(nt.P_WAIT, ping_cmd, ["ping", "-n", "2", "-w", "1000", "127.0.0.1"], {})
  518. #negative cases
  519. AssertError(TypeError, nt.spawnve, nt.P_WAIT, ping_cmd , ["ping", "/?"], None)
  520. AssertError(TypeError, nt.spawnve, nt.P_WAIT, ping_cmd , ["ping", "/?"], {1: "xyz"})
  521. AssertError(TypeError, nt.spawnve, nt.P_WAIT, ping_cmd , ["ping", "/?"], {"abc": 1})
  522. # tmpfile tests
  523. #for some strange reason this fails on some Vista machines with an OSError related
  524. #to permissions problems
  525. @skip("win32")
  526. def test_tmpfile():
  527. '''
  528. '''
  529. #sanity check
  530. joe = nt.tmpfile()
  531. AreEqual(type(joe), file)
  532. joe.close()
  533. # waitpid tests
  534. def test_waitpid():
  535. '''
  536. '''
  537. #sanity check
  538. ping_cmd = get_environ_variable("windir") + "\system32\ping"
  539. pid = nt.spawnv(nt.P_NOWAIT, ping_cmd , ["ping", "-n", "1", "127.0.0.1"])
  540. new_pid, exit_stat = nt.waitpid(pid, 0)
  541. #negative cases
  542. AssertErrorWithMessage(OSError, "[Errno 10] No child processes", nt.waitpid, -1234, 0)
  543. AssertError(TypeError, nt.waitpid, "", 0)
  544. # stat_result test
  545. def test_stat_result():
  546. #sanity check
  547. statResult = [0,1,2,3,4,5,6,7,8,9]
  548. object = None
  549. object = nt.stat_result(statResult)
  550. Assert(object != None,
  551. "The class did not return an object instance")
  552. AreEqual(object.st_uid,4)
  553. AreEqual(object.st_gid,5)
  554. AreEqual(object.st_nlink,3)
  555. AreEqual(object.st_dev,2)
  556. AreEqual(object.st_ino,1)
  557. AreEqual(object.st_mode,0)
  558. AreEqual(object.st_atime,7)
  559. AreEqual(object.st_mtime,8)
  560. AreEqual(object.st_ctime,9)
  561. AreEqual(str(nt.stat_result(range(12))),
  562. "nt.stat_result(st_mode=0, st_ino=1, st_dev=2, st_nlink=3, st_uid=4, st_gid=5, st_size=6, st_atime=7, st_mtime=8, st_ctime=9)") #CodePlex 8755
  563. #negative tests
  564. statResult = [0,1,2,3,4,5,6,7,8,]
  565. AssertError(TypeError,nt.stat_result,statResult)
  566. # this should not produce an error
  567. statResult = ["a","b","c","y","r","a","a","b","d","r","f"]
  568. x = nt.stat_result(statResult)
  569. AreEqual(x.st_mode, 'a')
  570. AreEqual(x.st_ino, 'b')
  571. AreEqual(x.st_dev, 'c')
  572. AreEqual(x.st_nlink, 'y')
  573. AreEqual(x.st_uid, 'r')
  574. AreEqual(x.st_gid, 'a')
  575. AreEqual(x.st_size, 'a')
  576. AreEqual(x.st_atime, 'f')
  577. AreEqual(x.st_mtime, 'd')
  578. AreEqual(x.st_ctime, 'r')
  579. # can pass dict to get values...
  580. x = nt.stat_result(xrange(10), {'st_atime': 23, 'st_mtime':42, 'st_ctime':2342})
  581. AreEqual(x.st_atime, 23)
  582. AreEqual(x.st_mtime, 42)
  583. AreEqual(x.st_ctime, 2342)
  584. # positional values take precedence over dict values
  585. x = nt.stat_result(xrange(13), {'st_atime': 23, 'st_mtime':42, 'st_ctime':2342})
  586. AreEqual(x.st_atime, 10)
  587. AreEqual(x.st_mtime, 11)
  588. AreEqual(x.st_ctime, 12)
  589. x = nt.stat_result(xrange(13))
  590. AreEqual(x.st_atime, 10)
  591. AreEqual(x.st_mtime, 11)
  592. AreEqual(x.st_ctime, 12)
  593. # other values are ignored...
  594. x = nt.stat_result(xrange(13), {'st_dev': 42, 'st_gid': 42, 'st_ino': 42, 'st_mode': 42, 'st_nlink': 42, 'st_size':42, 'st_uid':42})
  595. AreEqual(x.st_mode, 0)
  596. AreEqual(x.st_ino, 1)
  597. AreEqual(x.st_dev, 2)
  598. AreEqual(x.st_nlink, 3)
  599. AreEqual(x.st_uid, 4)
  600. AreEqual(x.st_gid, 5)
  601. AreEqual(x.st_size, 6)
  602. AreEqual(x.st_atime, 10)
  603. AreEqual(x.st_mtime, 11)
  604. AreEqual(x.st_ctime, 12)
  605. Assert(not isinstance(x, tuple))
  606. #--Misc
  607. #+
  608. x = nt.stat_result(range(10))
  609. AreEqual(x + (), x)
  610. AreEqual(x + tuple(x), tuple(range(10)*2))
  611. AssertError(TypeError, lambda: x + (1))
  612. AssertError(TypeError, lambda: x + 1)
  613. AssertError(TypeError, lambda: x + x)
  614. #> (list/object)
  615. Assert(nt.stat_result(range(10)) > None)
  616. Assert(nt.stat_result(range(10)) > 1)
  617. Assert(nt.stat_result(range(10)) > range(10))
  618. Assert(nt.stat_result([1 for x in range(10)]) > nt.stat_result(range(10)))
  619. Assert(not nt.stat_result(range(10)) > nt.stat_result(range(10)))
  620. Assert(not nt.stat_result(range(10)) > nt.stat_result(range(11)))
  621. Assert(not nt.stat_result(range(10)) > nt.stat_result([1 for x in range(10)]))
  622. Assert(not nt.stat_result(range(11)) > nt.stat_result(range(10)))
  623. #< (list/object)
  624. Assert(not nt.stat_result(range(10)) < None)
  625. Assert(not nt.stat_result(range(10)) < 1)
  626. Assert(not nt.stat_result(range(10)) < range(10))
  627. Assert(not nt.stat_result([1 for x in range(10)]) < nt.stat_result(range(10)))
  628. Assert(not nt.stat_result(range(10)) < nt.stat_result(range(10)))
  629. Assert(not nt.stat_result(range(10)) < nt.stat_result(range(11)))
  630. Assert(nt.stat_result(range(10)) < nt.stat_result([1 for x in range(10)]))
  631. Assert(not nt.stat_result(range(11)) < nt.stat_result(range(10)))
  632. #>= (list/object)
  633. Assert(nt.stat_result(range(10)) >= None)
  634. Assert(nt.stat_result(range(10)) >= 1)
  635. Assert(nt.stat_result(range(10)) >= range(10))
  636. Assert(nt.stat_result([1 for x in range(10)]) >= nt.stat_result(range(10)))
  637. Assert(nt.stat_result(range(10)) >= nt.stat_result(range(10)))
  638. Assert(nt.stat_result(range(10)) >= nt.stat_result(range(11)))
  639. Assert(not nt.stat_result(range(10)) >= nt.stat_result([1 for x in range(10)]))
  640. Assert(nt.stat_result(range(11)) >= nt.stat_result(range(10)))
  641. #<= (list/object)
  642. Assert(not nt.stat_result(range(10)) <= None)
  643. Assert(not nt.stat_result(range(10)) <= 1)
  644. Assert(not nt.stat_result(range(10)) <= range(10))
  645. Assert(not nt.stat_result([1 for x in range(10)]) <= nt.stat_result(range(10)))
  646. Assert(nt.stat_result(range(10)) <= nt.stat_result(range(10)))
  647. Assert(nt.stat_result(range(10)) <= nt.stat_result(range(11)))
  648. Assert(nt.stat_result(range(10)) <= nt.stat_result([1 for x in range(10)]))
  649. Assert(nt.stat_result(range(11)) <= nt.stat_result(range(10)))
  650. #* (size/stat_result)
  651. x = nt.stat_result(range(10))
  652. AreEqual(x * 1, tuple(x))
  653. AreEqual(x * 2, tuple(range(10)*2))
  654. AreEqual(1 * x, tuple(x))
  655. AreEqual(3 * x, tuple(range(10)*3))
  656. AssertError(TypeError, lambda: x * x)
  657. AssertError(TypeError, lambda: x * 3.14)
  658. AssertError(TypeError, lambda: x * None)
  659. AssertError(TypeError, lambda: x * "abc")
  660. AssertError(TypeError, lambda: "abc" * x)
  661. #__repr__
  662. x = nt.stat_result(range(10))
  663. AreEqual(x.__repr__(),
  664. "nt.stat_result(st_mode=0, st_ino=1, st_dev=2, st_nlink=3, st_uid=4, st_gid=5, st_size=6, st_atime=7, st_mtime=8, st_ctime=9)")
  665. #index get/set
  666. x = nt.stat_result(range(10))
  667. for i in xrange(10):
  668. AreEqual(x[i], i)
  669. def temp_func():
  670. z = nt.stat_result(range(10))
  671. z[3] = 4
  672. AssertError(TypeError, temp_func)
  673. #__getslice__
  674. x = nt.stat_result(range(10))
  675. AreEqual(x[1:3], (1, 2))
  676. AreEqual(x[7:100], (7, 8, 9))
  677. AreEqual(x[7:-100], ())
  678. AreEqual(x[-101:-100], ())
  679. AreEqual(x[-2:8], ())
  680. AreEqual(x[-2:1000], (8,9))
  681. #__contains__
  682. x = nt.stat_result(range(10))
  683. for i in xrange(10):
  684. Assert(i in x)
  685. x.__contains__(i)
  686. Assert(-1 not in x)
  687. Assert(None not in x)
  688. Assert(20 not in x)
  689. #GetHashCode
  690. x = nt.stat_result(range(10))
  691. Assert(type(hash(x))==int)
  692. #IndexOf
  693. x = nt.stat_result(range(10))
  694. AreEqual(x.__getitem__(0), 0)
  695. AreEqual(x.__getitem__(3), 3)
  696. AreEqual(x.__getitem__(9), 9)
  697. AreEqual(x.__getitem__(-1), 9)
  698. AssertError(IndexError, lambda: x.__getitem__(10))
  699. AssertError(IndexError, lambda: x.__getitem__(11))
  700. #Insert
  701. x = nt.stat_result(range(10))
  702. AreEqual(x.__add__(()), tuple(x))
  703. AreEqual(x.__add__((1,2,3)), tuple(x) + (1, 2, 3))
  704. AssertError(TypeError, lambda: x.__add__(3))
  705. AssertError(TypeError, lambda: x.__add__(None))
  706. #Remove
  707. x = nt.stat_result(range(10))
  708. def temp_func():
  709. z = nt.stat_result(range(10))
  710. del z[3]
  711. AssertError(TypeError, temp_func)
  712. #enumerate
  713. x = nt.stat_result(range(10))
  714. temp_list = []
  715. for i in x:
  716. temp_list.append(i)
  717. AreEqual(tuple(x), tuple(temp_list))
  718. statResult = ["a","b","c","y","r","a","a","b","d","r","f"]
  719. x = nt.stat_result(statResult)
  720. temp_list = []
  721. for i in x:
  722. temp_list.append(i)
  723. AreEqual(tuple(x), tuple(temp_list))
  724. temp = Exception()
  725. statResult = [temp for i in xrange(10)]
  726. x = nt.stat_result(statResult)
  727. temp_list = []
  728. for i in x:
  729. temp_list.append(i)
  730. AreEqual(tuple(x), tuple(temp_list))
  731. # urandom tests
  732. def test_urandom():
  733. # argument n is a random int
  734. rand = _random.Random()
  735. n = rand.getrandbits(16)
  736. str = nt.urandom(n)
  737. result = len(str)
  738. AreEqual(isinstance(str,type("string")),True)
  739. AreEqual(n,result)
  740. # write/read tests
  741. def test_write():
  742. # write the file
  743. tempfilename = "temp.txt"
  744. file = open(tempfilename,"w")
  745. nt.write(file.fileno(),"Hello,here is the value of test string")
  746. file.close()
  747. # read from the file
  748. file = open(tempfilename,"r")
  749. str = nt.read(file.fileno(),100)
  750. AreEqual(str,"Hello,here is the value of test string")
  751. file.close()
  752. nt.unlink(tempfilename)
  753. # BUG 8783 the argument buffersize in nt.read(fd, buffersize) is less than zero
  754. # the string written to the file is empty string
  755. tempfilename = "temp.txt"
  756. file = open(tempfilename,"w")
  757. nt.write(file.fileno(),"bug test")
  758. file.close()
  759. file = open(tempfilename,"r")
  760. AssertError(OSError,nt.read,file.fileno(),-10)
  761. file.close()
  762. nt.unlink(tempfilename)
  763. # open test
  764. def test_open():
  765. file('temp.txt', 'w+').close()
  766. try:
  767. fd = nt.open('temp.txt', nt.O_WRONLY | nt.O_CREAT)
  768. nt.close(fd)
  769. AssertErrorWithNumber(OSError, 17, nt.open, 'temp.txt', nt.O_CREAT | nt.O_EXCL)
  770. for flag in [nt.O_EXCL, nt.O_APPEND]:
  771. fd = nt.open('temp.txt', nt.O_RDONLY | flag)
  772. nt.close(fd)
  773. fd = nt.open('temp.txt', nt.O_WRONLY | flag)
  774. nt.close(fd)
  775. fd = nt.open('temp.txt', nt.O_RDWR | flag)
  776. nt.close(fd)
  777. # sanity test
  778. tempfilename = "temp.txt"
  779. fd = nt.open(tempfilename,256,1)
  780. nt.close(fd)
  781. nt.unlink('temp.txt')
  782. f = nt.open('temp.txt', nt.O_TEMPORARY | nt.O_CREAT)
  783. nt.close(f)
  784. AssertError(OSError, nt.stat, 'temp.txt')
  785. # TODO: These tests should probably test more functionality regarding O_SEQUENTIAL/O_RANDOM
  786. f = nt.open('temp.txt', nt.O_TEMPORARY | nt.O_CREAT | nt.O_SEQUENTIAL | nt.O_RDWR)
  787. nt.close(f)
  788. AssertError(OSError, nt.stat, 'temp.txt')
  789. f = nt.open('temp.txt', nt.O_TEMPORARY | nt.O_CREAT | nt.O_RANDOM | nt.O_RDWR)
  790. nt.close(f)
  791. AssertError(OSError, nt.stat, 'temp.txt')
  792. finally:
  793. try:
  794. # should fail if the file doesn't exist
  795. nt.unlink('temp.txt')
  796. except:
  797. pass
  798. def test_system_minimal():
  799. Assert(hasattr(nt, "system"))
  800. AreEqual(nt.system("ping localhost -n 1"), 0)
  801. AreEqual(nt.system('"ping localhost -n 1"'), 0)
  802. AreEqual(nt.system('"ping localhost -n 1'), 0)
  803. AreEqual(nt.system("ping"), 1)
  804. AreEqual(nt.system("some_command_which_is_not_available"), 1)
  805. # flags test
  806. def test_flags():
  807. AreEqual(nt.P_WAIT,0)
  808. AreEqual(nt.P_NOWAIT,1)
  809. AreEqual(nt.P_NOWAITO,3)
  810. AreEqual(nt.O_APPEND,8)
  811. AreEqual(nt.O_CREAT,256)
  812. AreEqual(nt.O_TRUNC,512)
  813. AreEqual(nt.O_EXCL,1024)
  814. AreEqual(nt.O_NOINHERIT,128)
  815. AreEqual(nt.O_RANDOM,16)
  816. AreEqual(nt.O_SEQUENTIAL,32)
  817. AreEqual(nt.O_SHORT_LIVED,4096)
  818. AreEqual(nt.O_TEMPORARY,64)
  819. AreEqual(nt.O_WRONLY,1)
  820. AreEqual(nt.O_RDONLY,0)
  821. AreEqual(nt.O_RDWR,2)
  822. AreEqual(nt.O_BINARY,32768)
  823. AreEqual(nt.O_TEXT,16384)
  824. def test_access():
  825. f = file('new_file_name', 'w')
  826. f.close()
  827. AreEqual(nt.access('new_file_name', nt.F_OK), True)
  828. AreEqual(nt.access('new_file_name', nt.R_OK), True)
  829. AreEqual(nt.access('does_not_exist.py', nt.F_OK), False)
  830. AreEqual(nt.access('does_not_exist.py', nt.R_OK), False)
  831. nt.chmod('new_file_name', 0x100) # S_IREAD
  832. AreEqual(nt.access('new_file_name', nt.W_OK), False)
  833. nt.chmod('new_file_name', 0x80) # S_IWRITE
  834. nt.unlink('new_file_name')
  835. nt.mkdir('new_dir_name')
  836. AreEqual(nt.access('new_dir_name', nt.R_OK), True)
  837. nt.rmdir('new_dir_name')
  838. AssertError(TypeError, nt.access, None, 1)
  839. def test_umask():
  840. orig = nt.umask(0)
  841. try:
  842. AssertError(TypeError, nt.umask, 3.14)
  843. for i in [0, 1, 5, int((2**(31))-1)]:
  844. AreEqual(nt.umask(i), 0)
  845. AssertError(OverflowError, nt.umask, 2**31)
  846. for i in [None, "abc", 3j, int]:
  847. AssertError(TypeError, nt.umask, i)
  848. finally:
  849. nt.umask(orig)
  850. def test_cp16413():
  851. tmpfile = 'tmpfile.tmp'
  852. f = open(tmpfile, 'w')
  853. f.close()
  854. nt.chmod(tmpfile, 0777)
  855. nt.unlink(tmpfile)
  856. def test__getfullpathname():
  857. AreEqual(nt._getfullpathname('.'), nt.getcwd())
  858. AreEqual(nt._getfullpathname('<bad>'), path_combine(nt.getcwd(), '<bad>'))
  859. AreEqual(nt._getfullpathname('bad:'), path_combine(nt.getcwd(), 'bad:'))
  860. AreEqual(nt._getfullpathname(':bad:'), path_combine(nt.getcwd(), ':bad:'))
  861. AreEqual(nt._getfullpathname('::'), '::\\')
  862. AreEqual(nt._getfullpathname('1:'), '1:\\')
  863. AreEqual(nt._getfullpathname('1:a'), '1:\\a')
  864. AreEqual(nt._getfullpathname('1::'), '1:\\:')
  865. AreEqual(nt._getfullpathname('1:\\'), '1:\\')
  866. def test__getfullpathname_neg():
  867. for bad in [None, 0, 34, -12345L, 3.14, object, test__getfullpathname]:
  868. AssertError(TypeError, nt._getfullpathname, bad)
  869. @skip("netstandard") # TODO: figure out
  870. def test_cp15514():
  871. cmd_variation_list = ['%s -c "print __name__"' % sys.executable,
  872. '"%s -c "print __name__""' % sys.executable,
  873. ]
  874. cmd_cmd = get_environ_variable("windir") + "\system32\cmd"
  875. for x in cmd_variation_list:
  876. ec = nt.spawnv(nt.P_WAIT, cmd_cmd , ["cmd", "/C",
  877. x])
  878. AreEqual(ec, 0)
  879. def test_strerror():
  880. test_dict = {
  881. 0: 'No error',
  882. 1: 'Operation not permitted',
  883. 2: 'No such file or directory',
  884. 3: 'No such process',
  885. 4: 'Interrupted function call',
  886. 5: 'Input/output error',
  887. 6: 'No such device or address',
  888. 7: 'Arg list too long',
  889. 8: 'Exec format error',
  890. 9: 'Bad file descriptor',
  891. 10: 'No child processes',
  892. 11: 'Resource temporarily unavailable',
  893. 12: 'Not enough space',
  894. 13: 'Permission denied',
  895. 14: 'Bad address',
  896. 16: 'Resource device',
  897. 17: 'File exists',
  898. 18: 'Improper link',
  899. 19: 'No such device',
  900. 20: 'Not a directory',
  901. 21: 'Is a directory',
  902. 22: 'Invalid argument',
  903. 23: 'Too many open files in system',
  904. 24: 'Too many open files',
  905. 25: 'Inappropriate I/O control operation',
  906. 27: 'File too large',
  907. 28: 'No space left on device',
  908. 29: 'Invalid seek',
  909. 30: 'Read-only file system',
  910. 31: 'Too many links',
  911. 32: 'Broken pipe',
  912. 33: 'Domain error',
  913. 34: 'Result too large',
  914. 36: 'Resource deadlock avoided',
  915. 38: 'Filename too long',
  916. 39: 'No locks available',
  917. 40: 'Function not implemented',
  918. 41: 'Directory not empty', 42: 'Illegal byte sequence'
  919. }
  920. for key, value in test_dict.iteritems():
  921. AreEqual(nt.strerror(key), value)
  922. @skip("netstandard") # TODO: figure out
  923. def test_popen_cp34837():
  924. import subprocess
  925. import os
  926. p = subprocess.Popen("whoami", env=os.environ)
  927. Assert(p!=None)
  928. p.wait()
  929. def test_fsync():
  930. fsync_file_name = 'text_fsync.txt'
  931. fd = nt.open(fsync_file_name, nt.O_WRONLY | nt.O_CREAT)
  932. # negative test, make sure it raises on invalid (closed) fd
  933. try:
  934. nt.close(fd+1)
  935. except:
  936. pass
  937. AssertError(OSError, nt.fsync, fd+1)
  938. # BUG (or implementation detail)
  939. # On a posix system, once written to a file descriptor
  940. # it can be read using another fd without any additional intervention.
  941. # In case of IronPython the data lingers in a stream which
  942. # is used to simulate file descriptor.
  943. fd2 = nt.open(fsync_file_name, nt.O_RDONLY)
  944. AreEqual(nt.read(fd2, 1), '')
  945. nt.write(fd, '1')
  946. AreEqual(nt.read(fd2, 1), '') # this should be visible right away, but is not
  947. nt.fsync(fd)
  948. AreEqual(nt.read(fd2, 1), '1')
  949. nt.close(fd)
  950. nt.close(fd2)
  951. # fsync on read file descriptor
  952. fd = nt.open(fsync_file_name, nt.O_RDONLY)
  953. AssertError(OSError, nt.fsync, fd)
  954. nt.close(fd)
  955. # fsync on rdwr file descriptor
  956. fd = nt.open(fsync_file_name, nt.O_RDWR)
  957. nt.fsync(fd)
  958. nt.close(fd)
  959. # fsync on derived fd
  960. for mode in ('rb', 'r'):
  961. f = open(fsync_file_name, mode)
  962. AssertError(OSError, nt.fsync, f.fileno())
  963. f.close()
  964. for mode in ('wb', 'w'):
  965. f = open(fsync_file_name, mode)
  966. nt.fsync(f.fileno())
  967. f.close()
  968. nt.unlink(fsync_file_name)
  969. # fsync on pipe ends
  970. r,w = nt.pipe()
  971. AssertError(OSError, nt.fsync, r)
  972. nt.write(w, '1')
  973. nt.fsync(w)
  974. nt.close(w)
  975. nt.close(r)
  976. #------------------------------------------------------------------------------
  977. try:
  978. run_test(__name__)
  979. finally:
  980. #test cleanup - the test functions create the following directories and if any of them
  981. #fail, the directories may not necessarily be removed. for this reason we try to remove
  982. #them again
  983. for temp_dir in ['dir_create_test', 'tsd', 'tmp2', 'newnamefile.txt']:
  984. try:
  985. nt.rmdir(temp_dir)
  986. except:
  987. pass