1 from __future__ import annotations

2

3 import itertools

4 import os

5

6 import pytest

7

8 from muutils.nbutils.convert_ipynb_to_script import process_dir, process_file

9 from muutils.nbutils.run_notebook_tests import run_notebook_tests

10

11 notebooks_input_dir: str = "tests/input_data/notebooks"

12 notebooks_converted_input_dir: str = "tests/input_data/notebooks_converted/"

13 nb_test_dir: str = "tests/_temp/run_notebook_tests"

14 nb_conversion_dir: str = "tests/_temp/test_file_conversion"

15

16

17 def test_run_notebook_tests():

18 os.makedirs(nb_test_dir, exist_ok=True)

19 print(os.listdir(notebooks_input_dir))

20 print(os.listdir(notebooks_converted_input_dir))

21

22 # convert the notebooks

23 process_dir(

24 input_dir=notebooks_input_dir,

25 output_dir=nb_test_dir,

26 disable_plots=True,

27 )

28

29 # run the notebooks

30 run_notebook_tests(

31 notebooks_dir=notebooks_input_dir,

32 converted_notebooks_temp_dir=nb_test_dir,

33 run_python_cmd="python",

34 )

35

36 # assert output directory contents are identical

37 output_files: list = sorted(os.listdir(notebooks_converted_input_dir))

38 assert sorted(os.listdir(nb_test_dir)) == output_files

39

40 for fname in output_files:

41 with open(os.path.join(notebooks_converted_input_dir, fname), "r") as f:

42 expected = f.read()

43 with open(os.path.join(nb_test_dir, fname), "r") as f:

44 actual = f.read()

45 assert expected == actual

46

47

48@pytest.mark.parametrize(

49 "idx, args",

50 enumerate(

51 itertools.product(

52 [True, False],

53 [r"#%%", "#" + "=" * 50],

54 [True, False],

55 ["%", ("!", "#"), ("import", "return")],

56 )

57 ),

58)

59 def test_file_conversion(idx, args):

60 os.makedirs(nb_conversion_dir, exist_ok=True)

61 process_file(

62 in_file=os.path.join(notebooks_input_dir, "dummy_notebook.ipynb"),

63 out_file=os.path.join(nb_conversion_dir, f"dn-test-{idx}.py"),

64 strip_md_cells=args[0],

65 header_comment=args[1],

66 disable_plots=args[2],

67 filter_out_lines=args[3],

68 )