Skip to content

Commit 6925299

Browse files
committed
Add a test for port ownership switchover
1 parent 3d1d8f4 commit 6925299

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

test/gleam/erlang/port_test.gleam

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import gleam/erlang/port
22
import gleam/erlang/port/receive.{Data, ExitStatus}
3-
import gleam/erlang/process.{receive, port_open, port_subject}
3+
import gleam/erlang/process.{receive, port_open, port_connect, port_subject}
4+
5+
@external(erlang, "gleam_erlang_test_ffi", "assert_gleam_panic")
6+
fn assert_panic(f: fn() -> t) -> String
47

58
pub fn port_open_test() {
69
let assert Ok(port) = port.open(
@@ -61,3 +64,41 @@ pub fn delay_port_test() {
6164
assert Ok(ExitStatus(0)) == receive(subject, 100)
6265
assert Error(Nil) == receive(subject, 100)
6366
}
67+
68+
// mirrors name_other_switchover_test in process_test a bit
69+
pub fn port_switchover_test() {
70+
// create a new port
71+
let assert Ok(port) = port.open(
72+
port.spawn_executable("/bin/bash"),
73+
[port.Args(["-c", "cat"]), port.UseStdio, port.ExitStatus, port.Binary]
74+
)
75+
76+
let subject = process.port_subject(port)
77+
78+
// verify we can listen on it
79+
port.port_command(port, <<"wasd\n">>, [])
80+
assert Ok(Data(<<"wasd\n">>)) == receive(subject, 5)
81+
82+
// switch the owner to some other erlang process
83+
let pid = process.spawn(fn() { process.sleep(20) })
84+
let newsubject = port_connect(port, pid)
85+
86+
// try to listen on it again
87+
port.port_command(port, <<"test2\n">>, [])
88+
assert assert_panic(fn() { process.receive(newsubject, 0) })
89+
== "Cannot receive with a subject owned by another process"
90+
// test the original subject, too
91+
assert assert_panic(fn() { process.receive(subject, 0) })
92+
== "Cannot receive with a subject owned by another process"
93+
94+
// let's switch back now
95+
let newnewsubject = port_connect(port, process.self())
96+
port.port_command(port, <<"test3\n">>, [])
97+
assert Ok(Data(<<"test3\n">>)) == receive(subject, 5)
98+
port.port_command(port, <<"test4\n">>, [])
99+
assert Ok(Data(<<"test4\n">>)) == receive(newsubject, 5)
100+
port.port_command(port, <<"test5\n">>, [])
101+
assert Ok(Data(<<"test5\n">>)) == receive(newnewsubject, 5)
102+
103+
port.close(port)
104+
}

0 commit comments

Comments
 (0)