-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest.py
More file actions
268 lines (220 loc) · 9.66 KB
/
test.py
File metadata and controls
268 lines (220 loc) · 9.66 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
from __future__ import annotations
import os
import sys
import traceback
from collections.abc import Callable
from io import BufferedReader
from typing import (
Any,
cast,
)
import ext4
FAILED = False
def test_path_tuple(path: str | bytes, expected: tuple[bytes, ...]) -> None:
global FAILED # noqa: PLW0603
print(f"check Volume.path_tuple({path}): ", end="")
try:
t = ext4.Volume.path_tuple(path)
if t != expected:
raise ValueError(f"Result is unexpected {t}")
print("pass")
except Exception as e:
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
print(" ", end="", file=sys.stderr)
print(e, file=sys.stderr)
def _eval_or_False(source: str) -> Any: # pyright: ignore[reportExplicitAny, reportAny] # noqa: ANN401
try:
return eval(source) # pyright: ignore[reportAny] # noqa: S307
except Exception:
traceback.print_exc()
return False
def _assert(source: str, debug: Callable[[], Any] | None = None) -> None: # pyright: ignore[reportExplicitAny]
global FAILED # noqa: PLW0603
print(f"check {source}: ", end="")
if _eval_or_False(source):
print("pass")
return
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
if debug is not None:
print(f" {debug()}", file=sys.stderr)
def _not_raises(source: str, debug: Callable[[], Any] | None = None) -> None: # pyright: ignore[reportExplicitAny]
global FAILED # noqa: PLW0603
print(f"check {source} does not raise exception: ", end="")
try:
_ = eval(source) # noqa: S307 # pyright: ignore[reportAny]
print("pass")
except Exception:
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
if debug is not None:
print(f" {debug()}", file=sys.stderr)
def test_magic_error(f: BufferedReader) -> None:
global FAILED # noqa: PLW0603
try:
print("check MagicError: ", end="")
_ = ext4.Volume(f, offset=0)
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
print(" MagicError not raised")
except ext4.struct.MagicError:
print("pass")
except Exception as e:
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
print(" ", end="", file=sys.stderr)
print(e, file=sys.stderr)
def test_root_inode(volume: ext4.Volume) -> None:
global FAILED # noqa: PLW0603
try:
print("Validate root inode: ", end="")
volume.root.validate()
print("pass")
except ext4.struct.ChecksumError as e:
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
print(" ", end="", file=sys.stderr)
print(e, file=sys.stderr)
print("check ext4.Volume stream validation: ", end="")
try:
_ = ext4.Volume(1) # pyright: ignore[reportArgumentType]
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
except ext4.InvalidStreamException:
print("pass")
except Exception as e:
FAILED = True # pyright: ignore[reportConstantRedefinition]
print("fail")
print(" ", end="", file=sys.stderr)
print(e, file=sys.stderr)
test_path_tuple("/", tuple())
test_path_tuple(b"/", tuple())
test_path_tuple("/test", (b"test",))
test_path_tuple(b"/test", (b"test",))
test_path_tuple("/test/test", (b"test", b"test"))
test_path_tuple(b"/test/test", (b"test", b"test"))
for img_file in ("test32.ext4", "test64.ext4"):
print(f"Testing image: {img_file}")
offset = os.path.getsize(img_file) - os.path.getsize(f"{img_file}.tmp")
_assert("offset > 0", lambda: offset)
if offset < 0:
continue
with open(img_file, "rb") as f:
test_magic_error(f)
volume = None
try:
volume = ext4.Volume(f, offset=offset)
except Exception:
FAILED = True # pyright: ignore[reportConstantRedefinition]
traceback.print_exc()
continue
_assert("volume.superblock is not None")
_assert("volume.bad_blocks is not None")
_assert("volume.boot_loader is not None")
_assert("volume.journal is not None")
test_root_inode(volume)
_assert('volume.root.inode_at("test.txt") == volume.inode_at("/test.txt")')
_assert('volume.root.inode_at("/test.txt") == volume.inode_at("/test.txt")')
inode = cast(ext4.File, volume.inode_at("/test.txt"))
_assert("isinstance(inode, ext4.File)")
b = inode.open()
_assert("isinstance(b, ext4.BlockIO)")
_assert("b.readable()")
_assert("not b.peek(0)")
size = volume.block_size + 1
_assert(f"len(b.peek({size})) == {size}")
_assert("b.seekable()")
_assert("b.seek(1) == 1")
_assert("b.seek(0) == 0")
_assert("b.seek(10) == 10")
for i in range(1, 101):
inode = volume.inode_at(f"/test{i}.txt")
attrs = {k: v for k, v in inode.xattrs}
for j in range(1, 21):
_assert(f'attrs["user.name{j}"] == b"value{i}_{j}"')
data = inode.open().read()
_assert(f'data == b"hello world{i}\\n"')
inode = cast(ext4.File, volume.inode_at("/test1.txt"))
b = inode.open()
data = b"hello world1\n"
for x in range(1, 15):
_ = b.seek(0)
_assert(f"b.read({x}) == {data[:x]}", lambda: b.seek(0) == 0 and b.read(x))
inode = cast(ext4.SymbolicLink, volume.inode_at("/symlink.txt"))
_assert("isinstance(inode, ext4.SymbolicLink)")
_assert('inode.readlink() == b"test.txt"', inode.readlink)
img_file = "test_htree.ext4"
print(f"Testing image: {img_file}")
with open(img_file, "rb") as f:
volume = None
try:
volume = ext4.Volume(f)
except Exception:
FAILED = True # pyright: ignore[reportConstantRedefinition]
traceback.print_exc()
if volume is not None:
_assert("volume.superblock is not None")
_assert("volume.bad_blocks is not None")
_assert("volume.boot_loader is not None")
_assert("volume.journal is not None")
test_root_inode(volume)
_assert("volume.root.is_htree == True")
_assert("volume.root.htree is not None")
htree = volume.root.htree
_assert("htree is not None")
if htree is not None:
_assert(
"isinstance(htree.dot, ext4.DotDirectoryEntry2)",
lambda: htree.dot, # pyright: ignore[reportOptionalMemberAccess, reportAny]
)
_assert(
"isinstance(htree.dotdot, ext4.DotDirectoryEntry2)",
lambda: htree.dotdot, # pyright: ignore[reportOptionalMemberAccess, reportAny]
)
_assert("htree.limit > 0", lambda: htree.limit) # pyright: ignore[reportOptionalMemberAccess, reportAny]
_assert("htree.count > 0", lambda: htree.count) # pyright: ignore[reportOptionalMemberAccess, reportAny]
_assert("htree.count <= htree.limit")
_assert("htree.block >= 0", lambda: htree.block) # pyright: ignore[reportOptionalMemberAccess, reportAny]
_assert("htree.dx_root_info is not None")
_assert("htree.dot.verify() is None")
_assert("htree.dotdot.verify() is None")
_assert("htree.dot.name == b'.'", lambda: htree.dot.name) # pyright: ignore[reportAny, reportOptionalMemberAccess]
_assert("htree.dotdot.name == b'..'", lambda: htree.dotdot.name) # pyright: ignore[reportAny, reportOptionalMemberAccess]
dx_root_info = htree.dx_root_info # pyright: ignore[reportAny]
_assert(
"isinstance(dx_root_info.hash_version, int)",
lambda: dx_root_info.hash_version, # pyright: ignore[reportAny]
)
_not_raises(
"ext4.DX_HASH(dx_root_info.hash_version)",
lambda: dx_root_info.hash_version, # pyright: ignore[reportAny]
)
_assert("dx_root_info.info_length == 8", lambda: dx_root_info.info_length) # pyright: ignore[reportAny]
_assert(
"dx_root_info.indirect_levels == 0",
lambda: dx_root_info.indirect_levels, # pyright: ignore[reportAny]
)
entries = list(htree.entries)
_assert("len(entries) > 0", lambda: len(entries))
_assert(
"len(entries) == htree.count - 1",
lambda: f"{len(entries)} != {htree.count - 1}", # pyright: ignore[reportAny, reportOptionalMemberAccess]
)
for entry in entries:
_assert("isinstance(entry.hash, int)", lambda: entry.hash) # pyright: ignore[reportAny]
_assert("isinstance(entry.block, int)", lambda: entry.block) # pyright: ignore[reportAny]
if entries:
first_entry = entries[0]
_assert("first_entry.hash >= 0", lambda: first_entry.hash) # pyright: ignore[reportAny]
_assert("first_entry.block > 0", lambda: first_entry.block) # pyright: ignore[reportAny]
block_io = ext4.BlockIO(volume.root)
block = block_io.blocks[first_entry.block] # pyright: ignore[reportAny]
_assert("len(block) > 0", lambda: len(block))
_assert(f"len(block) == {volume.block_size}", lambda: len(block))
dirent = ext4.DirectoryEntry2(volume.root, 0)
_assert("dirent.rec_len > 0", lambda: dirent.rec_len) # pyright: ignore[reportAny]
non_htree_dir = cast(ext4.Directory, volume.inode_at("/empty"))
_assert("not non_htree_dir.is_htree")
if FAILED:
sys.exit(1)