small medium large xlarge

Dave_gnome_head_isolated_pragsmall
15 Jul 2013, 03:42
Dave Thomas (390 posts)
  • So far, we haven’t written any tests for the application. Is there anything you can test? See what you can do.
Generic-user-small
18 Jan 2015, 10:08
Pierre Sugar (57 posts)

I have put all test in one test as I am not sure how to set the application into initial state after each test.

defmodule StackTest do
  use ExUnit.Case

  test "the application" do
    #started
    { stack, pid } = :sys.get_state Stack.Stack
    assert stack == [1,2,3]
    refute pid == nil

    #pop
    assert Stack.Stack.pop == 1

    #empty
    stack = for x <- 1..2, do: Stack.Stack.pop
    assert stack = [2,3]
    { empty_stack, pid } = :sys.get_state Stack.Stack
    assert empty_stack == []

    #push
    Stack.Stack.push 1234
    { stack, _ } = :sys.get_state Stack.Stack
    assert stack == [1234]
  end

end
Generic-user-small
20 May 2015, 01:55
Ben Stephens (1 post)

Here is a version that resets the state between each test.

defmodule StackTest do
  use ExUnit.Case
 
  setup do
    :sys.replace_state(Stack.Server, fn {_old_state, pid} -> {["Howdy", "ho", "folks"], pid} end)
    :ok
  end
  
  test "the stack has initial values" do
    { stack, pid } = :sys.get_state Stack.Server
    assert stack == ["Howdy", "ho", "folks"]
    refute pid == nil
  end

  test "can push onto the stack" do
    Stack.Server.push "!!!"
    { stack, pid } = :sys.get_state Stack.Server
    assert stack == ["!!!", "Howdy", "ho", "folks"]
  end

  test "can pop items off stack" do
    assert Stack.Server.pop == "Howdy"
    assert Stack.Server.pop == "ho"
    assert Stack.Server.pop == "folks"
  end
end
1-p1070077-1_pragsmall
07 Sep 2016, 11:09
Patrick Davey (2 posts)

Just came to see how other people did it. That :sys.get_state Stack.Stack call is pretty handy. I didn’t see that in the book. The GenServer docs have more on this. Thanks for the pointer!

Generic-user-small
01 Jun 2017, 19:10
Gert Bouwens (1 post)

Apparently the ordering of the items in the tuple for :sys.replace_state is wrong, it should be like this:

:sys.replace_state(Stack.Server, fn {pid, _old_state} -> {pid, ["Howdy", "ho", "folks"]} end)
You must be logged in to comment