test.erp5.testExecuteJupyter.py 17.2 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 113 114 115 116 117 118 119 120 121 122 123
    # 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, 
      old_local_variable_dict=portal.Base_addLocalVariableDict()
    )
    
    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 128

    # Test that calling Base_runJupyter shouldn't change the context Title
    self.assertNotEqual(portal.getTitle(), new_test_title)

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  def testUserCannotAccessBaseExecuteJupyter(self):
    """
    Test if non developer user can't access Base_executeJupyter
    """
    portal = self.portal

    self.login('member_user')
    result = portal.Base_executeJupyter.Base_checkPermission('portal_components', 'Manage Portal')

    self.assertFalse(result)

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

158 159
  def testUserCanCreateNotebookWithCode(self):
    """
160
    Test if user can create Data Notebook Line object or not
161 162 163
    """
    portal = self.portal

164
    notebook = self._newNotebook(reference='new_notebook_with_code %s' %time.time())
165
    self.tic()
166 167

    notebook_code='some_random_invalid_notebook_code %s' % time.time()
168
    notebook_line = self._newNotebookLine(
169 170 171 172 173
                            notebook_module=notebook,
                            notebook_code=notebook_code
                            )
    self.tic()

174
    notebook_line_search_result = portal.portal_catalog(portal_type='Data Notebook Line')
175

176 177
    result_reference_list = [obj.getReference() for obj in notebook_line_search_result]
    result_id_list = [obj.getId() for obj in notebook_line_search_result]
178

179 180 181 182
    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)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205

  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)

206
  def testBaseExecuteJupyterAddNotebookLine(self):
207
    """
208
    Test if the notebook adds code history to the Data Notebook Line
209 210
    portal type while multiple calls are made to Base_executeJupyter with
    notebooks having same reference
211 212 213 214
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = "print 52"
215
    reference = 'Test.Notebook.AddNewNotebookLine %s' % time.time()
216
    title = 'Test NB Title %s' % time.time()
217

218 219 220 221 222 223 224 225 226 227 228
    # 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()

229
    notebook = portal.portal_catalog.getResultValue(
230 231 232 233
                                          portal_type='Data Notebook',
                                          reference=reference
                                          )

234
    notebook_line_search_result = portal.portal_catalog.getResultValue(
235 236
                                              portal_type='Data Notebook Line',
                                              reference=reference
237
                                              )
238 239 240 241 242 243
    # 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())
244 245 246

  def testBaseExecuteJupyterErrorHandling(self):
    """
247 248 249
    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.
250 251 252 253 254 255 256
    """
    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()

257 258 259 260 261 262 263 264
    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)
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

  def testBaseExecuteJupyterSaveActiveResult(self):
    """
    Test if the result is being saved inside active_process and the user can
    access the loacl variable and execute python expression on them
    """
    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]
    process_id = notebook.getProcess()
    active_process = portal.portal_activities[process_id]
    result_list = active_process.getResultList()
292
    local_variable_dict = result_list[0].summary['variables']
293
    result = {'a':2, 'b':3}
294
    self.assertDictContainsSubset(result, local_variable_dict)
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342

  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)

  def testBaseExecuteJupyterWithContextObjectsAsLocalVariables(self):
    """
    Test Base_executeJupyter with context objects as local variables
    """
    portal = self.portal
    self.login('dev_user')
    python_expression = 'a=context.getPortalObject(); print a.getTitle()'
    reference = 'Test.Notebook.ExecutePythonExpressionWithVariables %s' % time.time()
    title = 'Test NB Title %s' % time.time()

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

    expected_result = portal.getTitle()
    self.assertEquals(json.loads(result)['code_result'].rstrip(), expected_result)
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369

  def testSavingModuleObjectLocalVariables(self):
    """
    Test to check the saving of module objects in local_variable_dict
    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')

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

    # Call Base_displayImage from inside of Base_runJupyter
    jupyter_code = """
392
image = context.portal_catalog.getResultValue(portal_type='Image',reference='%s')
393
context.Base_renderAsHtml(image)
394 395 396 397 398 399 400 401
"""%reference

    local_variable_dict = {'imports' : {}, 'variables' : {}}
    result = self.portal.Base_runJupyter(
      jupyter_code=jupyter_code,
      old_local_variable_dict=local_variable_dict
      )

402
    self.assertEquals(result['result_string'].rstrip(), data_template % base64.b64encode(data))
403 404 405
    # 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')
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 438 439

  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
      )
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
    self.assertEquals(json.loads(result)['code_result'].rstrip(), 'sys')
    
  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()
iframe = context.Base_erp5PivotTableUI(my_df, 'https://localhost:2202/erp5')
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'])