grass_jupyter_session_test.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Test session functions in grass.jupyter"""
  2. import subprocess
  3. import os
  4. import sys
  5. # All init tests change the global environment, but we use a separate process
  6. # only when it is necessary.
  7. # Ideally, the functions would support env parameter and the tests
  8. # would mostly use that.
  9. def run_in_subprocess(file):
  10. """Run function in a separate process
  11. The function must take a Queue and put its result there.
  12. The result is then returned from this function.
  13. """
  14. process = subprocess.run(
  15. [sys.executable, os.fspath(file)], stdout=subprocess.PIPE, text=True, check=True
  16. )
  17. return process.stdout
  18. def test_init_finish(tmp_path):
  19. """Check that init function works with an explicit session finish"""
  20. location = "test"
  21. script = f"""
  22. import os
  23. import grass.script as gs
  24. import grass.jupyter as gj
  25. gs.core._create_location_xy("{tmp_path}", "{location}")
  26. session = gj.init("{tmp_path / location}")
  27. gs.read_command("g.region", flags="p")
  28. print(os.environ["GISRC"])
  29. session.finish()
  30. """
  31. file = tmp_path / "script.py"
  32. file.write_text(script)
  33. session_file = run_in_subprocess(file)
  34. assert session_file, "Expected something from the subprocess"
  35. session_file = session_file.strip()
  36. assert "\n" not in session_file, "Expected a file name from the subprocess"
  37. assert not os.path.exists(session_file), f"Session file {session_file} not deleted"
  38. def test_init_with_auto_finish(tmp_path):
  39. """Check that init function works with an implicit session finish"""
  40. location = "test"
  41. script = f"""
  42. import os
  43. import grass.script as gs
  44. import grass.jupyter as gj
  45. gs.core._create_location_xy("{tmp_path}", "{location}")
  46. session = gj.init("{tmp_path / location}")
  47. print(os.environ["GISRC"])
  48. """
  49. file = tmp_path / "script.py"
  50. file.write_text(script)
  51. session_file = run_in_subprocess(file)
  52. assert session_file, "Expected something from the subprocess"
  53. session_file = session_file.strip()
  54. assert "\n" not in session_file, "Expected a file name from the subprocess"
  55. assert not os.path.exists(session_file), f"Session file {session_file} not deleted"