micheloliveira

micheloliveira

I would like to make a test to assert if specific status codes were used when a websocket connection is closed.

In my code, I raise {:stop, :normal, {1009, "message-too-big"}, :init}, {:stop, :normal, {1007, "invalid-json"}, :init}, {:stop, :normal, {4000, "missing-required-field"}, :init} and others.

When I interact in websocket using wscat:

wscat -c ws://localhost:4000/v1/ws
(I provoke an error resulting in a connection closed by server)

I get the closed connection messages as:

Disconnected (code: 1007, reason: "invalid-json")

My test would be something like that:

  test "sends a invalid JSON" do
    assert {:ok, client} = WebsocketClient.connect(self(), @path, :noop)
    WebsocketClient.send(client, {:text, '{"foo": "bar", something_wrong_here}')})
    
   # assert if the connection was closed with status code 1007 and reason invalid-json
  end

How could I write the status code and reason asserts?

Showing Posts 1 to 5

al2o3cr

al2o3cr

What is WebsocketClient? I couldn’t find anything with a similar API in any of the likely hits for “websocket” on hex.pm.


As far as the specifics of an assertion, I find it useful to assert clearly-wrong things first and then let the failure messages clue me into what’s going on. For instance:

result = do_something_complicated(etc etc etc)

assert result == "foo"

Running a spec like this and seeing the assert fail produces several important pieces of data:

  • demonstrates that do_something_complicated at least runs (important when the setup is tricky)

  • inspects result in the failure message

micheloliveira

micheloliveira OP

I am sorry. Missing information: Websocketclient is my class to abstract GenServer lib:

  def connect(sender, url, serializer, headers \\ []) do
    with {:ok, socket} <- GenServer.start_link(__MODULE__, {sender, serializer}),
         {:ok, :connected} <- GenServer.call(socket, {:connect, url, headers}) do
      {:ok, socket}
    end
  end

  def send(socket, msg) do
    GenServer.call(socket, {:send, msg})
  end
micheloliveira

micheloliveira OP

About the test itself, in the example, I want to send a bad formated JSON message, since something_wrong_here is not inside quotation marks and is not a key/value, it is a invalid structure in JSON:

{"foo": "bar", something_wrong_here}

My application is intolerant to client errors, so, the behaviour is immediately do a disconnection. There is no message sent back, only the disconnection. I want to test if the client was disconnected and if the correct status code and reason for disconnection were sent (using the websocket protocol). I expect to get the same message shown when I make this call using the wscat command line:

Disconnected (code: 1007, reason: "invalid-json")

I do not know how to get this “disconnection” state and data.

al2o3cr

al2o3cr

This part of the code gives a little bit of information about what might happen. The implementation of send tells me that the test will be waiting for a reply.

HOWEVER

It tells nothing else about what might happen when the connection malfunctions. Does the handle_call({:send, msg} handler crash (and cause the test to exit as well)? Does it reply with {:error, ????}? Something else entirely?

micheloliveira

micheloliveira OP

I close connection from server returning a {:stop, :normal, {result["code"], result["msg"]}, :init} from handle_in function like this:

defmodule MyApp.Websocket do
  @behaviour Phoenix.Socket.Transport
  ...
  def handle_in({input, _opts}, state) do
      result  = ...
      result_text = ...
      ...
      case result["type"] do
        "error" -> {:stop, :normal, {result["code"], result["msg"]}, :init}
        _ -> {:reply, :ok, {:text, result_text}, new_state}
      end
    end
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Alvinkariuki
How Can I Optimise Compile Time Dependencies I have been building an elixir application for about 2 years now. Many modules and files ha...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New

Other Trending Topics Top

mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews