Skip to content

Commit

Permalink
grass.jupyter: Test init and session (OSGeo#2247)
Browse files Browse the repository at this point in the history
Adds test for Jupyter init, session, and finish using pytest.

Uses temporary script to test automatic (implicit) cleanup with weakref.finalize (always needed).

Uses temporary script for the standard test because the session restores the global state cleanly, namely the global variables in the Python library (temporary solution).
  • Loading branch information
wenzeslaus authored Mar 16, 2022
1 parent 0ba1287 commit f9ee75c
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions python/grass/jupyter/tests/grass_jupyter_session_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Test session functions in grass.jupyter"""

import subprocess
import os
import sys


# All init tests change the global environment, but we use a separate process
# only when it is necessary.
# Ideally, the functions would support env parameter and the tests
# would mostly use that.
def run_in_subprocess(file):
"""Run function in a separate process
The function must take a Queue and put its result there.
The result is then returned from this function.
"""
process = subprocess.run(
[sys.executable, os.fspath(file)], stdout=subprocess.PIPE, text=True, check=True
)
return process.stdout


def test_init_finish(tmp_path):
"""Check that init function works with an explicit session finish"""
location = "test"
script = f"""
import os
import grass.script as gs
import grass.jupyter as gj
gs.core._create_location_xy("{tmp_path}", "{location}")
session = gj.init("{tmp_path / location}")
gs.read_command("g.region", flags="p")
print(os.environ["GISRC"])
session.finish()
"""
file = tmp_path / "script.py"
file.write_text(script)
session_file = run_in_subprocess(file)
assert session_file, "Expected something from the subprocess"
session_file = session_file.strip()
assert "\n" not in session_file, "Expected a file name from the subprocess"
assert not os.path.exists(session_file), f"Session file {session_file} not deleted"


def test_init_with_auto_finish(tmp_path):
"""Check that init function works with an implicit session finish"""
location = "test"
script = f"""
import os
import grass.script as gs
import grass.jupyter as gj
gs.core._create_location_xy("{tmp_path}", "{location}")
session = gj.init("{tmp_path / location}")
print(os.environ["GISRC"])
"""

file = tmp_path / "script.py"
file.write_text(script)
session_file = run_in_subprocess(file)
assert session_file, "Expected something from the subprocess"
session_file = session_file.strip()
assert "\n" not in session_file, "Expected a file name from the subprocess"
assert not os.path.exists(session_file), f"Session file {session_file} not deleted"

0 comments on commit f9ee75c

Please sign in to comment.