Skip to content

Commit cf80577

Browse files
committed
Use pathlib in test code.
1 parent dbf085f commit cf80577

30 files changed

+200
-185
lines changed

examples/wasm/primes.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
"""
2-
Example that compiles Python code to WASM, then WASM to PPCI-IR, then to native,
3-
and run in-process.
2+
Example that compiles Python code to WASM, then WASM to PPCI-IR,
3+
then to native, and run in-process.
44
"""
55

6-
import os
76
import logging
87
from io import StringIO
8+
from pathlib import Path
99
from time import perf_counter
1010

1111
from ppci import irutils
12-
from ppci.api import ir_to_object, get_current_arch
12+
from ppci.api import get_current_arch, ir_to_object
13+
from ppci.lang.python import ir_to_python, python_to_wasm
1314
from ppci.utils import codepage, reporting
14-
15-
from ppci.wasm import wasm_to_ir, export_wasm_example
16-
from ppci.lang.python import python_to_wasm, ir_to_python
15+
from ppci.wasm import export_wasm_example, wasm_to_ir
1716

1817
logging.basicConfig(level=logging.DEBUG)
1918

2019

2120
# Example Python code
22-
# A bit silly; they are assumed to be "main functions" so they can return a value
21+
# A bit silly; they are assumed to be "main functions"
22+
# so they can return a value
2323

2424
py1 = """
2525
return 42
@@ -46,7 +46,7 @@
4646
4747
while n < max:
4848
i = i + 1
49-
49+
5050
if i <= 1:
5151
continue # nope
5252
elif i == 2:
@@ -80,9 +80,9 @@
8080
# Optimizer fails, or makes it slower ;)
8181
# optimize(ppci_module, 2)
8282

83-
this_dir = os.path.dirname(os.path.abspath(__file__))
83+
this_dir = Path(__file__).resolve().parent
8484
# Generate a report:
85-
html_report = os.path.join(this_dir, "compilation_report.html")
85+
html_report = this_dir / "compilation_report.html"
8686
with reporting.html_reporter(html_report) as reporter:
8787
# Write IR code
8888
f = StringIO()
@@ -104,9 +104,7 @@
104104
print(f"native says {result} in {etime} s")
105105

106106
# Generate html page:
107-
export_wasm_example(
108-
os.path.join(this_dir, "prime_demo_page.html"), py3, wasm_module
109-
)
107+
export_wasm_example(this_dir / "prime_demo_page.html", py3, wasm_module)
110108

111109
# Convert PPCI IR to (ugly) Python to skip codegen
112110
if True:

ppci/common.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"""
66

77
import logging
8+
from pathlib import Path
89
from .lang.common import SourceLocation
910

1011

@@ -34,6 +35,8 @@ def get_file(f, mode="r"):
3435
if hasattr(f, "read"):
3536
# Assume this is a file like object
3637
return f
38+
elif isinstance(f, Path):
39+
return f.open(mode)
3740
elif isinstance(f, str):
3841
return open(f, mode)
3942
else:

ppci/wasm/util.py

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import re
1010
import tempfile
1111
import struct
12+
from pathlib import Path
1213
import subprocess
1314
import keyword
1415
from contextlib import suppress
@@ -23,7 +24,7 @@
2324
"has_node",
2425
]
2526

26-
27+
this_dir = Path(__file__).resolve().parent
2728
PAGE_SIZE = 64 * 1024 # 64 KiB
2829
hex_prog = re.compile(r"-?0x[0-9a-fA-F]+")
2930
hex_float_prog = re.compile(r"[-+]?0x[0-9a-fA-F]+")
@@ -79,6 +80,11 @@ def make_float(s):
7980
raise NotImplementedError(str(s))
8081

8182

83+
def read_template(name):
84+
path = this_dir / name
85+
return path.read_text()
86+
87+
8288
class SlugTable:
8389
"""A translation table which allows simple ascii characters."""
8490

@@ -199,14 +205,8 @@ def export_wasm_example(filename, code, wasm, main_js=""):
199205
fname = os.path.basename(filename).rsplit(".", 1)[0]
200206

201207
# Read templates
202-
src_filename_js = os.path.join(os.path.dirname(__file__), "template.js")
203-
src_filename_html = os.path.join(
204-
os.path.dirname(__file__), "template.html"
205-
)
206-
with open(src_filename_js, "rb") as f:
207-
js = f.read().decode()
208-
with open(src_filename_html, "rb") as f:
209-
html = f.read().decode()
208+
js = read_template("template.js")
209+
html = read_template("template.html")
210210

211211
# Produce HTML
212212
js = js.replace(
@@ -243,9 +243,7 @@ def run_wasm_in_notebook(wasm):
243243
wasm_text = str(list(wasm)) # [0, 1, 12, ...]
244244

245245
# Read templates
246-
src_filename_js = os.path.join(os.path.dirname(__file__), "template.js")
247-
with open(src_filename_js, "rb") as f:
248-
js = f.read().decode()
246+
js = read_template("template.js")
249247

250248
# Get id
251249
global _nb_output
@@ -297,9 +295,7 @@ def run_wasm_in_node(wasm, silent=False):
297295
wasm_text = str(list(wasm)) # [0, 1, 12, ...]
298296

299297
# Read templates
300-
src_filename_js = os.path.join(os.path.dirname(__file__), "template.js")
301-
with open(src_filename_js, "rb") as f:
302-
js = f.read().decode()
298+
js = read_template("template.js")
303299

304300
# Produce JS
305301
js = js.replace("MAIN_JS_PLACEHOLDER", "")

test/helper_util.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# Store testdir for safe switch back to directory:
1515
testdir = os.path.dirname(os.path.abspath(__file__))
1616
test_path = Path(testdir)
17+
examples_path = test_path.parent / "examples"
1718
logger = logging.getLogger("util")
1819

1920

@@ -84,13 +85,15 @@ def has_qemu():
8485
return False
8586

8687

87-
def run_qemu(kernel, machine="lm3s811evb", dump_file=None, dump_range=None):
88+
def run_qemu(
89+
kernel: Path, machine="lm3s811evb", dump_file=None, dump_range=None
90+
):
8891
"""Runs qemu on a given kernel file"""
8992

9093
if not has_qemu():
9194
return ""
9295
# Check bin file exists:
93-
assert os.path.isfile(kernel)
96+
assert kernel.is_file()
9497

9598
logger.debug("Running qemu with machine=%s and image %s", machine, kernel)
9699

@@ -107,7 +110,7 @@ def run_qemu(kernel, machine="lm3s811evb", dump_file=None, dump_range=None):
107110
return qemu(args)
108111

109112

110-
def create_qemu_launch_script(filename, qemu_cmd):
113+
def create_qemu_launch_script(filename: Path, qemu_cmd):
111114
"""Create a shell script for a qemu command.
112115
113116
This can be used to launch qemu manually for a specific test example.
@@ -129,7 +132,7 @@ def create_qemu_launch_script(filename, qemu_cmd):
129132
if "-nographic" in qemu_cmd:
130133
qemu_cmd.remove("-nographic")
131134

132-
with open(filename, "w") as f:
135+
with filename.open("w") as f:
133136
print("#!/bin/bash", file=f)
134137
print("", file=f)
135138
print("# *** automatically generated QEMU launch file! ***", file=f)
@@ -141,8 +144,8 @@ def create_qemu_launch_script(filename, qemu_cmd):
141144
# chmod +x:
142145
import stat
143146

144-
st = os.stat(filename)
145-
os.chmod(filename, st.st_mode | stat.S_IEXEC)
147+
st = filename.stat()
148+
filename.chmod(st.st_mode | stat.S_IEXEC)
146149

147150

148151
def qemu(args):
@@ -264,22 +267,20 @@ def has_iverilog():
264267
return hasattr(shutil, "which") and bool(shutil.which(iverilog_app))
265268

266269

267-
def run_msp430(pmem):
270+
def run_msp430(pmem: Path):
268271
"""Run the given memory file in the openmsp430 iverilog project."""
269272

270273
# Make a run file with the same name as the mem file:
271-
simv = pmem[:-4] + ".run"
274+
simv = pmem.with_suffix(".run")
272275

273-
if not os.path.exists(simv):
276+
if not simv.exists():
274277
print()
275278
print("======")
276279
print("Compiling verilog!")
277280
print("======")
278281

279282
# compile msp430 bench for this pmem:
280-
workdir = relpath(
281-
"..", "examples", "msp430", "test_system", "iverilog"
282-
)
283+
workdir = examples_path / "msp430" / "test_system" / "iverilog"
283284
cmd = [
284285
"iverilog",
285286
"-o",
@@ -313,20 +314,20 @@ def run_msp430(pmem):
313314
return data
314315

315316

316-
def run_picorv32(pmem):
317+
def run_picorv32(pmem: Path):
317318
"""Run the given memory file in the riscvpicorv32 iverilog project."""
318319

319320
# Make a run file with the same name as the mem file:
320-
simv = pmem[:-4] + ".run"
321+
simv = pmem.with_suffix(".run")
321322

322-
if not os.path.exists(simv):
323+
if not simv.exists():
323324
print()
324325
print("======")
325326
print("Compiling verilog!")
326327
print("======")
327328

328329
# compile picorv32 bench for this pmem:
329-
workdir = relpath("..", "examples", "riscvpicorv32", "iverilog")
330+
workdir = examples_path / "riscvpicorv32" / "iverilog"
330331
cmd = [
331332
"iverilog",
332333
"-o",
@@ -353,11 +354,11 @@ def run_picorv32(pmem):
353354
return outs
354355

355356

356-
avr_emu1 = relpath("..", "examples", "avr", "emu", "build", "emu1")
357+
avr_emu1 = examples_path / "avr" / "emu" / "build" / "emu1"
357358

358359

359360
def has_avr_emulator():
360-
return os.path.exists(avr_emu1)
361+
return avr_emu1.exists()
361362

362363

363364
def run_avr(hexfile):

test/run_profiler.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
1-
from cProfile import Profile
2-
import pstats
31
import logging
42
import logging.handlers
5-
import shutil
63
import os
7-
4+
import pstats
5+
import shutil
6+
from cProfile import Profile
87

98
if __name__ == "__main__":
109
logging.getLogger().setLevel(logging.DEBUG)

test/samples/sample_helpers.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
from ppci.lang.c import COptions
77
from ppci.utils.reporting import html_reporter
88

9-
from ..helper_util import relpath, source_files, test_path
9+
from ..helper_util import source_files, test_path
10+
11+
librt_path = test_path.parent / "librt"
1012

1113

1214
def create_test_function(source: Path, output: Path, lang: str):
@@ -45,7 +47,7 @@ def build_sample_to_ir(src, lang, bsp_c3, march, reporter):
4547
if lang == "c3":
4648
ir_modules = [
4749
api.c3_to_ir(
48-
[bsp_c3, relpath("..", "librt", "io.c3"), io.StringIO(src)],
50+
[bsp_c3, librt_path / "io.c3", io.StringIO(src)],
4951
[],
5052
march,
5153
reporter=reporter,
@@ -55,11 +57,11 @@ def build_sample_to_ir(src, lang, bsp_c3, march, reporter):
5557
ir_modules = [api.bf_to_ir(src, march)]
5658
elif lang == "c":
5759
coptions = COptions()
58-
libc_path = relpath("..", "librt", "libc")
60+
libc_path = librt_path / "libc"
5961
include_path1 = os.path.join(libc_path, "include")
60-
lib = relpath("..", "librt", "libc", "lib.c")
62+
lib = libc_path / "lib.c"
6163
coptions.add_include_path(include_path1)
62-
with open(lib) as f:
64+
with lib.open() as f:
6365
mod1 = api.c_to_ir(f, march, coptions=coptions, reporter=reporter)
6466
mod2 = api.c_to_ir(
6567
io.StringIO(src), march, coptions=coptions, reporter=reporter
@@ -78,7 +80,7 @@ def build_sample_to_ir(src, lang, bsp_c3, march, reporter):
7880
def build_sample_to_code(src, lang, bsp_c3, opt_level, march, debug, reporter):
7981
"""Turn example sample into code objects."""
8082
if lang == "c3":
81-
srcs = [relpath("..", "librt", "io.c3"), bsp_c3, io.StringIO(src)]
83+
srcs = [librt_path / "io.c3", bsp_c3, io.StringIO(src)]
8284
o2 = api.c3c(
8385
srcs,
8486
[],
@@ -95,10 +97,10 @@ def build_sample_to_code(src, lang, bsp_c3, opt_level, march, debug, reporter):
9597
elif lang == "c":
9698
o2 = api.c3c([bsp_c3], [], march, reporter=reporter)
9799
coptions = COptions()
98-
libc_path = relpath("..", "librt", "libc")
100+
libc_path = librt_path / "libc"
99101
include_path1 = os.path.join(libc_path, "include")
100102
coptions.add_include_path(include_path1)
101-
with open(relpath("..", "librt", "libc", "lib.c")) as f:
103+
with open(libc_path / "lib.c") as f:
102104
o3 = api.cc(
103105
f, march, coptions=coptions, debug=debug, reporter=reporter
104106
)

test/samples/test_samples_on_arm.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import io
22
import unittest
33

4-
from ..helper_util import do_long_tests, has_qemu, make_filename, qemu, relpath
4+
from ..helper_util import (
5+
do_long_tests,
6+
has_qemu,
7+
make_filename,
8+
qemu,
9+
examples_path,
10+
)
511
from .sample_helpers import add_samples, build
612

713

@@ -52,7 +58,7 @@ class TestSamplesOnVexpress(unittest.TestCase):
5258

5359
def do(self, src, expected_output, lang="c3"):
5460
# Construct binary file from snippet:
55-
bsp_c3 = relpath("..", "examples", "realview-pb-a8", "arch.c3")
61+
bsp_c3 = examples_path / "realview-pb-a8" / "arch.c3"
5662
startercode = io.StringIO(self.startercode)
5763
base_filename = make_filename(self.id())
5864
build(
@@ -149,7 +155,7 @@ class TestSamplesOnCortexM3O2(unittest.TestCase):
149155

150156
def do(self, src, expected_output, lang="c3"):
151157
# Construct binary file from snippet:
152-
bsp_c3 = relpath("..", "examples", "lm3s6965evb", "bare", "arch.c3")
158+
bsp_c3 = examples_path / "lm3s6965evb" / "bare" / "arch.c3"
153159
startercode = io.StringIO(self.startercode)
154160
base_filename = make_filename(self.id())
155161
build(

test/samples/test_samples_on_avr.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
do_long_tests,
66
has_avr_emulator,
77
make_filename,
8-
relpath,
98
run_avr,
9+
examples_path,
1010
)
1111
from .sample_helpers import add_samples, build
1212

@@ -19,9 +19,9 @@ class TestSamplesOnAvr(unittest.TestCase):
1919

2020
def do(self, src, expected_output, lang="c3"):
2121
base_filename = make_filename(self.id())
22-
bsp_c3 = relpath("..", "examples", "avr", "bsp.c3")
23-
crt0 = relpath("..", "examples", "avr", "glue.asm")
24-
mmap = relpath("..", "examples", "avr", "avr.mmap")
22+
bsp_c3 = examples_path / "avr" / "bsp.c3"
23+
crt0 = examples_path / "avr" / "glue.asm"
24+
mmap = examples_path / "avr" / "avr.mmap"
2525
build(
2626
base_filename,
2727
src,

0 commit comments

Comments
 (0)