tosproc.nim 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. discard """
  2. joinable: false
  3. """
  4. #[
  5. joinable: false
  6. because it'd need cleanup up stdout
  7. see also: tests/osproc/*.nim; consider merging those into a single test here
  8. (easier to factor and test more things as a single self contained test)
  9. ]#
  10. when defined(case_testfile): # compiled test file for child process
  11. from posix import exitnow
  12. proc c_exit2(code: c_int): void {.importc: "_exit", header: "<unistd.h>".}
  13. import os
  14. var a = 0
  15. proc fun(b = 0) =
  16. a.inc
  17. if a mod 10000000 == 0: # prevents optimizing it away
  18. echo a
  19. fun(b+1)
  20. proc main() =
  21. let args = commandLineParams()
  22. echo (msg: "child binary", pid: getCurrentProcessId())
  23. let arg = args[0]
  24. echo (arg: arg)
  25. case arg
  26. of "exit_0":
  27. if true: quit(0)
  28. of "exitnow_139":
  29. if true: exitnow(139)
  30. of "c_exit2_139":
  31. if true: c_exit2(139)
  32. of "quit_139":
  33. # `exitStatusLikeShell` doesn't distinguish between a process that
  34. # exit(139) and a process that gets killed with `SIGSEGV` because
  35. # 139 = 11 + 128 = SIGSEGV + 128.
  36. # However, as #10249 shows, this leads to bad debugging experience
  37. # when a child process dies with SIGSEGV, leaving no trace of why it
  38. # failed. The shell (and lldb debugger) solves that by inserting a
  39. # helpful msg: `segmentation fault` when it detects a signal killed
  40. # the child.
  41. # todo: expose an API that will show more diagnostic, returning
  42. # (exitCode, signal) instead of just `shellExitCode`.
  43. if true: quit(139)
  44. of "exit_recursion": # stack overflow by infinite recursion
  45. fun()
  46. echo a
  47. of "exit_array": # bad array access
  48. echo args[1]
  49. main()
  50. elif defined(case_testfile2):
  51. import strutils
  52. let x = stdin.readLine()
  53. echo x.parseInt + 5
  54. elif defined(case_testfile3):
  55. echo "start ta_out"
  56. stdout.writeLine("to stdout")
  57. stdout.flushFile()
  58. stdout.writeLine("to stdout")
  59. stdout.flushFile()
  60. stderr.writeLine("to stderr")
  61. stderr.flushFile()
  62. stderr.writeLine("to stderr")
  63. stderr.flushFile()
  64. stdout.writeLine("to stdout")
  65. stdout.flushFile()
  66. stdout.writeLine("to stdout")
  67. stdout.flushFile()
  68. echo "end ta_out"
  69. elif defined(case_testfile4):
  70. import system # we could remove that
  71. quit(QuitFailure)
  72. else: # main driver
  73. import stdtest/[specialpaths, unittest_light]
  74. import os, osproc, strutils
  75. const nim = getCurrentCompilerExe()
  76. const sourcePath = currentSourcePath()
  77. let dir = getCurrentDir() / "tests" / "osproc"
  78. template deferScoped(cleanup, body) =
  79. # pending https://github.com/nim-lang/RFCs/issues/236#issuecomment-646855314
  80. # xxx move to std/sugar or (preferably) some low level module
  81. try: body
  82. finally: cleanup
  83. # we're testing `execShellCmd` so don't rely on it to compile test file
  84. # note: this should be exported in posix.nim
  85. proc c_system(cmd: cstring): cint {.importc: "system", header: "<stdlib.h>".}
  86. proc compileNimProg(opt: string, name: string): string =
  87. result = buildDir / name.addFileExt(ExeExt)
  88. let cmd = "$# c -o:$# --hints:off $# $#" % [nim.quoteShell, result.quoteShell, opt, sourcePath.quoteShell]
  89. doAssert c_system(cmd) == 0, $cmd
  90. doAssert result.fileExists
  91. block execShellCmdTest:
  92. let output = compileNimProg("-d:release -d:case_testfile", "D20190111T024543")
  93. ## use it
  94. template runTest(arg: string, expected: int) =
  95. echo (arg2: arg, expected2: expected)
  96. assertEquals execShellCmd(output & " " & arg), expected
  97. runTest("exit_0", 0)
  98. runTest("exitnow_139", 139)
  99. runTest("c_exit2_139", 139)
  100. runTest("quit_139", 139)
  101. import std/streams
  102. block execProcessTest:
  103. let dir = sourcePath.parentDir
  104. let (_, err) = execCmdEx(nim & " c " & quoteShell(dir / "osproctest.nim"))
  105. doAssert err == 0
  106. let exePath = dir / addFileExt("osproctest", ExeExt)
  107. let outStr1 = execProcess(exePath, workingDir = dir, args = ["foo",
  108. "b A r"], options = {})
  109. doAssert outStr1 == dir & "\nfoo\nb A r\n"
  110. const testDir = "t e st"
  111. createDir(testDir)
  112. doAssert dirExists(testDir)
  113. let outStr2 = execProcess(exePath, workingDir = testDir, args = ["x yz"],
  114. options = {})
  115. doAssert outStr2 == absolutePath(testDir) & "\nx yz\n"
  116. removeDir(testDir)
  117. # test for PipeOutStream
  118. var
  119. p = startProcess(exePath, args = ["abcdefghi", "foo", "bar", "0123456"])
  120. outStrm = p.peekableOutputStream
  121. var tmp: string
  122. doAssert outStrm.readLine(tmp)
  123. doAssert outStrm.readChar == 'a'
  124. doAssert outStrm.peekChar == 'b'
  125. doAssert outStrm.readChar == 'b'
  126. doAssert outStrm.readChar == 'c'
  127. doAssert outStrm.peekChar == 'd'
  128. doAssert outStrm.peekChar == 'd'
  129. doAssert outStrm.readChar == 'd'
  130. doAssert outStrm.readStr(2) == "ef"
  131. doAssert outStrm.peekStr(2) == "gh"
  132. doAssert outStrm.peekStr(2) == "gh"
  133. doAssert outStrm.readStr(1) == "g"
  134. doAssert outStrm.readStr(3) == "hi\n"
  135. doAssert outStrm.readLine == "foo"
  136. doAssert outStrm.readChar == 'b'
  137. doAssert outStrm.peekChar == 'a'
  138. doAssert outStrm.readLine == "ar"
  139. tmp.setLen(4)
  140. tmp[0] = 'n'
  141. doAssert outStrm.readDataStr(tmp, 1..3) == 3
  142. doAssert tmp == "n012"
  143. doAssert outStrm.peekStr(3) == "345"
  144. doAssert outStrm.readDataStr(tmp, 1..2) == 2
  145. doAssert tmp == "n342"
  146. doAssert outStrm.peekStr(2) == "56"
  147. doAssert outStrm.readDataStr(tmp, 0..3) == 3
  148. doAssert tmp == "56\n2"
  149. p.close
  150. p = startProcess(exePath, args = ["123"])
  151. outStrm = p.peekableOutputStream
  152. let c = outStrm.peekChar
  153. doAssert outStrm.readLine(tmp)
  154. doAssert tmp[0] == c
  155. tmp.setLen(7)
  156. doAssert outStrm.peekData(addr tmp[0], 7) == 4
  157. doAssert tmp[0..3] == "123\n"
  158. doAssert outStrm.peekData(addr tmp[0], 7) == 4
  159. doAssert tmp[0..3] == "123\n"
  160. doAssert outStrm.readData(addr tmp[0], 7) == 4
  161. doAssert tmp[0..3] == "123\n"
  162. p.close
  163. try:
  164. removeFile(exePath)
  165. except OSError:
  166. discard
  167. block: # test for startProcess (more tests needed)
  168. # bugfix: windows stdin.close was a noop and led to blocking reads
  169. proc startProcessTest(command: string, options: set[ProcessOption] = {
  170. poStdErrToStdOut, poUsePath}, input = ""): tuple[
  171. output: TaintedString,
  172. exitCode: int] {.tags:
  173. [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
  174. var p = startProcess(command, options = options + {poEvalCommand})
  175. var outp = outputStream(p)
  176. if input.len > 0: inputStream(p).write(input)
  177. close inputStream(p)
  178. result = (TaintedString"", -1)
  179. var line = newStringOfCap(120).TaintedString
  180. while true:
  181. if outp.readLine(line):
  182. result[0].string.add(line.string)
  183. result[0].string.add("\n")
  184. else:
  185. result[1] = peekExitCode(p)
  186. if result[1] != -1: break
  187. close(p)
  188. var result = startProcessTest("nim r --hints:off -", options = {}, input = "echo 3*4")
  189. doAssert result == ("12\n", 0)
  190. block: # startProcess stdin (replaces old test `tstdin` + `ta_in`)
  191. let output = compileNimProg("-d:case_testfile2", "D20200626T215919")
  192. var p = startProcess(output, dir) # dir not needed though
  193. p.inputStream.write("5\n")
  194. p.inputStream.flush()
  195. var line = ""
  196. var s: seq[string]
  197. while p.outputStream.readLine(line.TaintedString):
  198. s.add line
  199. doAssert s == @["10"]
  200. block:
  201. let output = compileNimProg("-d:case_testfile3", "D20200626T221233")
  202. var x = newStringOfCap(120)
  203. block: # startProcess stdout poStdErrToStdOut (replaces old test `tstdout` + `ta_out`)
  204. var p = startProcess(output, dir, options={poStdErrToStdOut})
  205. deferScoped: p.close()
  206. do:
  207. var sout: seq[string]
  208. while p.outputStream.readLine(x.TaintedString): sout.add x
  209. doAssert sout == @["start ta_out", "to stdout", "to stdout", "to stderr", "to stderr", "to stdout", "to stdout", "end ta_out"]
  210. block: # startProcess stderr (replaces old test `tstderr` + `ta_out`)
  211. var p = startProcess(output, dir, options={})
  212. deferScoped: p.close()
  213. do:
  214. var serr, sout: seq[string]
  215. while p.errorStream.readLine(x.TaintedString): serr.add x
  216. while p.outputStream.readLine(x.TaintedString): sout.add x
  217. doAssert serr == @["to stderr", "to stderr"]
  218. doAssert sout == @["start ta_out", "to stdout", "to stdout", "to stdout", "to stdout", "end ta_out"]
  219. block: # startProcess exit code (replaces old test `texitcode` + `tafalse`)
  220. let output = compileNimProg("-d:case_testfile4", "D20200626T224758")
  221. var p = startProcess(output, dir)
  222. doAssert waitForExit(p) == QuitFailure
  223. p = startProcess(output, dir)
  224. var running = true
  225. while running:
  226. # xxx: avoid busyloop?
  227. running = running(p)
  228. doAssert waitForExit(p) == QuitFailure
  229. # make sure that first call to running() after process exit returns false
  230. p = startProcess(output, dir)
  231. for j in 0..<30: # refs #13449
  232. os.sleep(50)
  233. if not running(p): break
  234. doAssert not running(p)
  235. doAssert waitForExit(p) == QuitFailure # avoid zombies
  236. import std/strtabs
  237. block execProcessTest:
  238. var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
  239. stripLineEnd(result[0])
  240. doAssert result == ("12", 0)
  241. when not defined(windows):
  242. doAssert execCmdEx("ls --nonexistant").exitCode != 0
  243. when false:
  244. # bug: on windows, this raises; on posix, passes
  245. doAssert execCmdEx("nonexistant").exitCode != 0
  246. when defined(posix):
  247. doAssert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
  248. doAssert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)