ttempfiles.nim 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. joinable: false # not strictly necessary
  4. """
  5. import std/tempfiles
  6. import std/[os, nre]
  7. import std/[assertions, syncio]
  8. const
  9. prefix = "D20210502T100442" # safety precaution to only affect files/dirs with this prefix
  10. suffix = ".tmp"
  11. block:
  12. var t1 = createTempFile(prefix, suffix)
  13. var t2 = createTempFile(prefix, suffix)
  14. defer:
  15. close(t1.cfile)
  16. close(t2.cfile)
  17. removeFile(t1.path)
  18. removeFile(t2.path)
  19. doAssert t1.path != t2.path
  20. let s = "1234"
  21. write(t1.cfile, s)
  22. doAssert readAll(t2.cfile) == ""
  23. doAssert readAll(t1.cfile) == ""
  24. t1.cfile.setFilePos 0
  25. doAssert readAll(t1.cfile) == s
  26. block: # createTempDir
  27. doAssertRaises(OSError): discard createTempDir(prefix, suffix, "nonexistent")
  28. block:
  29. let dir1 = createTempDir(prefix, suffix)
  30. let dir2 = createTempDir(prefix, suffix)
  31. defer:
  32. removeDir(dir1)
  33. removeDir(dir2)
  34. doAssert dir1 != dir2
  35. doAssert dirExists(dir1)
  36. doAssert dir1.lastPathPart.contains(re"^D20210502T100442(\w+).tmp$")
  37. doAssert dir1.parentDir == getTempDir().normalizePathEnd()
  38. block:
  39. let dir3 = createTempDir(prefix, "_mytmp", ".")
  40. doAssert dir3.lastPathPart.contains(re"^D20210502T100442(\w+)_mytmp$")
  41. doAssert dir3.parentDir == "." # not getCurrentDir(): we honor the absolute/relative state of input `dir`
  42. removeDir(dir3)