ttempfiles.nim 1.3 KB

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