ttempfiles.nim 1.3 KB

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