测试时禁止记录器

时间:2017-12-27 17:06:19

标签: testing logging elixir

我想知道如何在测试时禁用Elixir中的日志记录。在我当前的代码中,我测试记录器消息,所以我不想完全禁用它,但是隐藏消息直到任何测试停止传递。

我使用mix和ExUnit来管理和测试我的项目。

mix test
Compiling 2 files (.ex)
.........
17:59:18.446 [warn]  Code seems to be empty
.
17:59:18.447 [warn]  Code doesn't contain HLT opcode
.
17:59:18.448 [warn]  Code doesn't contain HLT opcode

17:59:18.448 [error] Label error doesn't exist
.....

Finished in 0.07 seconds
16 tests, 0 failures

3 个答案:

答案 0 :(得分:9)

使用ExUnit.CaptureLog

import ExUnit.CaptureLog

test "example" do
   assert capture_log(fn ->
      Logger.error "log msg"
   end) =~ "log msg"
end

或者,如果您只想忽略任何日志,则:

@tag capture_log: true
test "example" do
    Logger.error "log msg"
end

答案 1 :(得分:6)

在您的config/test.exs文件中为记录器添加以下配置:

config :logger, level: :error

如果您没有特定于环境的配置,请在config/config.exs中添加以下行:

config :logger, level:
  case Mix.env do
    :test -> :error
    _ -> :info
  end

另一种选择是使用另一个后端作为日志消息(假设{:logger_file_backend, "~> 0.0"}的{​​{1}}部分中包含deps):

mix.exs

答案 2 :(得分:3)

我在Logger的文档中发现了remove_backend()函数,所以在使用之后 Logger.remove_backend(:console) 在应该禁用Logger的文件中,每条记录的消息都消失了(测试正在通过)。

编辑:我问Logger devs这个问题。显然,最好在测试之上使用@moduletag :capture_log而不是删除后端。无论如何,工作,对我来说很好。