Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make bypassing capture context-aware #447

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 23 additions & 17 deletions src/kaocha/plugin/capture_output.cljc
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
(ns kaocha.plugin.capture-output
(:require
[clojure.java.io :as io]
[kaocha.hierarchy :as hierarchy]
[kaocha.plugin :as plugin :refer [defplugin]])
(:import (java.io ByteArrayOutputStream
FileOutputStream ;; false positive
OutputStream
PrintStream
PrintWriter)))
[kaocha.hierarchy :as hierarchy]
[kaocha.plugin :as plugin :refer [defplugin]])
(:import
(java.io
ByteArrayOutputStream
OutputStream
PrintStream
PrintWriter)))

;; Many props to eftest for much of this code

(def ^:dynamic *test-buffer* nil)

(def ^:dynamic *previous-writers* nil)

(def active-buffers (atom #{}))

(defn make-buffer []
Expand All @@ -24,11 +26,11 @@

(defmacro with-test-buffer [buffer & body]
`(try
(swap! active-buffers conj ~buffer)
(binding [*test-buffer* ~buffer]
~@body)
(finally
(swap! active-buffers disj ~buffer))))
(swap! active-buffers conj ~buffer)
(binding [*test-buffer* ~buffer]
~@body)
(finally
(swap! active-buffers disj ~buffer))))

(defn- doto-capture-buffer [f]
(if *test-buffer*
Expand All @@ -54,6 +56,7 @@
(System/setOut new-stream)
(System/setErr new-stream)
{:captured-writer new-writer
:previous-writers {:out *out*, :err *err*}
:old-system-out old-out
:old-system-err old-err}))

Expand All @@ -65,7 +68,9 @@
`(let [context# (init-capture)
writer# (:captured-writer context#)]
(try
(binding [*out* writer#, *err* writer#]
(binding [*out* writer#
*err* writer#
*previous-writers* (or *previous-writers* (:previous-writers context#))]
(with-redefs [*out* writer#, *err* writer#]
~@body))
(finally
Expand Down Expand Up @@ -110,6 +115,7 @@
"Bypass output-capturing within this code block, so any print statements go to
the process out/err streams without being captured."
[& body]
`(binding [*out* (io/writer (PrintStream. (FileOutputStream. java.io.FileDescriptor/out)))
*err* (io/writer (PrintStream. (FileOutputStream. java.io.FileDescriptor/err)))]
~@body)))
`(let [{out# :out, err# :err} (or *previous-writers* {:out *out*, :err *err*})]
(binding [*out* out#
*err* err#]
~@body))))