"""Smoke test for the FORTRAN 704 Jupyter kernel. Builds no Jupyter server. The kernel class is driven directly. """ import os import fcntl import resource import select import shlex import sys import tempfile import subprocess import time from pathlib import Path from unittest.mock import patch os.environ['FORTRAN704'] = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'fortran704')) def write_probe(path, source): path = Path(path) path.write_text('#!/bin/sh\nexec ' + shlex.quote(sys.executable) + ' -c ' + shlex.quote(source) + ' "$@"\n') path.chmod(0o700) def test_cards(): from .kernel import statement_fields, program_has_end, needs_stdin, split_cell assert list(statement_fields([' END'])) == ['END'] assert not program_has_end(['END']) assert list(statement_fields(['C A COMMENT'])) == [] assert program_has_end([' END FILE 1', ' END']) assert not program_has_end([' END FILE 1']) assert needs_stdin([' READ 1, N']) assert not needs_stdin([' READ TAPE 1, N']) assert program_has_end([' E N D']) assert needs_stdin([' R E A D 1,N']) assert not needs_stdin([' R E A D T A P E 1,N']) assert not needs_stdin([' R E A D I N P U T T A P E 1,2,N']) assert needs_stdin([' READ INPUT']) assert needs_stdin([' R E', ' 1AD 1,I']) assert needs_stdin([' I=1', ' 10', ' 1READ 1,I']) assert program_has_end([' E', ' 1ND']) assert not needs_stdin([' READ=1', ' READ((I+1))=2']) assert needs_stdin([' READ 1,(A(I),I=1,3)']) magics, source, deck = split_cell( '%std 0\n%deck\n4\n%enddeck\n PRINT N\n END\n') assert magics == ['%std 0'] assert deck == ['4'] assert source[-1].strip() == 'END' assert split_cell(' I=1\v I=2\n')[1] == [' I=1\v I=2'] assert split_cell(' END\r\n')[1] == [' END'] print(' PASS cards') def test_kernel(): from .kernel import Fortran704Kernel, OUTPUT_LIMIT class MockKernel(Fortran704Kernel): execution_count = 1 iopub_socket = None def __init__(self): self._init_session() self._captured = [] def send_response(self, socket, msg_type, content): self._captured.append((msg_type, content)) k = MockKernel() def run(code, allow_stdin=False): k._captured = [] result = k.do_execute(code, silent=False, allow_stdin=allow_stdin) out = '' err = '' for msg_type, content in k._captured: if msg_type != 'stream': continue if content.get('name') == 'stderr': err += content.get('text', '') else: out += content.get('text', '') return result, out, err hello = ( ' PRINT 1\n' ' 1 FORMAT(13H HELLO, WORLD)\n' ' STOP\n' ' END\n' ) result, out, err = run(hello) assert result['status'] == 'ok', result assert 'HELLO, WORLD' in out, out assert 'STOP' in err, err print(' PASS hello') result, out, err = run(' K = 0\n DO 12 J = 1, 4\n 12 K = K + J\n') assert result['status'] == 'ok', result assert 'STOP' not in err assert 'Appended 3 cards' in out print(' PASS append') result, out, err = run('%list') assert 'DO 12 J' in out, out print(' PASS list') result, out, err = run( ' PRINT 1, K\n' ' 1 FORMAT(1H ,I5)\n' ' STOP\n' '%run\n' ) assert result['status'] == 'ok', (result, err) assert '10' in out, out print(' PASS run deck') result, out, err = run('%std 0') assert 'FORTRAN 0' in out, out result, out, err = run(' CALL FOO\n END\n') assert result['status'] == 'error', result assert 'not in FORTRAN 0' in err, err print(' PASS std 0') result, out, err = run('%reset\n' + hello) assert result['status'] == 'ok', (result, err) assert 'HELLO, WORLD' in out print(' PASS reset') result, out, err = run( '%std 0\n' '%deck\n' '4\n' '%enddeck\n' ' READ N\n' ' N = N + 1\n' ' PRINT N\n' ' STOP\n' ' END\n' ) assert result['status'] == 'ok', (result, err) assert out.strip().endswith('5'), out print(' PASS read deck') result, _, err = run('%std 9') assert result['status'] == 'error' assert 'Usage' in err print(' PASS bad std') result, out, err = run('%') assert result['status'] == 'error' and result['ename'] == 'UsageError', result result, out, err = run('%reset\n' + hello) assert result['status'] == 'ok', (result, err) print(' PASS bare magic and recovery') run('%std 2') result, out, err = run('C caf\u00e9\n' + hello) assert result['status'] == 'error' and result['ename'] == 'UnicodeError', (result, err) assert 'ASCII' in err and k._proc is None result, out, err = run(hello) assert result['status'] == 'ok', (result, err) print(' PASS non-ASCII source and recovery') result, out, err = run('%deck\n\u00e9\n%enddeck\n' + hello) assert result['status'] == 'error' and result['ename'] == 'UnicodeError', (result, err) print(' PASS non-ASCII input deck') for blank, expected in [('\t', 'error'), ('\r ', 'error'), (' \n', 'ok'), (' \r\n', 'ok')]: run('%reset') assert k.do_is_complete(blank)['status'] == ('complete' if expected == 'error' else 'incomplete') run(blank) run(' I=1\n STOP\n') result, out, err = run('%run') assert result['status'] == expected, (result, err) if expected == 'error': assert ('tab' if blank == '\t' else 'bad statement number') in err.lower(), err print(' PASS tab-only cells reach native card validation') for card, message in [('\t', 'tab is not'), ('\0', 'NUL is not'), ('\r ', 'bad statement number'), (' 1', 'continuation with no statement')]: run('%reset') run(card) result, out, err = run('%run') assert result['status'] == 'error' and message in err, (result, err) for card in [' ', ' ' * 72 + 'SEQ', 'C COMMENT']: run('%reset') run(card) result, out, err = run('%run') assert result['ename'] == 'UsageError' and 'deck is empty' in err, (result, err) print(' PASS standalone malformed cards reach native validation') guide = (Path(__file__).resolve().parents[1] / 'docs/getting-started.md').read_text() first_cell = guide.split('```fortran\n')[2].split('```', 1)[0] second_cell = guide.split('```text\n', 1)[1].split('```', 1)[0] run('%reset') result, out, err = run(first_cell) assert result['status'] == 'ok', (result, err) result, out, err = run(second_cell) assert result['status'] == 'ok' and out.strip() == '4', (result, out, err) result, out, err = run('%run') assert result['status'] == 'ok' and out.strip() == '4', (result, out, err) run('%new') run(first_cell) result, out, err = run(second_cell) assert result['status'] == 'ok' and out.strip() == '4', (result, out, err) print(' PASS documented two-cell notebook example') with tempfile.TemporaryDirectory() as directory: work = Path(directory) search = work / 'path' search.mkdir() name = 'fortran704-probe' for folder, label in [(work, 'CHECKED'), (search, 'PATH')]: script = folder / name write_probe(script, 'print(' + repr(label) + ')\n') previous_directory = os.getcwd() try: os.chdir(work) for selected in [name, str(work / name)]: with patch.dict(os.environ, {'FORTRAN704': selected, 'PATH': str(search) + os.pathsep + os.environ.get('PATH', '')}): result, out, err = run(hello) assert result['status'] == 'ok' and out == 'CHECKED\n', (result, out, err) finally: os.chdir(previous_directory) print(' PASS executable override launches the checked file') prior = k._timeout for timeout in ['0', '-1', '86401', '9' * 400, 'bad']: result, out, err = run('%timeout ' + timeout) assert result['status'] == 'error' and k._timeout == prior, (result, err) result, out, err = run('%timeout 60') assert result['status'] == 'ok' and k._timeout == 60 print(' PASS timeout validation') executable = os.environ['FORTRAN704'] try: with tempfile.TemporaryDirectory() as directory: invalid = os.path.join(directory, 'invalid-compiler') with open(invalid, 'w') as fh: fh.write('not an executable format\n') os.chmod(invalid, 0o700) os.environ['FORTRAN704'] = invalid result, out, err = run(hello) assert result['status'] == 'error' and result['ename'] == 'OSError', (result, err) assert k._proc is None finally: os.environ['FORTRAN704'] = executable print(' PASS compiler launch error') # A child can remain alive after receiving EOF. Cancellation must stop # further prompts and the timeout must still kill and reap that child. try: with tempfile.TemporaryDirectory() as directory: child = os.path.join(directory, 'wait-after-eof') write_probe(child, 'import sys,time\n' 'sys.stdin.read()\ntime.sleep(10)\n') os.environ['FORTRAN704'] = child spawned, prompts = [], [] popen = subprocess.Popen def record_child(*args, **kwargs): proc = popen(*args, **kwargs) spawned.append(proc) return proc def cancel(prompt): prompts.append(prompt) raise EOFError('cancelled') k._timeout = 1 k.raw_input = cancel with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result = k.do_execute(' READ 1,I\n END\n', silent=False, allow_stdin=True) assert result['status'] == 'error', result assert prompts == ['READ '], prompts assert len(spawned) == 1 and spawned[0].poll() is not None assert k._proc is None spawned = [] def interrupt(prompt): raise KeyboardInterrupt() k.raw_input = interrupt with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result, out, err = run(' READ 1,I\n END\n', allow_stdin=True) assert result['status'] == 'error' and result['ename'] == 'KeyboardInterrupt', result assert len(spawned) == 1 and spawned[0].poll() is not None assert not os.path.exists(spawned[0].args[-1]) and k._proc is None finally: os.environ['FORTRAN704'] = executable print(' PASS cancelled READ reaps child') print(' PASS interrupted READ returns a structured error and reaps child') k._timeout = 5 for failure in [OSError(5, 'input channel failed'), OSError('input channel failed')]: spawned = [] def failed_input(prompt): raise failure k.raw_input = failed_input with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result, out, err = run( ' READ 1,I\n 1 FORMAT(I1)\n STOP\n END\n', allow_stdin=True) assert result['status'] == 'error' and result['ename'] == 'OSError', result assert 'input channel failed' in err and 'STOP' not in err and 'None' not in err, err assert len(spawned) == 1 and spawned[0].poll() is not None assert not os.path.exists(spawned[0].args[-1]) and k._proc is None print(' PASS READ input-channel failure reports an error and reaps child') with tempfile.TemporaryDirectory() as directory: child = Path(directory) / 'read-to-eof' write_probe(child, 'import sys\nsys.stdin.read()\n') real_read, real_write = os.read, os.write for boundary in ['idle', 'eof', 'writable', 'completion']: now, prompts, spawned, writes = [0.0], [], [], [] read_fds, eof_fds = set(), set() class ExpiringPoll: def __init__(self): self.events = {} def register(self, stream, event): self.events[stream.fileno()] = event if event & select.POLLIN: read_fds.add(stream.fileno()) def poll(self, timeout): if boundary in ['eof', 'completion']: spawned[0].stdin.close() spawned[0].wait() now[0] = 0.5 if boundary == 'completion' else 2.0 if boundary == 'idle': return [] return list(self.events.items()) def track_read(fd, size): chunk = real_read(fd, size) if boundary == 'completion' and fd in read_fds and not chunk: eof_fds.add(fd) if len(eof_fds) == 2: now[0] = 2.0 return chunk def track_write(fd, data): writes.append(bytes(data)) return real_write(fd, data) k._timeout = 1 k.raw_input = lambda prompt: prompts.append(prompt) or '1' cards = ' READ 1,I\n 1 FORMAT(I1)\n STOP\n END\n' if boundary == 'writable': cards = '%deck\n7\n%enddeck\n' + cards with patch.dict(os.environ, {'FORTRAN704': str(child)}), \ patch('fortran704kernel.kernel.subprocess.Popen', record_child), \ patch('select.poll', ExpiringPoll), \ patch('fortran704kernel.kernel.time.monotonic', side_effect=lambda: now[0]), \ patch('os.read', side_effect=track_read), patch('os.write', side_effect=track_write): result, out, err = run(cards, allow_stdin=True) assert result['ename'] == 'TimeoutError', (boundary, result) assert not prompts and not writes, (boundary, prompts, writes) assert spawned[0].poll() is not None and k._proc is None assert not os.path.exists(spawned[0].args[-1]) k._timeout = 5 print(' PASS deadlines guard prompts, ready I/O and final completion') prompts = [] def answer(prompt): prompts.append(prompt) return '4' k.raw_input = answer sequence = ' ' * 72 + 'SEQ00001\n' continued = (' 10\n 1R E\n' + sequence + ' %A D INPUT\n PRINT INPUT\n STOP\n E\n' + sequence + ' 1ND\n') result, out, err = run('%std 0\n' + continued, allow_stdin=True) assert result['status'] == 'ok' and out.strip().endswith('4'), (result, out, err) assert prompts and all(prompt == 'READ ' for prompt in prompts), prompts with tempfile.TemporaryDirectory() as directory: source = os.path.join(directory, 'continued.f') with open(source, 'w') as fh: fh.write(continued) direct = subprocess.run([executable, '--std=0', source], input=b'4\n', capture_output=True, timeout=5) assert direct.returncode == 0 and direct.stdout.strip() == b'4', direct print(' PASS continued READ and END match direct execution') for code in ['C\u2028' + hello, '%deck\n4\u20288\n%enddeck\n' + hello]: result, out, err = run(code) assert result['status'] == 'error' and result['ename'] == 'UnicodeError', result k.raw_input = lambda prompt: '\u00e9' result, out, err = run('%std 0\n' + continued, allow_stdin=True) assert result['status'] == 'error' and result['ename'] == 'UnicodeError', result assert k._proc is None print(' PASS Unicode separators and interactive input') k._timeout = 1 try: with tempfile.TemporaryDirectory() as directory: child = os.path.join(directory, 'closed-pipes') write_probe(child, 'import os,time\n' 'os.close(1)\nos.close(2)\ntime.sleep(10)\n') os.environ['FORTRAN704'] = child spawned = [] k.raw_input = cancel with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result, out, err = run(continued, allow_stdin=True) assert result['status'] == 'error' and result['ename'] == 'TimeoutError', result assert len(spawned) == 1 and spawned[0].poll() is not None assert not os.path.exists(spawned[0].args[-1]) and k._proc is None finally: os.environ['FORTRAN704'] = executable print(' PASS closed-pipe timeout reaps child') # A reply larger than pipe capacity must not block the timeout watchdog. k._timeout = 1 try: with tempfile.TemporaryDirectory() as directory: child = os.path.join(directory, 'unread-input') write_probe(child, 'import time\ntime.sleep(10)\n') os.environ['FORTRAN704'] = child spawned = [] k.raw_input = lambda prompt: '1' * (1024 * 1024) started = time.monotonic() with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result, out, err = run(continued, allow_stdin=True) assert result['status'] == 'error' and result['ename'] == 'TimeoutError', result assert time.monotonic() - started < 5 assert len(spawned) == 1 and spawned[0].poll() is not None assert not os.path.exists(spawned[0].args[-1]) and k._proc is None finally: os.environ['FORTRAN704'] = executable print(' PASS oversized interactive reply respects deadline') try: with tempfile.TemporaryDirectory() as directory: child = os.path.join(directory, 'bounded-output') os.environ['FORTRAN704'] = child assert OUTPUT_LIMIT == 1024 * 1024 limit_message = 'Execution exceeded the 1 MiB per-stream output limit.' for stream in ('stdout', 'stderr'): write_probe(child, 'import sys\n' 'while True:\n sys.%s.buffer.write(b"X" * 8192)\n' % stream) spawned = [] k._timeout = 5 started = time.monotonic() with patch('fortran704kernel.kernel.subprocess.Popen', record_child): result, out, err = run(hello) assert result['status'] == 'error' and result['ename'] == 'OutputLimitError', result assert result['evalue'] == limit_message, result prefix = 'X' * OUTPUT_LIMIT + '\n' assert out == (prefix if stream == 'stdout' else '') assert err == (prefix if stream == 'stderr' else '') + limit_message + '\n' assert time.monotonic() - started < 8 assert spawned[0].poll() is not None and k._proc is None assert not os.path.exists(spawned[0].args[-1]) for size in (OUTPUT_LIMIT, OUTPUT_LIMIT + 1): write_probe(child, 'import sys\nsys.%s.buffer.write(b"Y" * %d)\n' % (stream, size)) result, out, err = run(hello) diagnostic = '' if size == OUTPUT_LIMIT: assert result['status'] == 'ok', result else: assert result['status'] == 'error' and result['ename'] == 'OutputLimitError', result assert result['evalue'] == limit_message, result diagnostic = limit_message + '\n' prefix = 'Y' * OUTPUT_LIMIT + '\n' assert out == (prefix if stream == 'stdout' else '') assert err == (prefix if stream == 'stderr' else '') + diagnostic write_probe(child, 'import time\n' 'print("BEFORE",flush=True)\ntime.sleep(10)\n') k._timeout = 1 result, out, err = run(hello) assert result['ename'] == 'TimeoutError' and out == 'BEFORE\n', (result, out) write_probe(child, 'import sys\n' 'print(len(sys.stdin.buffer.read()))\n') k._timeout = 5 deck = '1' * (1024 * 1024) result, out, err = run('%deck\n' + deck + '\n%enddeck\n' + hello) assert result['status'] == 'ok' and int(out) == len(deck) + 1, (result, out, err) write_probe(child, 'import sys\n' 'print(sys.stdin.buffer.read().hex())\n') for records, expected in [('', b''), ('\n', b'\n'), ('4\n\n', b'4\n\n')]: result, out, err = run('%deck\n' + records + '%enddeck\n' + hello) assert result['status'] == 'ok' and out.strip() == expected.hex(), (result, out, err) finally: os.environ['FORTRAN704'] = executable print(' PASS bounded stdout and stderr with retained timeout output') print(' PASS large batch input closes stdin after delivery') limits = resource.getrlimit(resource.RLIMIT_NOFILE) if limits[1] != resource.RLIM_INFINITY and limits[1] < 1100: print(' SKIP high pipe descriptors: hard descriptor limit below 1100') else: try: if limits[0] != resource.RLIM_INFINITY and limits[0] < 1100: resource.setrlimit(resource.RLIMIT_NOFILE, (min(2048, limits[1]) if limits[1] != resource.RLIM_INFINITY else 2048, limits[1])) high_fds = [] def high_pipes(*args, **kwargs): proc = record_child(*args, **kwargs) for name, mode in [('stdin', 'wb'), ('stdout', 'rb'), ('stderr', 'rb')]: old = getattr(proc, name) fd = fcntl.fcntl(old.fileno(), fcntl.F_DUPFD, 1024) high_fds.append(fd) old.close() setattr(proc, name, os.fdopen(fd, mode, buffering=0)) return proc run('%std 2') with patch('fortran704kernel.kernel.subprocess.Popen', high_pipes): result, out, err = run('%deck\n7\n%enddeck\n' ' READ 1,I\n PRINT 2,I\n' ' 1 FORMAT(I1)\n 2 FORMAT(1H ,I2)\n' ' STOP\n END\n') assert result['status'] == 'ok' and out.strip() == '7', (result, out, err) assert len(high_fds) == 3 and min(high_fds) >= 1024 assert k._proc is None finally: resource.setrlimit(resource.RLIMIT_NOFILE, limits) print(' PASS high pipe descriptors') # An I/O exception still has to reap the launched process and remove its deck. spawned = [] with patch('fortran704kernel.kernel.subprocess.Popen', record_child), \ patch.object(k, '_read_process', side_effect=OSError(5, 'injected I/O error')): result, out, err = run('%std 2\n' + hello) assert result['status'] == 'error' and result['ename'] == 'OSError', result assert spawned[0].poll() is not None and not os.path.exists(spawned[0].args[-1]) assert k._proc is None result, out, err = run(hello) assert result['status'] == 'ok', (result, err) print(' PASS I/O exception cleanup and recovery') saved = os.environ.get('FORTRAN704') os.environ['FORTRAN704'] = '/no/such/fortran704' missing = MockKernel() missing._captured = [] result = missing.do_execute(hello, silent=False) assert result['status'] == 'error' os.environ['FORTRAN704'] = saved print(' PASS missing binary') def main(): binary = os.environ['FORTRAN704'] if not (os.path.isfile(binary) and os.access(binary, os.X_OK)): print('fortran704 is not built at %s' % binary, file=sys.stderr) return 1 test_cards() test_kernel() print('fortran704kernel: passed') return 0 if __name__ == '__main__': sys.exit(main())