;; io-input.sx — tests for getLine, getContents, readFile, writeFile.

(hk-test
  "getLine reads single line"
  (hk-run-io-with-input "main = getLine >>= putStrLn" (list "hello"))
  (list "hello"))

(hk-test
  "getLine reads two lines"
  (hk-run-io-with-input
    "main = do { line1 <- getLine; line2 <- getLine; putStrLn line1; putStrLn line2 }"
    (list "first" "second"))
  (list "first" "second"))

(hk-test
  "getLine bind in layout do"
  (hk-run-io-with-input
    "main = do\n  line <- getLine\n  putStrLn line"
    (list "world"))
  (list "world"))

(hk-test
  "getLine echo with prefix"
  (hk-run-io-with-input
    "main = do\n  line <- getLine\n  putStrLn (\"Got: \" ++ line)"
    (list "test"))
  (list "Got: test"))

(hk-test
  "getContents reads all lines joined"
  (hk-run-io-with-input
    "main = getContents >>= putStr"
    (list "line1" "line2" "line3"))
  (list "line1\nline2\nline3"))

(hk-test
  "getContents empty stdin"
  (hk-run-io-with-input "main = getContents >>= putStr" (list))
  (list ""))

(hk-test
  "readFile reads pre-loaded content"
  (begin
    (set! hk-vfs (dict))
    (dict-set! hk-vfs "hello.txt" "Hello, World!")
    (hk-run-io "main = readFile \"hello.txt\" >>= putStrLn"))
  (list "Hello, World!"))

(hk-test
  "writeFile creates file"
  (begin
    (set! hk-vfs (dict))
    (hk-run-io "main = writeFile \"out.txt\" \"written content\"")
    (get hk-vfs "out.txt"))
  "written content")

(hk-test
  "writeFile then readFile roundtrip"
  (begin
    (set! hk-vfs (dict))
    (hk-run-io
      "main = do { writeFile \"f.txt\" \"round trip\"; readFile \"f.txt\" >>= putStrLn }"))
  (list "round trip"))

(hk-test
  "readFile error on missing file"
  (guard
    (e (true (>= (index-of e "file not found") 0)))
    (begin
      (set! hk-vfs (dict))
      (hk-run-io "main = readFile \"no.txt\" >>= putStrLn")
      false))
  true)

(hk-test
  "getLine then writeFile combined"
  (begin
    (set! hk-vfs (dict))
    (hk-run-io-with-input
      "main = do\n  line <- getLine\n  writeFile \"cap.txt\" line"
      (list "captured"))
    (get hk-vfs "cap.txt"))
  "captured")

{:fails hk-test-fails :pass hk-test-pass :fail hk-test-fail}