Skip to content

Commit

Permalink
Ensure nbformat minor version is present when upgrading (#237)
Browse files Browse the repository at this point in the history
* Ensure nbformat minor version is present when upgrading
Motivation:
  - We have seen a number of notebooks which do not contain the nbformat
    minor version, this throws a key error when trying to update. This
    pr adds a check to ensure it is present and throws a validation error
    if not.

* fix test
  • Loading branch information
gwincr11 committed Dec 17, 2021
1 parent 6be91cc commit dee3e4f
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
20 changes: 20 additions & 0 deletions nbformat/tests/no_min_version.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"test"
]
}
],
"metadata": {
"language_info": {
"name": "plaintext"
},
"orig_nbformat": 4
},
"nbformat": 4
}
9 changes: 9 additions & 0 deletions nbformat/tests/test_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,12 @@ def test_invalid_cell_id():
with pytest.raises(ValidationError):
validate(nb)
assert not isvalid(nb)

def test_notebook_invalid_without_min_version():
with TestsBase.fopen(u'no_min_version.ipynb', u'r') as f:
nb = read(f, as_version=4)
with pytest.raises(ValidationError):
validate(nb)

def test_notebook_invalid_without_main_version():
pass
3 changes: 3 additions & 0 deletions nbformat/v4/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import json
import re
from .. import validator

from .nbbase import (
random_cell_id,
Expand Down Expand Up @@ -38,6 +39,8 @@ def upgrade(nb, from_version=None, from_minor=None):
if not from_version:
from_version = nb['nbformat']
if not from_minor:
if not 'nbformat_minor' in nb:
raise validator.ValidationError('The notebook does not include the nbformat minor which is needed')
from_minor = nb['nbformat_minor']

if from_version == 3:
Expand Down
10 changes: 10 additions & 0 deletions nbformat/v4/tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from nbformat import validate
from .. import convert
from ..nbjson import reads
import pytest
from nbformat import ValidationError

from . import nbexamples
from nbformat.v3.tests import nbexamples as v3examples
Expand Down Expand Up @@ -89,3 +91,11 @@ def test_upgrade_v4_to_4_dot_5():
assert nb_up['nbformat_minor'] == 5
validate(nb_up)
assert nb_up.cells[0]['id'] is not None

def test_upgrade_without_nbminor_version():
here = os.path.dirname(__file__)
with io.open(os.path.join(here, os.pardir, os.pardir, 'tests', "no_min_version.ipynb"), encoding='utf-8') as f:
nb = reads(f.read())

with pytest.raises(ValidationError):
convert.upgrade(nb)

0 comments on commit dee3e4f

Please sign in to comment.