Skip to content

Commit

Permalink
test: add a mock test for the REPL server
Browse files Browse the repository at this point in the history
  • Loading branch information
mtshiba committed Apr 26, 2023
1 parent 03a30a4 commit 5536858
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 4 deletions.
7 changes: 3 additions & 4 deletions crates/erg_common/python_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -738,15 +738,14 @@ pub fn _eval_pyc<S: Into<String>>(file: S, py_command: Option<&str>) -> String {
String::from_utf8_lossy(&out.stdout).to_string()
}

pub fn _exec_py(code: &str) -> Option<i32> {
pub fn exec_py(file: &str) -> Option<i32> {
let mut child = if cfg!(windows) {
Command::new(which_python())
.arg("-c")
.arg(code)
.arg(file)
.spawn()
.expect("cannot execute python")
} else {
let exec_command = format!("{} -c \"{}\"", which_python(), code);
let exec_command = format!("{} {file}", which_python());
Command::new("sh")
.arg("-c")
.arg(exec_command)
Expand Down
40 changes: 40 additions & 0 deletions src/scripts/repl_server_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import itertools
import random
import string

with open("./src/scripts/repl_server.py") as f:
code = f.readlines()

code.insert(0, "__PORT__ = 9000\n")
code = itertools.takewhile(lambda l: not l.startswith("# DummyVM"), code)

exec("".join(code))


class MockSocket:
def __init__(self):
self.data = bytearray()
self.cursor = 0

def send(self, data):
self.data.extend(data)

def recv(self, bufsize):
if self.cursor > len(self.data):
raise Exception(f"MockSocket: recv({bufsize}) out of range")
data = bytes(self.data[self.cursor : self.cursor + bufsize])
self.cursor += bufsize
return data

corr_data = "".join(random.choices(string.ascii_uppercase + string.digits, k=2048))
s = MessageStream(MockSocket())

s.send_msg(INST.PRINT, corr_data)
inst, recv_data = s.recv_msg()
assert inst == INST.PRINT
assert recv_data == corr_data

s.send_msg(INST.EXIT, "")
inst, recv_data = s.recv_msg()
assert inst == INST.EXIT
assert recv_data == ""
9 changes: 9 additions & 0 deletions tests/repl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
mod common;

use common::expect_repl_failure;
use common::expect_repl_success;
use erg_common::python_util::exec_py;

#[test]
#[ignore]
Expand Down Expand Up @@ -193,3 +195,10 @@ fn exec_repl_invalid_def_after_the_at_sign() -> Result<(), ()> {
1,
)
}

#[test]
#[ignore]
fn exec_repl_server_mock_test() -> Result<(), ()> {
assert_eq!(exec_py("src/scripts/repl_server_test.py"), Some(0));
Ok(())
}

0 comments on commit 5536858

Please sign in to comment.