Skip to content

Commit

Permalink
Improve test for selector replacement in actor
Browse files Browse the repository at this point in the history
  • Loading branch information
arnarg committed Jul 19, 2023
1 parent f8e408d commit 82cddff
Showing 1 changed file with 27 additions and 18 deletions.
45 changes: 27 additions & 18 deletions test/gleam/otp/actor_test.gleam
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import gleam/otp/actor.{Continue, Selecting}
import gleam/erlang/process.{Pid, Selector}
import gleam/erlang/process.{Pid, Subject}
import gleam/erlang/atom.{Atom}
import gleam/otp/system
import gleam/dynamic.{Dynamic}
Expand Down Expand Up @@ -134,49 +134,58 @@ pub fn unexpected_message_handled_test() {
|> should.equal(dynamic.from("Unexpected message 1"))
}

type ActorMessage(inner) {
UserMessage(inner)
ReplaceSelector(selector: Selector(ActorMessage(inner)))
type ActorMessage {
UserMessage(String)
ReplaceSelector(
reply: Subject(Subject(String)),
mapper: fn(String) -> ActorMessage,
)
}

pub fn replace_selector_test() {
let assert Ok(subject) =
actor.start(
"init",
fn(msg: ActorMessage(String), state) {
fn(msg: ActorMessage, state) {
case msg {
UserMessage(string) -> Continue("user message: " <> string)
ReplaceSelector(selector) -> Selecting(state, selector)
ReplaceSelector(reply, mapper) -> {
// Create a new subject and create a selector
// for it using the mapper function
let subject = process.new_subject()
let selector =
process.new_selector()
|> process.selecting(subject, mapper)

// Send new subject back to caller
process.send(reply, subject)

Selecting(state, selector)
}
}
},
)

// Send initial user message to original subject
process.send(subject, UserMessage("test 1"))

subject
|> process.subject_owner
|> system.get_state()
|> should.equal(dynamic.from("user message: test 1"))

process.send(
subject,
ReplaceSelector(
process.new_selector()
|> process.selecting_anything(fn(data) {
data
|> dynamic.unsafe_coerce
|> UserMessage
}),
),
)
// Get a new subject with replaced selector
let replaced = process.call(subject, ReplaceSelector(_, UserMessage), 1000)

raw_send(process.subject_owner(subject), "test 2")
// Send to new subject
process.send(replaced, "test 2")

subject
|> process.subject_owner
|> system.get_state()
|> should.equal(dynamic.from("user message: test 2"))

// Send to original subject
process.send(subject, UserMessage("test 3"))

subject
Expand Down

0 comments on commit 82cddff

Please sign in to comment.