tests: move out of the main package.
[nmigen.git] / tests / utils.py
1 import os
2 import re
3 import shutil
4 import subprocess
5 import textwrap
6 import traceback
7 import unittest
8 from contextlib import contextmanager
9
10 from nmigen.hdl.ast import *
11 from nmigen.hdl.ir import *
12 from nmigen.back import rtlil
13 from nmigen._toolchain import require_tool
14
15
16 __all__ = ["FHDLTestCase"]
17
18
19 class FHDLTestCase(unittest.TestCase):
20 def assertRepr(self, obj, repr_str):
21 if isinstance(obj, list):
22 obj = Statement.cast(obj)
23 def prepare_repr(repr_str):
24 repr_str = re.sub(r"\s+", " ", repr_str)
25 repr_str = re.sub(r"\( (?=\()", "(", repr_str)
26 repr_str = re.sub(r"\) (?=\))", ")", repr_str)
27 return repr_str.strip()
28 self.assertEqual(prepare_repr(repr(obj)), prepare_repr(repr_str))
29
30 def assertFormal(self, spec, mode="bmc", depth=1):
31 caller, *_ = traceback.extract_stack(limit=2)
32 spec_root, _ = os.path.splitext(caller.filename)
33 spec_dir = os.path.dirname(spec_root)
34 spec_name = "{}_{}".format(
35 os.path.basename(spec_root).replace("test_", "spec_"),
36 caller.name.replace("test_", "")
37 )
38
39 # The sby -f switch seems not fully functional when sby is reading from stdin.
40 if os.path.exists(os.path.join(spec_dir, spec_name)):
41 shutil.rmtree(os.path.join(spec_dir, spec_name))
42
43 if mode == "hybrid":
44 # A mix of BMC and k-induction, as per personal communication with Clifford Wolf.
45 script = "setattr -unset init w:* a:nmigen.sample_reg %d"
46 mode = "bmc"
47 else:
48 script = ""
49
50 config = textwrap.dedent("""\
51 [options]
52 mode {mode}
53 depth {depth}
54 wait on
55
56 [engines]
57 smtbmc
58
59 [script]
60 read_ilang top.il
61 prep
62 {script}
63
64 [file top.il]
65 {rtlil}
66 """).format(
67 mode=mode,
68 depth=depth,
69 script=script,
70 rtlil=rtlil.convert(Fragment.get(spec, platform="formal"))
71 )
72 with subprocess.Popen([require_tool("sby"), "-f", "-d", spec_name], cwd=spec_dir,
73 universal_newlines=True,
74 stdin=subprocess.PIPE, stdout=subprocess.PIPE) as proc:
75 stdout, stderr = proc.communicate(config)
76 if proc.returncode != 0:
77 self.fail("Formal verification failed:\n" + stdout)