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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
|
#!/usr/bin/env python3
"""Exercise the real terminal editor through a PTY and the same document CLI."""
import argparse
import fcntl
import hashlib
import json
import locale
import os
from pathlib import Path
import pty
import select
import signal
import struct
import subprocess
import tempfile
import termios
import time
HERE = Path(__file__).resolve().parent
def command(*args):
return subprocess.run([str(arg) for arg in args], capture_output=True,
timeout=20, check=True)
def utf8_locale():
original = locale.setlocale(locale.LC_CTYPE)
candidates = [os.environ.get('LC_ALL'), os.environ.get('LC_CTYPE'),
os.environ.get('LANG'), 'C.UTF-8', 'en_US.UTF-8']
try:
for candidate in candidates:
if not candidate:
continue
try:
locale.setlocale(locale.LC_CTYPE, candidate)
except locale.Error:
continue
if locale.nl_langinfo(locale.CODESET).upper().replace('-', '') == 'UTF8':
return candidate
finally:
locale.setlocale(locale.LC_CTYPE, original)
raise AssertionError('no UTF-8 locale available for terminal test')
def memory_kib(pid, field, portable=False):
if portable:
return None
for line in Path(f'/proc/{pid}/status').read_text().splitlines():
if line.startswith(field):
return int(line.split()[1])
raise AssertionError(field)
class Terminal:
def __init__(self, binary, program, store, key):
self.master, self.slave = pty.openpty()
fcntl.ioctl(self.slave, termios.TIOCSWINSZ, struct.pack('HHHH', 24, 80, 0, 0))
self.original = termios.tcgetattr(self.slave)
language = utf8_locale()
self.process = subprocess.Popen([str(binary),
*(['--program', str(program)] if program else []),
'--store', str(store), key],
stdin=self.slave, stdout=self.slave, stderr=self.slave,
env={**os.environ, 'LANG': language,
'LC_ALL': language})
self.wait_for(f'Pure | {key}'.encode())
def wait_for(self, marker, timeout=8):
seen = b''
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
ready, _, _ = select.select([self.master], [], [], 0.1)
if ready:
part = os.read(self.master, 65536)
seen = (seen + part)[-65536:]
if marker in seen:
return seen
if self.process.poll() is not None:
break
raise AssertionError((marker, self.process.poll(), seen[-2000:]))
def type(self, data):
os.write(self.master, data)
def resize(self, rows, columns):
fcntl.ioctl(self.slave, termios.TIOCSWINSZ,
struct.pack('HHHH', rows, columns, 0, 0))
os.kill(self.process.pid, signal.SIGWINCH)
def close(self, discard=False):
if self.process.poll() is None:
self.type(b'\x11')
if discard:
self.wait_for(b'Unsaved draft')
self.type(b'\x11')
self.process.wait(timeout=8)
assert self.process.returncode == 0, self.process.returncode
restored = termios.tcgetattr(self.slave)
assert restored == self.original, (restored, self.original)
os.close(self.master)
os.close(self.slave)
def signal_close(self):
os.kill(self.process.pid, signal.SIGTERM)
self.process.wait(timeout=8)
assert self.process.returncode == 0, self.process.returncode
assert termios.tcgetattr(self.slave) == self.original
os.close(self.master)
os.close(self.slave)
def shown(editor, store, key):
result = command(*editor, '--store', store, 'show', key)
return result.stdout, json.loads(result.stderr)['revision']
def wait_stored(editor, store, key, expected, revision):
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
try:
body, found_revision = shown(editor, store, key)
if body == expected and found_revision == str(revision):
return
except subprocess.CalledProcessError:
pass
time.sleep(0.05)
raise AssertionError((key, expected[:100], shown(editor, store, key)))
def check(build, rss_limit_kib, source, program_path, portable=False, object_files=True):
binary = (build / ('pure-edit-tui' if source else 'pure-edit-tui-fixed')).resolve()
program = (program_path or HERE / 'examples/editor.pure').resolve() if source else None
editor = [str((build / ('pure-edit' if source else 'pure-edit-fixed')).resolve())]
if source:
editor += ['--program', str(program)]
with tempfile.TemporaryDirectory(prefix='pure-tui-') as name:
root = Path(name)
store = root / 'store'
if source:
invalid = root / 'invalid.pure'
invalid.write_text('not a pure program\n')
for candidate, marker in ((invalid, b'Program:'),
(HERE / 'examples/storage.pure', b'Program needs')):
denied = subprocess.run([str(binary), '--program', str(candidate),
'--store', str(store), 'note'],
capture_output=True, timeout=10)
assert denied.returncode == 2 and marker in denied.stderr
assert not store.exists()
terminal = Terminal(binary, program, store, 'note')
try:
terminal.type(b'hello Pure\x1b[D\x1b[D!\x13')
wait_stored(editor, store, 'note', b'hello Pu!re', 1)
if source:
assert command(*editor, '--store', store, 'show', 'note').stdout == b'hello Pu!re'
terminal.type(b'\x0fsecond\r')
terminal.wait_for(b'Pure | second')
terminal.type('안녕'.encode() + b'\x1b[D' + '하'.encode() + b'\x13')
terminal.wait_for('안하녕'.encode())
wait_stored(editor, store, 'second', '안하녕'.encode(), 1)
terminal.resize(32, 100)
terminal.wait_for(b'Pure | second')
terminal.type(b'\x0fnote\r')
terminal.wait_for(b'Pure | note')
terminal.type(b'\x0c')
listing = terminal.wait_for(b'Pure | documents')
assert b'note' in listing and b'second' in listing, listing[-1000:]
terminal.type(b'\x1b[B\r')
terminal.wait_for(b'Pure | second')
terminal.type(b'\x0c\x1b[A\r')
terminal.wait_for(b'Pure | note')
terminal.type(b'\x0c')
terminal.wait_for(b'Pure | documents')
if object_files:
# Only per-object file stores can lose one document underneath the list.
(store / 'obj-second').unlink()
terminal.type(b'\x1b[B\r')
terminal.wait_for(b'Document disappeared; refresh the list')
terminal.type(b'\x1b')
terminal.wait_for(b'Pure | note')
terminal.type(b'!')
terminal.type(b'\x0c')
terminal.wait_for(b'Save or reload the draft before browsing')
external = root / 'external'
external.write_bytes(b' remote')
command(*editor, '--store', store, 'edit', 'note', '1', '11', '0', external)
terminal.type(b'\x13')
terminal.wait_for(b'Version conflict')
assert shown(editor, store, 'note') == (b'hello Pu!re remote', '2')
small_peak = memory_kib(terminal.process.pid, 'VmHWM:', portable)
finally:
terminal.close(discard=True)
multiline = b'first\n\tsecond\nthird'
insert = root / 'multiline-insert'
insert.write_bytes(multiline)
command(*editor, '--store', store, 'edit', 'multiline', '0', '0', '0', insert)
terminal = Terminal(binary, program, store, 'multiline')
try:
terminal.resize(25, 80)
terminal.wait_for(b'third')
terminal.type(b'!\x13')
wait_stored(editor, store, 'multiline', multiline + b'!', 2)
finally:
terminal.close()
terminal = Terminal(binary, program, store, 'multiline')
terminal.resize(25, 80)
terminal.wait_for(b'third!')
terminal.close()
rows = [f'line-{index:02}'.encode() for index in range(60)]
insert.write_bytes(b'\n'.join(rows))
command(*editor, '--store', store, 'edit', 'rows', '0', '0', '0', insert)
terminal = Terminal(binary, program, store, 'rows')
try:
terminal.type(b'\x1b[A' * 3 + b'X\x13')
rows[56] += b'X'
wait_stored(editor, store, 'rows', b'\n'.join(rows), 2)
terminal.wait_for(b'line-56X')
finally:
terminal.close()
large = b'Q' * 1_048_576
insert = root / 'large-insert'
insert.write_bytes(large)
command(*editor, '--store', store, 'edit', 'large', '0', '0', '0', insert)
terminal = Terminal(binary, program, store, 'large')
try:
terminal.type(b'Z')
terminal.wait_for(b'Z')
terminal.type(b'\x13')
wait_stored(editor, store, 'large', large + b'Z', 2)
large_peak = memory_kib(terminal.process.pid, 'VmHWM:', portable)
finally:
terminal.close()
if rss_limit_kib:
assert large_peak <= rss_limit_kib, (large_peak, rss_limit_kib)
unicode_body = '안녕'.encode() * 174_762
insert.write_bytes(unicode_body)
command(*editor, '--store', store, 'edit', 'unicode', '0', '0', '0', insert)
terminal = Terminal(binary, program, store, 'unicode')
try:
terminal.type(b'K')
terminal.wait_for(b'K')
terminal.type(b'\x1b[HX')
terminal.wait_for(b'X' + '안녕'.encode())
terminal.type(b'\x13')
wait_stored(editor, store, 'unicode', b'X' + unicode_body + b'K', 2)
finally:
terminal.close()
listed = root / 'listed-store'
insert.write_bytes(b'X')
for index in range(1024):
command(*editor, '--store', listed, 'edit', f'doc{index:04}', '0', '0', '0', insert)
terminal = Terminal(binary, program, listed, 'doc0000')
try:
terminal.type(b'\x0c')
terminal.wait_for(b'Pure | documents | 1024 keys')
terminal.resize(8, 12)
terminal.wait_for(b'\033[8;1H')
terminal.resize(24, 80)
terminal.wait_for(b'Pure | documents | 1024 keys')
terminal.type(b'\x1b[F\r')
terminal.wait_for(b'Pure | doc1023')
assert shown(editor, listed, 'doc1023') == (b'X', '1')
terminal.type(b'\x0c')
terminal.wait_for(b'Pure | documents | 1024 keys')
terminal.type(b'doc0919')
terminal.wait_for(b'Find: doc0919_')
terminal.type(b'\r')
terminal.wait_for(b'Pure | doc0919')
assert shown(editor, listed, 'doc0919') == (b'X', '1')
terminal.type(b'\x0czz')
terminal.wait_for(b'No matching key')
terminal.type(b'\r')
terminal.wait_for(b'No matching key')
terminal.type(b'\x7f\x7fdoc1023\r')
terminal.wait_for(b'Pure | doc1023')
list_peak = memory_kib(terminal.process.pid, 'VmHWM:', portable)
finally:
terminal.close()
if rss_limit_kib:
assert list_peak <= rss_limit_kib, (list_peak, rss_limit_kib)
if source:
alternate = root / 'alternate.pure'
definition = program.read_text()
fields = ' start: u32le;\n remove: u32le;'
assert fields in definition
alternate.write_text(definition.replace(fields,
' remove: u32le;\n start: u32le;'))
alternate_store = root / 'alternate-store'
terminal = Terminal(binary, alternate, alternate_store, 'different_layout')
try:
terminal.type(b'abcdef\x13')
wait_stored(editor, alternate_store, 'different_layout', b'abcdef', 1)
terminal.type(b'\x1b[D\x1b[D\x1b[D!\x13')
wait_stored(editor, alternate_store, 'different_layout', b'abc!def', 2)
finally:
terminal.close()
terminal = Terminal(binary, program, store, 'note')
terminal.signal_close()
return {'profile': 'native-source-document-terminal-editor' if source else
'native-fixed-document-terminal-editor',
'checks': (['source parse and incompatible definitions fail before store creation',
'source CLI and TUI read the same document',
'changed source field layout drives TUI input encoding'] if source else []) +
['cursor insertion and save through terminal', 'open another key',
'bounded document browser selects keys and protects unsaved draft',
'UTF-8 codepoint movement, visible redraw and edit', 'resize redraw',
'external revision conflict preserves draft',
'stored multiline and tabbed document survives edit and reopen',
'cached viewport preserves vertical movement across many rows',
'one MiB document viewport, edit and fresh CLI restore',
'one MiB UTF-8 viewport and edit before cached anchor',
'1,024 real documents listed, searched, resized and opened' +
(' within RSS gate' if not portable else ''),
'terminal mode restored after key and signal exit'],
'small_peak_rss_kib': small_peak,
'one_mib_peak_rss_kib': large_peak,
'one_thousand_key_list_peak_rss_kib': list_peak,
'one_mib_peak_rss_limit_kib': rss_limit_kib,
'portable': portable,
'terminal_locale': utf8_locale(),
'binary_sha256': hashlib.sha256(binary.read_bytes()).hexdigest()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--build', type=Path, default=HERE / 'build')
parser.add_argument('--rss-limit-kib', type=int, default=4096,
help='0 skips the release RSS gate for sanitizer builds')
parser.add_argument('--source', action='store_true', help='check the source-loaded TUI')
parser.add_argument('--portable', action='store_true',
help='run all PTY behavior without Linux /proc RSS measurement')
parser.add_argument('--program', type=Path, help='definition for --source (including relocated bundles)')
parser.add_argument('--single-file-store', action='store_true',
help='store keeps all documents in one file (skips external deletion)')
parser.add_argument('--output', type=Path)
args = parser.parse_args()
if args.output and args.output.exists():
parser.error('evidence file already exists')
result = check(args.build, 0 if args.portable else args.rss_limit_kib,
args.source, args.program, args.portable, not args.single_file_store)
body = json.dumps(result, indent=2) + '\n'
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(body)
print(body, end='')
if __name__ == '__main__':
main()
|