github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/utils/interactive_utils_test.py (about)

     1  #
     2  # Licensed to the Apache Software Foundation (ASF) under one or more
     3  # contributor license agreements.  See the NOTICE file distributed with
     4  # this work for additional information regarding copyright ownership.
     5  # The ASF licenses this file to You under the Apache License, Version 2.0
     6  # (the "License"); you may not use this file except in compliance with
     7  # the License.  You may obtain a copy of the License at
     8  #
     9  #    http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  #
    17  
    18  """Tests for interactive_utils module."""
    19  
    20  # pytype: skip-file
    21  
    22  import unittest
    23  from unittest.mock import patch
    24  
    25  from apache_beam.runners.interactive import interactive_environment as ie
    26  from apache_beam.runners.interactive.testing.mock_ipython import mock_get_ipython
    27  from apache_beam.utils.interactive_utils import is_in_ipython
    28  
    29  
    30  def unavailable_ipython():
    31    # ModuleNotFoundError since Py3.6 is sub class of ImportError. An example,
    32    # 'import apache_beam.hahaha' raises a ModuleNotFoundError while
    33    # 'from apache_beam import hahaha' raises an ImportError.
    34    # For simplicity, we only use super class ImportError here.
    35    raise ImportError('Module IPython is not found.')
    36  
    37  
    38  def corrupted_ipython():
    39    raise AttributeError('Module IPython does not contain get_ipython.')
    40  
    41  
    42  @unittest.skipIf(
    43      not ie.current_env().is_interactive_ready,
    44      '[interactive] dependency is not installed.')
    45  class IPythonTest(unittest.TestCase):
    46    @patch('IPython.get_ipython', new_callable=mock_get_ipython)
    47    def test_is_in_ipython_when_in_ipython_kernel(self, kernel):
    48      self.assertTrue(is_in_ipython())
    49  
    50    @patch('IPython.get_ipython', new_callable=lambda: unavailable_ipython)
    51    def test_is_not_in_ipython_when_no_ipython_dep(self, unavailable):
    52      self.assertFalse(is_in_ipython())
    53  
    54    @patch('IPython.get_ipython', new_callable=lambda: corrupted_ipython)
    55    def test_is_not_ipython_when_ipython_errors_out(self, corrupted):
    56      self.assertFalse(is_in_ipython())
    57  
    58  
    59  if __name__ == '__main__':
    60    unittest.main()