Return consecutively different values ​​for the `with-redefs` (Clojure) character

I hope to use with-redefsto make fun of user input from STDIN.

Firstly, I am testing incorrect input, which the user must ask for input. Then enter the correct entry.

Is there a way to use with-redefsdifferent values ​​to bind this character to sequentially?

I am trying to get this functionality:

(with-redefs [read-line (fn [] "HI")
              read-line (fn [] "OK")]
  (do (println (read-line)) ;; -> "HI"
      (println (read-line)))) ;; -> "OK"
+4
source share
3 answers

Not definitely, but you can always give a lambda with some condition!

(let [a (atom ["a" "b"])]
  (defn f []
    (let [r (first @a)]
      (swap! a rest)
      r)))

(f) ;; "a"
(f) ;; "b"
(f) ;; nil

In your particular case, it would be wise to have a function that generates a stateful function. So a complete example:

(defn maker [l]
  (let [a (atom l)]
    (fn []
      (let [r (first @a)]
        (swap! a rest)
        r))))

(with-redefs [read-line (maker ["HI" "OK"])]
  (do (println (read-line)) ;; -> "HI"
      (println (read-line)))) ;; -> "OK"
+6
source

, , with-in-str :

  (with-in-str "Hello"
    (println (read-line)))
  (with-in-str "There"
    (println (read-line))))

:

(read-line) => "Hello"
(read-line) => "There"

Clojure Cheatsheet !

+4

Here is an example of code that might be useful, I believe:

(ns project.test
  (:require [clojure.test :refer :all]))

(deftest test-user-input

  (testing "wrong input"
    (with-in-str "some wrong input"
      (is (thrown?
           SomeExceptionClass
           (call-your-function)))))

  (testing "correct input"
    (with-in-str "some correct input"
      (let [result (call-your-function)]
        (is (= result [:proper :data]))))))
0
source

Source: https://habr.com/ru/post/1692515/


All Articles