| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
import os |
| 5 |
import sys |
| 6 |
from pathlib import Path |
| 7 |
|
| 8 |
import unittest |
| 9 |
|
| 10 |
from jupyter_client.manager import start_new_kernel |
| 11 |
from jupyter_kernel_test import validate_message, KernelTests |
| 12 |
|
| 13 |
|
| 14 |
without_rich_display = '''\ |
| 15 |
options(jupyter.rich_display = FALSE) |
| 16 |
{} |
| 17 |
options(jupyter.rich_display = TRUE) |
| 18 |
''' |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
TIMEOUT = 15 |
| 23 |
|
| 24 |
|
| 25 |
class IRkernelTests(KernelTests): |
| 26 |
kernel_name = os.environ.get('IR_KERNEL_NAME', 'testir') |
| 27 |
|
| 28 |
language_name = 'R' |
| 29 |
|
| 30 |
def _execute_code(self, code, tests=True, silent=False, store_history=True): |
| 31 |
self.flush_channels() |
| 32 |
|
| 33 |
reply, output_msgs = self.execute_helper(code, silent=silent, store_history=store_history) |
| 34 |
|
| 35 |
self.assertEqual(reply['content']['status'], 'ok', '{0}: {0}'.format(reply['content'].get('ename'), reply['content'].get('evalue'))) |
| 36 |
if tests: |
| 37 |
self.assertGreaterEqual(len(output_msgs), 1) |
| 38 |
|
| 39 |
self.assertEqual(output_msgs[0]['msg_type'], 'display_data') |
| 40 |
return reply, output_msgs |
| 41 |
|
| 42 |
code_hello_world = 'print("hello, world")' |
| 43 |
|
| 44 |
completion_samples = [ |
| 45 |
{'text': 'zi', 'matches': {'zip'}}, |
| 46 |
{'text': 'seq_len(', 'matches': {'length.out = '}}, |
| 47 |
{'text': 'base::transform(', 'matches': {'`_data` = ', '...'}}, |
| 48 |
{'text': 'foo(R_system', 'matches': {'R_system_version'}}, |
| 49 |
{'text': 'version$plat', 'matches': {'version$platform'}}, |
| 50 |
{'text': 'stats4::AIC@def', 'matches': {'stats4::AIC@default'}}, |
| 51 |
{'text': 'stats4::AIC@default@ta', 'matches': {'stats4::AIC@default@target'}}, |
| 52 |
{'text': 'grDevice', 'matches': {'grDevices::'}}, |
| 53 |
{'text': 'base::abbrev', 'matches': {'base::abbreviate'}}, |
| 54 |
{'text': 'base::.rowNamesD', 'matches': {'base::`.rowNamesDF<-`'}}, |
| 55 |
{'text': 'repr:::repr_png.def', 'matches': {'repr:::repr_png.default'}}, |
| 56 |
{'text': 'repr::format2repr$mark', 'matches': {'repr::format2repr$markdown'}}, |
| 57 |
{'text': 'load("test_i', 'matches': {'test_ir.py'}}, |
| 58 |
{'text': 'load("./test_', 'matches': {'./test_utils.r', './test_kernel.r', './test_ir.py'}}, |
| 59 |
{'text': '.Last.v', 'matches': {'.Last.value'}}, |
| 60 |
] |
| 61 |
|
| 62 |
complete_code_samples = ['1', 'print("hello, world")', 'f <- function(x) {\n x*2\n}'] |
| 63 |
|
| 64 |
incomplete_code_samples = ['print("hello', 'f <- function(x) {\n x*2'] |
| 65 |
|
| 66 |
code_display_data = [ |
| 67 |
{'code': '"a"', 'mime': 'text/plain'}, |
| 68 |
{'code': '"a"', 'mime': 'text/html'}, |
| 69 |
{'code': '"a"', 'mime': 'text/latex'}, |
| 70 |
{'code': '1:3', 'mime': 'text/plain'}, |
| 71 |
{'code': '1:3', 'mime': 'text/html'}, |
| 72 |
{'code': '1:3', 'mime': 'text/latex'}, |
| 73 |
{'code': without_rich_display.format('"a"'), 'mime': 'text/plain'}, |
| 74 |
{'code': without_rich_display.format('1:3'), 'mime': 'text/plain'}, |
| 75 |
] |
| 76 |
|
| 77 |
def test_display_vector(self): |
| 78 |
"""display of vectors""" |
| 79 |
code = '1:3' |
| 80 |
reply, output_msgs = self._execute_code(code) |
| 81 |
|
| 82 |
|
| 83 |
data = output_msgs[0]['content']['data'] |
| 84 |
self.assertEqual(len(data), 4, data.keys()) |
| 85 |
self.assertEqual(data['text/plain'], '[1] 1 2 3') |
| 86 |
self.assertIn('text/html', data) |
| 87 |
|
| 88 |
|
| 89 |
self.assertIn('</li>', output_msgs[0]['content']['data']['text/html']) |
| 90 |
self.assertIn('text/latex', output_msgs[0]['content']['data']) |
| 91 |
self.assertIn('text/markdown', output_msgs[0]['content']['data']) |
| 92 |
|
| 93 |
def test_display_vector_only_plaintext(self): |
| 94 |
"""display of plain text vectors""" |
| 95 |
code = without_rich_display.format('1:3') |
| 96 |
reply, output_msgs = self._execute_code(code) |
| 97 |
data = output_msgs[0]['content']['data'] |
| 98 |
self.assertEqual(len(data), 1, data.keys()) |
| 99 |
self.assertEqual(data['text/plain'], '[1] 1 2 3') |
| 100 |
|
| 101 |
def test_irkernel_plots(self): |
| 102 |
"""plotting""" |
| 103 |
code = 'plot(1:3)' |
| 104 |
reply, output_msgs = self._execute_code(code) |
| 105 |
|
| 106 |
|
| 107 |
data = output_msgs[0]['content']['data'] |
| 108 |
self.assertEqual(len(data), 2, data.keys()) |
| 109 |
self.assertEqual(data['text/plain'], 'plot without title') |
| 110 |
self.assertIn('image/png', data) |
| 111 |
|
| 112 |
|
| 113 |
metadata = output_msgs[0]['content']['metadata'] |
| 114 |
self.assertEqual(len(metadata), 1, metadata.keys()) |
| 115 |
self.assertIn('image/png', metadata) |
| 116 |
self.assertEqual(metadata['image/png'], dict(width=420, height=420), metadata['image/png']) |
| 117 |
|
| 118 |
def test_irkernel_plots_only_PNG(self): |
| 119 |
"""plotting PNG""" |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
code = '''\ |
| 126 |
old_options <- options(jupyter.plot_mimetypes = c('image/png')) |
| 127 |
plot(1:3) |
| 128 |
''' |
| 129 |
reply, output_msgs = self._execute_code(code) |
| 130 |
|
| 131 |
|
| 132 |
data = output_msgs[0]['content']['data'] |
| 133 |
self.assertEqual(len(data), 1, data.keys()) |
| 134 |
self.assertIn('image/png', data) |
| 135 |
|
| 136 |
|
| 137 |
metadata = output_msgs[0]['content']['metadata'] |
| 138 |
self.assertEqual(len(metadata), 1, metadata.keys()) |
| 139 |
self.assertIn('image/png', metadata) |
| 140 |
self.assertEqual(metadata['image/png'], dict(width=420, height=420), metadata['image/png']) |
| 141 |
|
| 142 |
|
| 143 |
code = 'options(old_options)' |
| 144 |
reply, output_msgs = self._execute_code(code, tests=False) |
| 145 |
|
| 146 |
def test_irkernel_plots_only_SVG(self): |
| 147 |
|
| 148 |
code = '''\ |
| 149 |
old_options <- options(jupyter.plot_mimetypes = c('image/svg+xml')) |
| 150 |
plot(1:3) |
| 151 |
''' |
| 152 |
reply, output_msgs = self._execute_code(code) |
| 153 |
|
| 154 |
|
| 155 |
data = output_msgs[0]['content']['data'] |
| 156 |
self.assertEqual(len(data), 1, data.keys()) |
| 157 |
self.assertIn('image/svg+xml', data) |
| 158 |
|
| 159 |
|
| 160 |
metadata = output_msgs[0]['content']['metadata'] |
| 161 |
self.assertEqual(len(metadata), 1, metadata.keys()) |
| 162 |
self.assertEqual(len(metadata['image/svg+xml']), 3) |
| 163 |
self.assertEqual(metadata['image/svg+xml'], dict(width=420, height=420, isolated=True), metadata['image/svg+xml']) |
| 164 |
|
| 165 |
|
| 166 |
code = 'options(old_options)' |
| 167 |
reply, output_msgs = self._execute_code(code, tests=False) |
| 168 |
|
| 169 |
def test_irkernel_plots_without_rich_display(self): |
| 170 |
code = '''\ |
| 171 |
options(jupyter.rich_display = FALSE) |
| 172 |
plot(1:3) |
| 173 |
''' |
| 174 |
reply, output_msgs = self._execute_code(code) |
| 175 |
|
| 176 |
|
| 177 |
data = output_msgs[0]['content']['data'] |
| 178 |
self.assertEqual(len(data), 2, data.keys()) |
| 179 |
self.assertEqual(data['text/plain'], 'plot without title') |
| 180 |
self.assertIn('image/png', data) |
| 181 |
|
| 182 |
|
| 183 |
code = 'options(jupyter.rich_display = TRUE)' |
| 184 |
reply, output_msgs = self._execute_code(code, tests=False) |
| 185 |
|
| 186 |
def test_irkernel_df_default_rich_output(self): |
| 187 |
"""data.frame rich representation""" |
| 188 |
code = 'data.frame(x = 1:3)' |
| 189 |
reply, output_msgs = self._execute_code(code) |
| 190 |
|
| 191 |
|
| 192 |
data = output_msgs[0]['content']['data'] |
| 193 |
self.assertEqual(len(data), 4, data.keys()) |
| 194 |
|
| 195 |
def test_irkernel_df_no_rich_output(self): |
| 196 |
"""data.frame plain representation""" |
| 197 |
code = ''' |
| 198 |
options(jupyter.rich_display = FALSE) |
| 199 |
data.frame(x = 1:3) |
| 200 |
options(jupyter.rich_display = TRUE) |
| 201 |
''' |
| 202 |
reply, output_msgs = self._execute_code(code) |
| 203 |
|
| 204 |
|
| 205 |
data = output_msgs[0]['content']['data'] |
| 206 |
self.assertEqual(len(data), 1, data.keys()) |
| 207 |
|
| 208 |
def test_html_isolated(self): |
| 209 |
"""HTML isolation""" |
| 210 |
code = ''' |
| 211 |
repr_html.full_page <- function(obj) sprintf('<html><body>%s</body></html>', obj) |
| 212 |
structure(0, class = 'full_page') |
| 213 |
''' |
| 214 |
reply, output_msgs = self._execute_code(code) |
| 215 |
|
| 216 |
data = output_msgs[0]['content']['data'] |
| 217 |
self.assertEqual(len(data), 2, data.keys()) |
| 218 |
self.assertEqual(data['text/html'], '<html><body>0</body></html>') |
| 219 |
|
| 220 |
metadata = output_msgs[0]['content']['metadata'] |
| 221 |
self.assertEqual(len(metadata), 1, metadata.keys()) |
| 222 |
self.assertEqual(len(metadata['text/html']), 1, metadata['text/html'].keys()) |
| 223 |
self.assertEqual(metadata['text/html']['isolated'], True) |
| 224 |
|
| 225 |
def test_in_kernel_set(self): |
| 226 |
"""jupyter.in_kernel option""" |
| 227 |
reply, output_msgs = self._execute_code('getOption("jupyter.in_kernel")') |
| 228 |
data = output_msgs[0]['content']['data'] |
| 229 |
self.assertGreaterEqual(len(data), 1, data.keys()) |
| 230 |
self.assertEqual(data['text/plain'], '[1] TRUE', data.keys()) |
| 231 |
|
| 232 |
def test_warning_message(self): |
| 233 |
self.flush_channels() |
| 234 |
reply, output_msgs = self.execute_helper('options(warn=1); warning(simpleWarning("wmsg"))') |
| 235 |
self.assertEqual(output_msgs[0]['msg_type'], 'stream') |
| 236 |
self.assertEqual(output_msgs[0]['content']['name'], 'stderr') |
| 237 |
self.assertEqual(output_msgs[0]['content']['text'].strip(), 'Warning message:\n“wmsg”') |
| 238 |
|
| 239 |
self.flush_channels() |
| 240 |
reply, output_msgs = self.execute_helper('options(warn=1); f <- function() warning("wmsg"); f()') |
| 241 |
self.assertEqual(output_msgs[0]['msg_type'], 'stream') |
| 242 |
self.assertEqual(output_msgs[0]['content']['name'], 'stderr') |
| 243 |
self.assertEqual(output_msgs[0]['content']['text'].strip(), 'Warning message in f():\n“wmsg”') |
| 244 |
|
| 245 |
def test_should_increment_history(self): |
| 246 |
"""properly increments execution history""" |
| 247 |
code = 'data.frame(x = 1:3)' |
| 248 |
reply, output_msgs = self._execute_code(code) |
| 249 |
reply2, output_msgs2 = self._execute_code(code) |
| 250 |
execution_count_1 = reply['content']['execution_count'] |
| 251 |
execution_count_2 = reply2['content']['execution_count'] |
| 252 |
self.assertEqual(execution_count_1 + 1, execution_count_2) |
| 253 |
|
| 254 |
def test_should_not_increment_history(self): |
| 255 |
"""Does not increment history if silent is true or store_history is false""" |
| 256 |
code = 'data.frame(x = 1:3)' |
| 257 |
reply, output_msgs = self._execute_code(code, store_history=False) |
| 258 |
reply2, output_msgs2 = self._execute_code(code, store_history=False) |
| 259 |
reply3, output_msgs3 = self._execute_code(code, tests=False, silent=True) |
| 260 |
execution_count_1 = reply['content']['execution_count'] |
| 261 |
execution_count_2 = reply2['content']['execution_count'] |
| 262 |
execution_count_3 = reply3['content']['execution_count'] |
| 263 |
self.assertEqual(execution_count_1, execution_count_2) |
| 264 |
self.assertEqual(execution_count_1, execution_count_3) |
| 265 |
|
| 266 |
irkernel_inspects = [ |
| 267 |
dict(name='Numeric constant', token='1'), |
| 268 |
|
| 269 |
dict(name='Dataset with a help document', token='iris'), |
| 270 |
dict(name='Function with a help document', token='c'), |
| 271 |
dict(name='Function name with namespace', token='base::c'), |
| 272 |
dict(name='Function not exported from namespace', token='tools:::.Rd2pdf'), |
| 273 |
dict(name='User-defined variable', token='x', vars=dict(x='1')), |
| 274 |
dict(name='User-defined function', token='f', vars=dict(f='function (x) x + x')), |
| 275 |
dict(name='Object which masks other object in workspace', token='c', vars=dict(c='function (x) x + x')), |
| 276 |
] |
| 277 |
|
| 278 |
def test_irkernel_inspects(self): |
| 279 |
"""Test if object inspection works. |
| 280 |
|
| 281 |
Checks if inspect_request for rach `token` returns a reply. |
| 282 |
|
| 283 |
Currently just test if the kernel replys without an error and not care about its content. |
| 284 |
Because the contents of inspections are still so arguable. |
| 285 |
When the requirements for the contents are decided, fix the tests and check the contents. |
| 286 |
""" |
| 287 |
self.flush_channels() |
| 288 |
|
| 289 |
for sample in self.irkernel_inspects: |
| 290 |
with self.subTest(text=sample["name"]): |
| 291 |
for var_name, var_code in sample.get('vars', {}).items(): |
| 292 |
self._execute_code(f'{var_name} <- {var_code}', tests=False) |
| 293 |
|
| 294 |
msg_id = self.kc.inspect(sample["token"]) |
| 295 |
reply = self.kc.get_shell_msg(timeout=TIMEOUT) |
| 296 |
validate_message(reply, 'inspect_reply', msg_id) |
| 297 |
|
| 298 |
self.assertEqual(reply['content']['status'], 'ok') |
| 299 |
self.assertTrue(reply['content']['found']) |
| 300 |
self.assertGreaterEqual(len(reply['content']['data']), 1) |
| 301 |
|
| 302 |
for var_name in sample.get('vars', {}): |
| 303 |
self._execute_code(f'rm("{var_name}")', tests=False) |
| 304 |
|
| 305 |
non_syntactic_completion_samples = [ |
| 306 |
dict(text='xx$host[[1]]$h', |
| 307 |
matches=['xx$host[[1]]$h1', 'xx$host[[1]]$h2'], |
| 308 |
vars=dict(xx='list(host = list(list(h1 = 1, h2 = 2), list(h3 = 3, h4 = 4)))')), |
| 309 |
dict(text='odd_named_list$a', |
| 310 |
matches=['odd_named_list$a'], |
| 311 |
vars=dict(odd_named_list=r'list(a = 1, b = 2, `b c` = 3, `\`\\\`` = 4, 5)')), |
| 312 |
dict(text='odd_named_list$b', |
| 313 |
matches=['odd_named_list$b', 'odd_named_list$`b c`'], |
| 314 |
vars=dict(odd_named_list=r'list(a = 1, b = 2, `b c` = 3, `\`\\\`` = 4, 5)')), |
| 315 |
dict(text='odd_named_list$', |
| 316 |
matches=['odd_named_list$a', 'odd_named_list$b', 'odd_named_list$`b c`', r'odd_named_list$`\`\\\``', 'odd_named_list$'], |
| 317 |
vars=dict(odd_named_list=r'list(a = 1, b = 2, `b c` = 3, `\`\\\`` = 4, 5)')), |
| 318 |
dict(text='arith_named_env$a', |
| 319 |
matches=['arith_named_env$`abc+def`', 'arith_named_env$`abc-def`'], |
| 320 |
vars=dict(arith_named_env='list2env(list(`abc+def` = 1, `def-abc` = 2, `abc-def` = 3, defabc = 4))')), |
| 321 |
dict(text='arith_named_env$def', |
| 322 |
matches=['arith_named_env$`def-abc`', 'arith_named_env$defabc'], |
| 323 |
vars=dict(arith_named_env='list2env(list(`abc+def` = 1, `def-abc` = 2, `abc-def` = 3, defabc = 4))')), |
| 324 |
dict(text='arith_named_env$', |
| 325 |
matches=['arith_named_env$`abc+def`', 'arith_named_env$`def-abc`', 'arith_named_env$`abc-def`', 'arith_named_env$defabc'], |
| 326 |
vars=dict(arith_named_env='list2env(list(`abc+def` = 1, `def-abc` = 2, `abc-def` = 3, defabc = 4))')), |
| 327 |
] |
| 328 |
|
| 329 |
def test_non_syntactic_completions(self): |
| 330 |
"""Test tab-completion for non-syntactic names which require setup/teardown""" |
| 331 |
|
| 332 |
for sample in self.non_syntactic_completion_samples: |
| 333 |
with self.subTest(text=sample['text']): |
| 334 |
for var_name, var_value in sample['vars'].items(): |
| 335 |
self._execute_code(f'{var_name} <- {var_value}', tests=False) |
| 336 |
msg_id = self.kc.complete(sample['text']) |
| 337 |
reply = self.get_non_kernel_info_reply() |
| 338 |
validate_message(reply, 'complete_reply', msg_id) |
| 339 |
self.assertEqual(set(reply['content']['matches']), set(sample['matches'])) |
| 340 |
|
| 341 |
for var_name in sample['vars']: |
| 342 |
self._execute_code(f'rm({var_name})', tests=False) |
| 343 |
|
| 344 |
if __name__ == '__main__': |
| 345 |
unittest.main(verbosity=2) |