test.erp5.testExecuteJupyter.py 29.3 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
import random
import string
37

38

39
class TestExecuteJupyter(ERP5TypeTestCase):
40 41 42 43 44 45 46
  
  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)
47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    # 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
      )

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

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

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

    python_script = """
93 94
portal = context.getPortalObject()
portal.setTitle('%s')
95 96 97 98 99
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)
100
    self.tic()
101 102 103 104 105 106

    # Call the above created script in jupyter_code
    jupyter_code = """
portal = context.getPortalObject()
portal.%s()
"""%script_id
107
    
108
    # Make call to Base_runJupyter to run the jupyter code which is making
109 110 111 112 113 114
    # 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, 
115
      old_notebook_context=portal.Base_createNotebookContext()
116 117 118 119 120 121 122 123 124 125
    )
    
    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)
    
126
    removeZODBPythonScript(script_container, script_id)
127 128 129

    # Test that calling Base_runJupyter shouldn't change the context Title
    self.assertNotEqual(portal.getTitle(), new_test_title)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    
  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')
147

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

    self.login('member_user')
155
    result = portal.Base_executeJupyter(title='Any title', reference='Any reference')
156

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

  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])
176

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

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

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

193
    notebook_line_search_result = portal.portal_catalog(portal_type='Data Notebook Line')
194

195 196
    result_reference_list = [obj.getReference() for obj in notebook_line_search_result]
    result_id_list = [obj.getId() for obj in notebook_line_search_result]
197

198 199 200 201
    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)
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

  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)

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

237 238 239 240 241 242 243 244 245 246 247
    # 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()

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

253
    notebook_line_search_result = portal.portal_catalog.getResultValue(
254 255
                                              portal_type='Data Notebook Line',
                                              reference=reference
256
                                              )
257 258 259 260 261 262
    # 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())
263 264 265

  def testBaseExecuteJupyterErrorHandling(self):
    """
266 267 268
    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.
269 270 271 272 273 274 275
    """
    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()

276 277 278 279 280 281 282 283
    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)
284

285
  def testBaseExecuteJupyterSaveNotebookContext(self):
286
    """
287 288
    Test if user context is being saved in the notebook_context property and the 
    user can access access and execute python code on it.
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    """
    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]
308
    notebook_context = notebook.getNotebookContext()['variables']
309
    result = {'a':2, 'b':3}
310
    self.assertDictContainsSubset(result, notebook_context)
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

  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)

340 341
  def testSavingModuleObjectLocalVariables(self):
    """
342
    Test to check the saving of module objects in notebook_context
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
    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')

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

    # Call Base_displayImage from inside of Base_runJupyter
    jupyter_code = """
390
image = context.portal_catalog.getResultValue(portal_type='Image',reference='%s')
391
context.Base_renderAsHtml(image)
392 393
"""%reference

394
    notebook_context = {'setup' : {}, 'variables' : {}}
395 396
    result = self.portal.Base_runJupyter(
      jupyter_code=jupyter_code,
397
      old_notebook_context=notebook_context
398 399
      )

400
    self.assertTrue((data_template % base64.b64encode(data)) in result['result_string'])
401 402 403
    # 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')
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 434 435 436 437

  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
      )
438 439
    self.assertEquals(json.loads(result)['code_result'].rstrip(), 'sys')
    
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
  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')
    
582
    jupyter_code = "print 'x' in locals()"
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 617 618 619 620
    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')
    
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
  def testEnvorinmentUndefineErrors(self):
    """
      Tests if environment.undefine wrong usage errors are correctly captured 
      and rendered in Jupyter.
    """
    self.login('dev_user')
    undefine_not_found = 'environment.undefine("foobar")' 
    
    reference = 'Test.Notebook.EnvironmentObject.Errors.Undefine'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=undefine_not_found
    )
    self.tic()
    
    error_substring = 'EnvironmentUndefineError: Trying to remove non existing'
    self.assertTrue(error_substring in result)
    
    not_string_code = 'def foobar(): pass\nenvironment.undefine(foobar)'
    
    reference = 'Test.Notebook.EnvironmentObject.Errors.Undefine'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=not_string_code
    )
    self.tic()
    
    error_substring = 'EnvironmentUndefineError: Type mismatch.'
    self.assertTrue(error_substring in result)
    
  def testEnvironmentDefineErrrors(self):
    """
      Tests if environment.define wrong usage errors are correctly captured 
      and rendered in Jupyter.
    """
    self.login('dev_user')
    
    first_arg_type_code = "environment.define('foobar', 'foobar')" 
    
    reference = 'Test.Notebook.EnvironmentObject.Errors.Define'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=first_arg_type_code
    )
    self.tic()
    
    error_substring = 'EnvironmentDefinitionError: Type mismatch'
    self.assertTrue(error_substring in result)
    self.assertTrue('first argument' in result)
    
    second_arg_type_code = 'def couscous(): pass\nenvironment.define(couscous, 123)'
    
    reference = 'Test.Notebook.EnvironmentObject.Errors.Define'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=second_arg_type_code
    )
    self.tic()
    
    error_substring = 'EnvironmentDefinitionError: Type mismatch'
    self.assertTrue(error_substring in result)
    self.assertTrue('second argument' in result)
    
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
  def testImportFixerWithAlias(self):
    self.login('dev_user')
    import_code = '''
import random as rand
'''

    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 rand.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')  

712 713 714 715 716 717 718 719 720 721 722 723 724
  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()
725
iframe = context.Base_erp5PivotTableUI(my_df)
726 727 728 729 730 731 732 733 734 735 736 737 738
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'
739
    
740
    self.assertTrue(pivottable_frame_display_path in json_result['code_result'])
741

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
  def testConsecutiveImports(self):
    '''
      This test guarantees that importing a module's variables consecutively in
      Jupyter works.
    '''
    self.login('dev_user')
    import_code = '''
from string import ascii_lowercase, ascii_uppercase, digits
'''
    reference = 'Test.Notebook.EnvironmentObject.Errors.Import'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=import_code
    )
    self.tic()

    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')

    jupyter_code = '''
print ascii_lowercase
'''
    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(), 'abcdefghijklmnopqrstuvwxyz')

    jupyter_code = '''
print ascii_uppercase
'''
    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(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')

    jupyter_code = '''
print digits
'''
    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(), '0123456789')

  def testStarImport(self):
    '''
      This test guarantees that "from x import *" works in Jupyter.
    '''
    self.login('dev_user')
    import_code = '''
from string import *
'''
    reference = 'Test.Notebook.EnvironmentObject.Errors.Import'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=import_code
    )
    self.tic()

    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')

    jupyter_code = '''
print ascii_lowercase
'''
    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(), 'abcdefghijklmnopqrstuvwxyz')

  def testAsImport(self):
    '''
      This test guarantees that "from x import a as b" works in Jupyter.
    '''
    self.login('dev_user')
    import_code = '''
from string import digits as dig
'''
    reference = 'Test.Notebook.EnvironmentObject.Errors.Import'
    result = self.portal.Base_executeJupyter(
      reference=reference,
      python_expression=import_code
    )
    self.tic()

    result = json.loads(result)
    self.assertEquals(result['status'], 'ok')

    jupyter_code = '''
print dig
'''
    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(), '0123456789')
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
    
  def testReferenceWarning(self):
    '''
      Tests Base_checkExistingReference in JupyterCompile.
    '''
    self.login('dev_user')
    
    notebook_reference = u''.join(random.choice(string.ascii_lowercase) for _ in range(30))
    notebook_title = u''.join(random.choice(string.ascii_lowercase) for _ in range(30))
    
    notebook_module = self.portal.getDefaultModule(portal_type='Data Notebook')
    data_notebook = notebook_module.DataNotebookModule_addDataNotebook(
                                      title=notebook_title,
                                      reference=notebook_reference,
                                      batch_mode=True)
    self.tic()
        
    result = self.portal.Base_checkExistingReference(
      reference=notebook_reference,
    )
    self.tic()
882

883
    self.assertEquals(result, True)
Iliya Manolov's avatar
Iliya Manolov committed
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926

def testNPArrayPrint(self):
  self.login('dev_user')
  import_code = '''
import numpy as np
'''
  reference = 'Test.Notebook.EnvironmentObject.Errors.NPArrayTest'
  result = self.portal.Base_executeJupyter(
    reference=reference,
    python_expression=import_code
  )
  self.tic()

  result = json.loads(result)
  self.assertEquals(result['status'], 'ok')
  
  jupyter_code = '''
print np.random.rand(256, 256, 256)
'''

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

  result = json.loads(result)
  self.assertEquals(result['status'], 'ok')

  jupyter_code = '''
print np.random.randint(low = 2 ** 63 - 1, size = (256, 256, 256), dtype = 'int64')
'''

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

  result = json.loads(result)
  self.assertEquals(result['status'], 'ok')