Skip to content

Commit 10158bb

Browse files
committed
Add in new pytest fixture for reading notebooks as scripts.
1 parent c774355 commit 10158bb

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

tests/conftest.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
import betamax
1515
import pytest
16+
import nbconvert
17+
import nbformat
1618
import requests
1719
from betamax.cassette.cassette import Placeholder
1820
from betamax_serializers import pretty_json
@@ -534,6 +536,45 @@ def sklearn_classification_model(iris_dataset):
534536
return model
535537

536538

539+
@pytest.fixture(scope="session")
540+
def notebook_code():
541+
def process_multiline(lines):
542+
filtered_lines = []
543+
current_line = ""
544+
open_brackets = 0
545+
546+
for line in lines:
547+
line = line.strip()
548+
if line:
549+
current_line += line
550+
open_brackets += len(re.findall(r"[({\[]", line)) - len(
551+
re.findall(r"[)}\]]", line)
552+
)
553+
if open_brackets == 0:
554+
filtered_lines.append(current_line)
555+
current_line = ""
556+
557+
return filtered_lines
558+
559+
def filter_code(source):
560+
source = re.sub(r"(?m)^\s*#.*\n?", "", source)
561+
lines = source.strip().split("\n")
562+
lines = process_multiline(lines)
563+
564+
return lines
565+
566+
def convert_notebook_to_script(notebook_path):
567+
with open(notebook_path) as notebook_file:
568+
nb = nbformat.reads(notebook_file.read(), nbformat.NO_CONVERT)
569+
exporter = nbconvert.PythonExporter()
570+
source, _ = exporter.from_notebook_node(nb)
571+
lines = filter_code(source)
572+
573+
return lines
574+
575+
return convert_notebook_to_script
576+
577+
537578
@pytest.fixture
538579
def cache(request):
539580
"""Wraps the built-in py.test cache with a custom cache that segregates data based on test grouping."""

0 commit comments

Comments
 (0)