test.erp5.testExecuteJupyter.py 21.6 KB
Newer Older
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
##############################################################################
#
# Copyright (c) 2002-2015 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################

28
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
29
from Products.ERP5Type.tests.utils import addUserToDeveloperRole
30
from Products.ERP5Type.tests.utils import createZODBPythonScript, removeZODBPythonScript
31 32 33

import time
import json
34
import base64
35

36

37
class TestExecuteJupyter(ERP5TypeTestCase):
38 39 40 41 42 43 44
  
  def afterSetUp(self):
    """
    Ran to set the environment
    """
    self.notebook_module = self.portal.getDefaultModule(portal_type='Data Notebook')
    self.assertTrue(self.notebook_module is not None)
45

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    # Create user to be used in tests
    user_folder = self.getPortal().acl_users
    user_folder._doAddUser('dev_user', '', ['Manager',], [])
    user_folder._doAddUser('member_user', '', ['Member','Authenticated',], [])
    # Assign developer role to user
    addUserToDeveloperRole('dev_user')
    self.tic()

  def _newNotebook(self, reference=None):
    """
    Function to create new notebook
    """
    return self.notebook_module.DataNotebookModule_addDataNotebook(
      title='Some Notebook Title',
      reference=reference,
      form_id='DataNotebookModule_viewAddNotebookDialog',
      batch_mode=True
      )

65
  def _newNotebookLine(self, notebook_module=None, notebook_code=None):
66
    """
67
    Function to create new notebook line
68
    """
69
    return notebook_module.DataNotebook_addDataNotebookLine(
70 71 72 73
      notebook_code=notebook_code,
      batch_mode=True
      )

74
  def testJupyterCompileErrorRaise(self):
75
    """
76 77 78
    Test if JupyterCompile portal_component correctly catches exceptions as 
    expected by the Jupyter frontend as also automatically abort the current
    transaction.
79
    Take the case in which one line in a statement is valid and another is not.
80 81 82 83 84
    """
    portal = self.getPortalObject()
    script_id = "JupyterCompile_errorResult"
    script_container = portal.portal_skins.custom

85
    new_test_title = "Wendelin Test 1"
86 87
    # Check if the existing title is different from new_test_title or not
    if portal.getTitle()==new_test_title:
88
      new_test_title = "Wendelin"
89 90

    python_script = """
91 92
portal = context.getPortalObject()
portal.setTitle('%s')
93 94 95 96 97
print an_undefined_variable
"""%new_test_title

    # Create python_script object with the above given code and containers
    createZODBPythonScript(script_container, script_id, '', python_script)
98
    self.tic()
99 100 101 102 103 104

    # Call the above created script in jupyter_code
    jupyter_code = """
portal = context.getPortalObject()
portal.%s()
"""%script_id
105
    
106
    # Make call to Base_runJupyter to run the jupyter code which is making
107 108 109 110 111 112
    # a call to the newly created ZODB python_script and assert if the call 
    # processes correctly the NameError as we are sending an invalid 
    # python_code to it.
    # 
    result = portal.Base_runJupyter(
      jupyter_code=jupyter_code, 
113
      old_notebook_context=portal.Base_createNotebookContext()
114 115 116 117 118 119 120 121 122 123
    )
    
    self.assertEquals(result['ename'], 'NameError')
    self.assertEquals(result['result_string'], None)
    
    # There's no need to abort the current transaction. The error handling code
    # should be responsible for this, so we check the script's title
    script_title = script_container.JupyterCompile_errorResult.getTitle()
    self.assertNotEqual(script_title, new_test_title)
    
124
    removeZODBPythonScript(script_container, script_id)
125 126 127

    # Test that calling Base_runJupyter shouldn't change the context Title
    self.assertNotEqual(portal.getTitle(), new_test_title)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    
  def testJupyterCompileInvalidPythonSyntax(self):
    """
    Test how the JupyterCompile extension behaves when it receives Python
    code to be executed that has invalid syntax. 
    """
    self.login('dev_user')
    jupyter_code = "a = 1\na++"
    
    reference = 'Test.Notebook.ErrorHandling.SyntaxError'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    result_json = json.loads(result)
    
    self.assertEquals(result_json['ename'], 'SyntaxError')
145

146 147 148 149 150 151 152
  def testUserCannotAccessBaseExecuteJupyter(self):
    """
    Test if non developer user can't access Base_executeJupyter
    """
    portal = self.portal

    self.login('member_user')
153
    result = portal.Base_executeJupyter(title='Any title', reference='Any reference')
154

155
    self.assertEquals(result, 'You are not authorized to access the script')
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173

  def testUserCanCreateNotebookWithoutCode(self):
    """
    Test the creation of Data Notebook object
    """
    portal = self.portal

    notebook = self._newNotebook(reference='new_notebook_without any_code')
    self.tic()

    notebook_search_result = portal.portal_catalog(
                                      portal_type='Data Notebook',
                                      title='Some Notebook Title'
                                      )

    result_title = [obj.getTitle() for obj in notebook_search_result]
    if result_title:
      self.assertEquals(notebook.getTitle(), result_title[0])
174

175 176
  def testUserCanCreateNotebookWithCode(self):
    """
177
    Test if user can create Data Notebook Line object or not
178 179 180
    """
    portal = self.portal

181
    notebook = self._newNotebook(reference='new_notebook_with_code %s' %time.time())
182
    self.tic()
183 184

    notebook_code='some_random_invalid_notebook_code %s' % time.time()
185
    notebook_line = self._newNotebookLine(
186 187 188 189 190
                            notebook_module=notebook,
                            notebook_code=notebook_code
                            )
    self.tic()

191
    notebook_line_search_result = portal.portal_catalog(portal_type='Data Notebook Line')
192

193 194
    result_reference_list = [obj.getReference() for obj in notebook_line_search_result]
    result_id_list = [obj.getId() for obj in notebook_line_search_result]
195

196 197 198 199
    if result_reference_list:
      self.assertIn(notebook.getReference(), result_reference_list)
      self.assertEquals(notebook_line.getReference(), notebook.getReference())
      self.assertIn(notebook_line.getId(), result_id_list)
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

  def testBaseExecuteJupyterAddNewNotebook(self):
    """
    Test the functionality of Base_executeJupyter python script.
    This test will cover folowing cases - 
    1. Call to Base_executeJupyter without python_expression
    2. Creating new notebook using the script
    """
    portal = self.portal
    self.login('dev_user')
    reference = 'Test.Notebook.AddNewNotebook %s' % time.time()
    title = 'Test new NB Title %s' % time.time()

    portal.Base_executeJupyter(title=title, reference=reference)
    self.tic()

    notebook_list = portal.portal_catalog(
                                    portal_type='Data Notebook',
                                    reference=reference
                                    )

    self.assertEquals(len([obj.getTitle() for obj in notebook_list]), 1)

223
  def testBaseExecuteJupyterAddNotebookLine(self):
224
    """
225
    Test if the notebook adds code history to the Data Notebook Line
226 227
    portal type while multiple calls are made to Base_executeJupyter with
    notebooks having same reference
228 229 230 231
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = "print 52"
232
    reference = 'Test.Notebook.AddNewNotebookLine %s' % time.time()
233
    title = 'Test NB Title %s' % time.time()
234

235 236 237 238 239 240 241 242 243 244 245
    # Calling the function twice, first to create a new notebook and then
    # sending python_expression to check if it adds to the same notebook
    portal.Base_executeJupyter(title=title, reference=reference)
    self.tic()

    portal.Base_executeJupyter(
                              reference=reference,
                              python_expression=python_expression
                              )
    self.tic()

246
    notebook = portal.portal_catalog.getResultValue(
247 248 249 250
                                          portal_type='Data Notebook',
                                          reference=reference
                                          )

251
    notebook_line_search_result = portal.portal_catalog.getResultValue(
252 253
                                              portal_type='Data Notebook Line',
                                              reference=reference
254
                                              )
255 256 257 258 259 260
    # As we use timestamp in the reference and the notebook is created in this
    # function itself so, if anyhow a new Data Notebook Line has been created,
    # then it means that the code has been added to Input and Output of Data
    # Notebook Line portal_type
    if notebook_line_search_result:
      self.assertEquals(notebook.getReference(), notebook_line_search_result.getReference())
261 262 263

  def testBaseExecuteJupyterErrorHandling(self):
    """
264 265 266
    Test if the Base_executeJupyter with invalid python code raises error on
    server side. We are not catching the exception here. Expected result is
    raise of exception.
267 268 269 270 271 272 273
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = 'some_random_invalid_python_code'
    reference = 'Test.Notebook.ExecuteJupyterErrorHandling %s' % time.time()
    title = 'Test NB Title %s' % time.time()

274 275 276 277 278 279 280 281
    result = json.loads(portal.Base_executeJupyter(
      title=title, 
      reference=reference, 
      python_expression=python_expression
    ))
    
    self.assertEquals(result['ename'], 'NameError')
    self.assertEquals(result['code_result'], None)
282

283
  def testBaseExecuteJupyterSaveNotebookContext(self):
284
    """
285 286
    Test if user context is being saved in the notebook_context property and the 
    user can access access and execute python code on it.
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = 'a=2; b=3; print a+b'
    reference = 'Test.Notebook.ExecutePythonExpressionWithVariables %s' % time.time()
    title = 'Test NB Title %s' % time.time()

    portal.Base_executeJupyter(
                              title=title,
                              reference=reference,
                              python_expression=python_expression
                              )
    self.tic()

    notebook_list = portal.portal_catalog(
                                          portal_type='Data Notebook',
                                          reference=reference
                                          )
    notebook = notebook_list[0]
306
    notebook_context = notebook.getNotebookContext()['variables']
307
    result = {'a':2, 'b':3}
308
    self.assertDictContainsSubset(result, notebook_context)
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

  def testBaseExecuteJupyterRerunWithPreviousLocalVariables(self):
    """
    Test if the Base_compileJupyter function in extension is able to recognize
    the local_variables from the previous run and execute the python code
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = 'a=2; b=3; print a+b'
    reference = 'Test.Notebook.ExecutePythonExpressionWithVariables %s' % time.time()
    title = 'Test NB Title %s' % time.time()

    portal.Base_executeJupyter(
                              title=title,
                              reference=reference,
                              python_expression=python_expression
                              )
    self.tic()

    python_expression = 'x=5; b=4; print a+b+x'
    result = portal.Base_executeJupyter(
                                        reference=reference,
                                        python_expression=python_expression
                                        )
    self.tic()

    expected_result = '11'
    self.assertEquals(json.loads(result)['code_result'].rstrip(), expected_result)

338 339
  def testSavingModuleObjectLocalVariables(self):
    """
340
    Test to check the saving of module objects in notebook_context
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    and if they work as expected.
    """
    portal = self.portal
    self.login('dev_user')
    jupyter_code = """
import imghdr as imh
import sys
"""
    reference = 'Test.Notebook.ModuleObject %s' %time.time()
    portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
      )
    self.tic()

    jupyter_code =  "print imh.__name__"
    result = portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code)

    self.assertEquals(json.loads(result)['code_result'].rstrip(), 'imghdr')
    self.assertEquals(json.loads(result)['mime_type'].rstrip(), 'text/plain')

364
  def testERP5ImageProcessor(self):
365
    """
366 367
    Test the fucntioning of the ERP5ImageProcessor and the custom system 
    display hook too. 
368 369 370 371
    """
    self.image_module = self.portal.getDefaultModule('Image')
    self.assertTrue(self.image_module is not None)
    # Create a new ERP5 image object
372 373
    reference = 'testBase_displayImageReference5'
    data_template = '<img src="data:application/unknown;base64,%s" /><br />'
374 375 376
    data = 'qwertyuiopasdfghjklzxcvbnm<somerandomcharacterstosaveasimagedata>'
    self.image_module.newContent(
      portal_type='Image',
377
      id='testBase_displayImageID5',
378 379 380 381 382 383 384 385
      reference=reference,
      data=data,
      filename='test.png'
      )
    self.tic()

    # Call Base_displayImage from inside of Base_runJupyter
    jupyter_code = """
386
image = context.portal_catalog.getResultValue(portal_type='Image',reference='%s')
387
context.Base_renderAsHtml(image)
388 389
"""%reference

390
    notebook_context = {'setup' : {}, 'variables' : {}}
391 392
    result = self.portal.Base_runJupyter(
      jupyter_code=jupyter_code,
393
      old_notebook_context=notebook_context
394 395
      )

396
    self.assertTrue((data_template % base64.b64encode(data)) in result['result_string'])
397 398 399
    # Mime_type shouldn't be  image/png just because of filename, instead it is
    # dependent on file and file data
    self.assertNotEqual(result['mime_type'], 'image/png')
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433

  def testImportSameModuleDifferentNamespace(self):
    """
    Test if the imports of python modules with same module name but different
    namespace work correctly as expected
    """
    portal = self.portal
    self.login('dev_user')

    # First we execute a jupyter_code which imports sys module as 'ss' namespace
    jupyter_code = "import sys as ss"
    reference = 'Test.Notebook.MutlipleImports %s' %time.time()
    portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
      )
    self.tic()

    # Call Base_executeJupyter again with jupyter_code which imports sys module
    # as 'ss1' namespace
    jupyter_code1 = "import sys as ss1"
    portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code1
      )
    self.tic()

    # Call Base_executeJupyter to check for the name of module and match it with
    # namespace 'ss1'
    jupyter_code2 = "print ss1.__name__"
    result = portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code2
      )
434 435
    self.assertEquals(json.loads(result)['code_result'].rstrip(), 'sys')
    
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
  def testEnvironmentObjectWithFunctionAndClass(self):
    self.login('dev_user')
    environment_define_code = '''
def create_sum_machines():
  def sum_function(x, y):
    return x + y
    
  class Calculator(object):
  
    def sum(self, x, y):
      return x + y
    
  return {'sum_function': sum_function, 'Calculator': Calculator}

environment.clearAll()
environment.define(create_sum_machines, 'creates sum function and class')
'''
    reference = 'Test.Notebook.EnvironmentObject.Function'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=environment_define_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    jupyter_code = '''
print sum_function(1, 1)
print Calculator().sum(2, 2)
'''
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    
    self.tic()
    result = json.loads(result)
    output = result['code_result']
    self.assertEquals(result['status'], 'ok')
    self.assertEquals(output.strip(), '2\n4')
    
  def testEnvironmentObjectSimpleVariable(self):
    self.login('dev_user')
    environment_define_code = '''
environment.clearAll()
environment.define(x='couscous')
'''
    reference = 'Test.Notebook.EnvironmentObject.Variable'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=environment_define_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    jupyter_code = 'print x'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    
    self.tic()
    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')
    self.assertEquals(result['code_result'].strip(), 'couscous')
    
  def testEnvironmentUndefineFunctionClass(self):
    self.login('dev_user')
    environment_define_code = '''
def create_sum_machines():
  def sum_function(x, y):
    return x + y
    
  class Calculator(object):
  
    def sum(self, x, y):
      return x + y
    
  return {'sum_function': sum_function, 'Calculator': Calculator}

environment.clearAll()
environment.define(create_sum_machines, 'creates sum function and class')
'''
    reference = 'Test.Notebook.EnvironmentObject.Function.Undefine'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=environment_define_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    undefine_code = '''
environment.undefine('creates sum function and class')
'''
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=undefine_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    jupyter_code = '''
print 'sum_function' in locals()
print 'Calculator' in locals()
'''

    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    result = json.loads(result)
    output = result['code_result']
    self.assertEquals(result['status'], 'ok')
    self.assertEquals(output.strip(), 'False\nFalse')
    
  def testEnvironmentUndefineVariable(self):
    self.login('dev_user')
    environment_define_code = '''
environment.clearAll()
environment.define(x='couscous')
'''
    reference = 'Test.Notebook.EnvironmentObject.Variable.Undefine'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=environment_define_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    undefine_code = 'environment.undefine("x")'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=undefine_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    jupyter_code = "'x' in locals()"
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    
    self.tic()
    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')
    self.assertEquals(result['code_result'].strip(), 'False')
    
  def testImportFixer(self):
    self.login('dev_user')
    import_code = '''
import random
'''

    reference = 'Test.Notebook.EnvironmentObject.ImportFixer'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=import_code
    )
    
    self.tic()
    self.assertEquals(json.loads(result)['status'], 'ok')
    
    jupyter_code = '''
print random.randint(1,1)
'''
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    
    self.tic()
    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')
    self.assertEquals(result['code_result'].strip(), '1')
    
617 618 619 620 621 622 623 624 625 626 627 628 629
  def testPivotTableJsIntegration(self):
    '''
      This test ensures the PivotTableJs user interface is correctly integrated
      into our Jupyter kernel.
    '''
    portal = self.portal
    self.login('dev_user')
    jupyter_code = '''
class DataFrameMock(object):
    def to_csv(self):
        return "column1, column2; 1, 2;" 

my_df = DataFrameMock()
630
iframe = context.Base_erp5PivotTableUI(my_df)
631 632 633 634 635 636 637 638 639 640 641 642 643 644
context.Base_renderAsHtml(iframe)
'''
    reference = 'Test.Notebook.PivotTableJsIntegration %s' % time.time()
    notebook = self._newNotebook(reference=reference)
    result = portal.Base_executeJupyter(
      reference=reference,
      python_expression=jupyter_code
    )
    json_result = json.loads(result)
    
    # The big hash in this string was previous calculated using the expect hash
    # of the pivot table page's html.
    pivottable_frame_display_path = 'Base_displayPivotTableFrame?key=853524757258b19805d13beb8c6bd284a7af4a974a96a3e5a4847885df069a74d3c8c1843f2bcc4d4bb3c7089194b57c90c14fe8dd0c776d84ce0868e19ac411'
    self.assertTrue(pivottable_frame_display_path in json_result['code_result'])
645