Skip to content

Commit 040f670

Browse files
committed
sync python tests between C and Go
1 parent 8ca3433 commit 040f670

File tree

1 file changed

+21
-13
lines changed

1 file changed

+21
-13
lines changed

python/_jsonnet_test.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,14 @@
1919
import _jsonnet
2020

2121

22-
# Returns content if worked, None if file not found, or throws an exception
23-
def try_path(dir, rel, do_encode):
22+
# Returns (full_path, contents) if the file was successfully retrieved,
23+
# (full_path, None) if file not found, or throws an exception when the path
24+
# is invalid or an IO error occured.
25+
# It caches both hits and misses in the `cache` dict. Exceptions
26+
# do not need to be cached, because they abort the computation anyway.
27+
# if do_encode is True, then the file is returned as bytes
28+
# instead of as a string (this does not make a difference in Python2).
29+
def try_path_cached(cache, dir, rel, do_encode):
2430
if not rel:
2531
raise RuntimeError('Got invalid filename (empty string).')
2632
if rel[0] == '/':
@@ -29,24 +35,27 @@ def try_path(dir, rel, do_encode):
2935
full_path = dir + rel
3036
if full_path[-1] == '/':
3137
raise RuntimeError('Attempted to import a directory')
32-
33-
if not os.path.isfile(full_path):
34-
return full_path, None
35-
with open(full_path) as f:
36-
if do_encode:
37-
return full_path, f.read().encode()
38+
if full_path not in cache:
39+
if not os.path.isfile(full_path):
40+
cache[full_path] = None
3841
else:
39-
return full_path, f.read()
40-
42+
with open(full_path) as f:
43+
if do_encode:
44+
cache[full_path] = f.read().encode()
45+
else:
46+
cache[full_path] = f.read()
47+
return full_path, cache[full_path]
4148

4249
def import_callback_encode(dir, rel):
43-
full_path, content = try_path(dir, rel, do_encode=True)
50+
cache = {}
51+
full_path, content = try_path_cached(cache, dir, rel, do_encode=True)
4452
if content:
4553
return full_path, content
4654
raise RuntimeError('File not found')
4755

4856
def import_callback_no_encode(dir, rel):
49-
full_path, content = try_path(dir, rel, do_encode=False)
57+
cache = {}
58+
full_path, content = try_path_cached(cache, dir, rel, do_encode=False)
5059
if content:
5160
return full_path, content
5261
raise RuntimeError('File not found')
@@ -268,6 +277,5 @@ def test_double_import(self):
268277
)
269278
self.assertEqual(json_str, "84\n")
270279

271-
272280
if __name__ == '__main__':
273281
unittest.main()

0 commit comments

Comments
 (0)