From 1c55eb1c1c0e66bb22cedfa4c2b7b0e9f442378c Mon Sep 17 00:00:00 2001 From: Christophe De Troyer Date: Thu, 17 May 2018 10:02:58 +0200 Subject: [PATCH] subject test --- lib/subject.ex | 23 +++++++++++++++++++++++ mix.exs | 2 +- test/subject_test.exs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 lib/subject.ex diff --git a/lib/subject.ex b/lib/subject.ex new file mode 100644 index 0000000..5f240e7 --- /dev/null +++ b/lib/subject.ex @@ -0,0 +1,23 @@ +defmodule Subject do + alias Observables.GenObservable + + @moduledoc """ + Subject defines functions to create and interact with subjects. + + A Subject is an observable which acts as a regular observer. It can be observed as usual, but it also allows the programmer to manually send messages to the process. The Subject will then emit the values. + + Have a look at test/subject_test.ex for a simple example. + """ + + def create() do + {:ok, pid} = GenObservable.spawn_supervised(Observables.Subject) + + {fn observer -> + GenObservable.send_to(pid, observer) + end, pid} + end + + def next({_f, pid}, v) do + GenObservable.send_event(pid, v) + end +end \ No newline at end of file diff --git a/mix.exs b/mix.exs index ac3b3e9..8590eb1 100644 --- a/mix.exs +++ b/mix.exs @@ -4,7 +4,7 @@ defmodule Observables.MixProject do def project do [ app: :observables, - version: "0.1.7", + version: "0.1.9", elixir: "~> 1.6", start_permanent: Mix.env() == :prod, deps: deps(), diff --git a/test/subject_test.exs b/test/subject_test.exs index b8d01b5..d0bf19f 100644 --- a/test/subject_test.exs +++ b/test/subject_test.exs @@ -1,2 +1,36 @@ defmodule SubjectTest do + use ExUnit.Case + alias Observables.{Obs, GenObservable} + require Logger + + @tag :subject + test "subject" do + Code.load_file("test/util.ex") + + # Create a subject. + testproc = self() + s = Subject.create() + + # Print out all the values that this subject produces, + # and forward them to the testproc. + s + |> Obs.each(fn v -> IO.puts("Subject produced #{v}") end) + |> Obs.each(fn v -> send(testproc, {:test, v}) end) + + # Send some values to the subject, and make sure we receive them. + Subject.next(s, 10) + Subject.next(s, 20) + Subject.next(s, 30) + Test.Util.sleep(2000) + + assert_receive({:test, 10}, 1000, "did not get this message!") + assert_receive({:test, 20}, 1000, "did not get this message!") + assert_receive({:test, 30}, 1000, "did not get this message!") + + receive do + x -> flunk("Mailbox was supposed to be empty, got: #{inspect(x)}") + after + 0 -> :ok + end + end end