gpt4 book ai didi

elixir - 如何断言 Elixir 消息按顺序到达

转载 作者:行者123 更新时间:2023-12-04 23:39:43 26 4
gpt4 key购买 nike

我正在构建一个以特定顺序发送消息的 Elixir 模块。我写了这样的单元测试

MyModule.send_msgs(self())
assert_received {:event, 1}
assert_received {:event, 2}
assert_received {:event, 3}

问题是,即使我洗牌 assert_received命令,测试仍然通过。
MyModule.send_msgs(self())
assert_received {:event, 2}
assert_received {:event, 1}
assert_received {:event, 3}

看来 assert_received不关心消息到达的顺序。不仅仅是 assert_received ,据我所知, receive也可以让消息乱序。
所以,我的问题是,如果可以乱序接收消息,如何确保到达消息的顺序?

最佳答案

似乎没有执行此操作的现有函数,但很容易制作自己的宏来断言邮箱中的下一条消息与特定模式匹配:

defmacro assert_next_receive(pattern, timeout \\ 100) do
quote do
receive do
message ->
assert unquote(pattern) = message
after unquote(timeout) ->
raise "timeout" # you might want to raise a better message here
end
end
end

测试:
defmodule MTest do
use ExUnit.Case

def send_msgs(pid) do
send pid, {:event, 1}
send pid, {:event, 2}
send pid, {:event, 3}
end

defmacro assert_next_receive(pattern, timeout \\ 100) do
quote do
receive do
message ->
assert unquote(pattern) = message
after unquote(timeout) ->
raise "timeout" # you might want to raise a better message here
end
end
end

test "should pass" do
send_msgs(self())
assert_next_receive {:event, 1}
assert_next_receive {:event, 2}
assert_next_receive {:event, 3}
end

test "should fail" do
send_msgs(self())
assert_next_receive {:event, 1}
assert_next_receive {:event, 3}
assert_next_receive {:event, 2}
end
end

输出:
.

1) test should fail (MTest)
test/m_test.exs:29
match (=) failed
code: {:event, 3} = message
right: {:event, 2}
stacktrace:
test/m_test.exs:32: (test)



Finished in 0.05 seconds
2 tests, 1 failure

Randomized with seed 351622

关于elixir - 如何断言 Elixir 消息按顺序到达,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41543466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com