Over the last week, I figured out how to write async tests for capturing multiple logs. The use case was I wanted to see if N log messages were generated when passing a collection into a process. While the test code was for a logger my company uses internally, I could basically write the equivalent for the Elixir Logger.
Imagine a test like this...
defmodule MyAppTest do
use ExUnit, async: true
import MyCaptureLog
test "capture 3 banana logs and 2 potato logs" do
# starts a process that accumulates log messages
# all logs generated by this logger will be intercepted and accumulated
{:ok, pid} = SomeLogger.start_link()
# generate logs without needing a callback
# logs generated by processes running within the test are isolated within the test sandbox
_ = for _ <- (1..3), do: SomeLogger.info("I love a ripe banana")
_ = for _ <- (1..2), do: SomeLogger.info("How would you like your potato?")
# captures & removes log messages from accumulating process
assert <captured 3 logs containing the string "banana">
assert <captured 2 logs matching the regex "potato">
# no cleanup "staop_capturing_logs()" is necessary, but it could implemented
# I think this type of test could be modified to capture standard out I/O, too (but I'd have to investigate)
end
end
Any interest? I'm flexible on the syntax, semantics, usability, etc.