File: formattest.py

package info (click to toggle)
nbformat 5.10.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,072 kB
  • sloc: python: 4,746; makefile: 167; javascript: 2
file content (61 lines) | stat: -rw-r--r-- 1,593 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations

import os
import shutil
import tempfile
from typing import Any, Optional

pjoin = os.path.join

from .nbexamples import nb0


def open_utf8(fname, mode):
    return open(fname, mode=mode, encoding="utf-8")  # noqa


class NBFormatTest:
    """Mixin for writing notebook format tests"""

    # override with appropriate values in subclasses
    nb0_ref: Optional[Any] = None
    ext: Optional[str] = None
    mod: Optional[Any] = None

    def setUp(self):
        self.wd = tempfile.mkdtemp()

    def tearDown(self):
        shutil.rmtree(self.wd)

    def assertNBEquals(self, nba, nbb):
        self.assertEqual(nba, nbb)  # type:ignore[attr-defined]

    def test_writes(self):
        assert self.mod is not None
        s = self.mod.writes(nb0)
        if self.nb0_ref:
            self.assertNBEquals(s, self.nb0_ref)

    def test_reads(self):
        assert self.mod is not None
        s = self.mod.writes(nb0)
        nb = self.mod.reads(s)

    def test_roundtrip(self):
        assert self.mod is not None
        s = self.mod.writes(nb0)
        self.assertNBEquals(self.mod.reads(s), nb0)

    def test_write_file(self):
        assert self.mod is not None
        with open_utf8(pjoin(self.wd, "nb0.%s" % self.ext), "w") as f:
            self.mod.write(nb0, f)

    def test_read_file(self):
        assert self.mod is not None
        with open_utf8(pjoin(self.wd, "nb0.%s" % self.ext), "w") as f:
            self.mod.write(nb0, f)

        with open_utf8(pjoin(self.wd, "nb0.%s" % self.ext), "r") as f:
            nb = self.mod.read(f)