简体   繁体   English

在Elixir中运行Mix Test时抑制stderr

[英]Suppress stderr while running Mix Test in Elixir

I'm working with several external processes in my application. 我在我的应用程序中使用了几个外部进程。 During tests the stderr output of several of these is output inline with my test messages and results. 在测试期间,其中几个的stderr输出与我的测试消息和结果一起输出。 I can do this: 我可以做这个:

mix test --trace 2> error.log

However, when I do, I lose all my lovely colors. 然而,当我这样做时,我失去了所有可爱的颜色。 Also some Elixir errors still appear, though not all (which is fine for me). 还有一些Elixir错误仍然出现,但不是全部(对我来说这很好)。

Is there a better way to suppress the errors of the external programs without affecting the mix output? 有没有更好的方法来抑制外部程序的错误而不影响混合输出? Is it even a good idea? 这甚至是个好主意吗?

Or should my tests not actually interact with the real command-line utilities? 或者我的测试是否真的不与真正的命令行实用程序交互? I ask because at that point I'm honestly no longer clear on what I'm testing. 我问,因为那时我真的不再清楚我正在测试什么。

UPDATE: 更新:

Below is a simplified function and test to illustrate the concept better. 下面是一个简化的功能和测试,以更好地说明这个概念。

The function: 功能:

@doc "Function takes a pre-routing rule as a string and adds it with iptables"
def addrule(pre_routing_rule)
  %Porcelain.Result{out: _output, status: status} = Porcelain.shell("sudo iptables -t nat -A #{pre_routing_rule}")
end

The test: 考试:

test "Removing a non-existent rule fails" do 
  Rules.clear
  assert {:error, :eiptables} == Rules.remove("PREROUTING -p tcp --dport 9080 -j DNAT --to-destination 192.168.1.3:9080")
end

This test passes perfectly. 这个测试完美通过。 However inline with the test messages it also outputs iptables: No chain/target/match by that name. 但是与测试消息一致,它也输出iptables: No chain/target/match by that name. . The exact position of the message is also unpredictable and en masse these messages make test information very hard to read. 消息的确切位置也是不可预测的,并且这些消息使得测试信息非常难以阅读。 Then I redirect stderr and I lose my colour-coding for some reason which also makes it hard to follow test results. 然后我重定向stderr,由于某些原因我失去了颜色编码,这也使得很难跟踪测试结果。

I think you should suppress these error messages at the point where you are calling the commandline utilities for example using the same method as in the question. 我认为您应该在调用命令行实用程序时抑制这些错误消息,例如使用与问题中相同的方法。

The lack of colors is connected to how Elixir detects ANSI : 缺少颜色与Elixir 检测ANSI的方式有关

[ANSI support] is by default false unless Elixir can detect during startup that both stdout and stderr are terminals. [ANSI支持]默认为false,除非Elixir在启动期间可以检测到stdout和stderr都是终端。

I'd suggest in general that you decide how to deal with stderr in your system calls. 我一般建议您决定如何在系统调用中处理stderr。 What's happening is that the test framework catches stdout, but not stderr. 发生的事情是测试框架捕获stdout,但不是stderr。

You can change how stderr is dealt with in the initial Porcelain call See 您可以在最初的瓷器调用中更改stderr的处理方式

Porcelain API Docs Porcelain API Docs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM