Open danielemegna opened 3 years ago
This would be great! I have this problem when testing async work triggered by AMQP messages. My current workaround for this goes like:
test "something" do
test = self()
Bypass.expect(bypass, "POST", "/endpoint", fn conn ->
send(test, :request_done)
# ...response
end)
trigger_work()
# Wait for the message
assert_received :request_done, :timer.seconds(3)
end
In case that helps anyone.
EDIT: This technique isn't reliable in all circumstances because the test can still end before the process finishes 😕. Which in my cases leads to a failure as the test is supervising and shuts down the process abnormally. send_after
could be used as a band-aid.
I just tripped exactly over the same stuff and was looking through the docs on how to solve this. @danielemegna happy to help if you want to takle this issue!
@Odaeus I use the same technique, which is actually accepted in the community, cosidering that it's also suggested in the documentation of the Mox library.
In my case I usually do the following:
test "something" do
parent = self()
ref = make_ref()
Bypass.expect(bypass, "POST", "/endpoint", fn conn ->
# ...response
send(parent, {ref, :sent})
end)
trigger_work()
assert_receive {^ref, :sent}
end
When the external request is not the thing you are testing, you may be interested in using the stub/4 function. It was added specifically for this case.
Added here https://github.com/PSPDFKit-labs/bypass/pull/58
Bypass.stub(bypass, "POST", "/1.1/statuses/update.json", fn conn ->
Agent.get_and_update(AgentModule, fn step_no -> {step_no, step_no + 1} end)
Plug.Conn.resp(conn, 429, ~s<{"errors": [{"code": 88, "message": "Rate limit exceeded"}]}>)
end)
This is a nice and clean phoenix integration test. It verifies that, when a GET request hits the
/welcome
route:/an/external/service
routeEverything is good, until we face a different (quite common) async scenario.
Let's imagine that our Phoenix application, when it receives the
/welcome
GET request, it spawns a new process to contact the external service and it response synchronously with the 200 response. Since with ExUnit theverify_expectations
is executed with hooks automatically at the end of the test:Usually popular http mocking frameworks solve this problem adding some waiting capabilities to the expectations (ie. do not fail immediately, do it if expectations are not satisfied in xxxx seconds). We could add some options as keyword list as last optional argument:
What do you think? I would be happy to work on it and I have some ideas:
polling_interval
) if the expectations are satisfiedreceive
with timeout otp functionalitiesBypass.wait_to_receive(bypass_instance, request_count: 3, timeout: 2_000)
)