|
1 | 1 | import gleam/erlang/port |
2 | 2 | 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 |
4 | 7 |
|
5 | 8 | pub fn port_open_test() { |
6 | 9 | let assert Ok(port) = port.open( |
@@ -61,3 +64,41 @@ pub fn delay_port_test() { |
61 | 64 | assert Ok(ExitStatus(0)) == receive(subject, 100) |
62 | 65 | assert Error(Nil) == receive(subject, 100) |
63 | 66 | } |
| 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