github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/runners/interactive/testing/mock_ipython.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 19 def mock_get_ipython(): 20 """Mock an ipython environment w/o setting up real ipython kernel. 21 22 Each entering of get_ipython() invocation will have the prompt increased by 23 one. Grouping arbitrary python code into separate cells using `with` clause. 24 25 Examples:: 26 27 # Usage, before each test function, prepend: 28 @patch('IPython.get_ipython', new_callable=mock_get_ipython) 29 30 # In the test function's signature, add an argument for the patch, e.g.: 31 def some_test(self, cell): 32 33 # Group lines of code into a cell using the argument: 34 with cell: 35 # arbitrary python code 36 # ... 37 # arbitrary python code 38 39 # Next cell with prompt increased by one: 40 with cell: # Auto-incremental 41 # arbitrary python code 42 # ... 43 # arbitrary python code 44 """ 45 class MockedGetIpython(object): 46 def __init__(self): 47 self._execution_count = 0 48 # Mock as if the kernel is connected to a notebook frontend. 49 self.config = {'IPKernelApp': 'mock'} 50 51 def __call__(self): 52 return self 53 54 @property 55 def execution_count(self): 56 """Execution count always starts from 1 and is constant within a cell.""" 57 return self._execution_count 58 59 def __enter__(self): 60 """Marks entering of a cell/prompt.""" 61 self._execution_count = self._execution_count + 1 62 63 def __exit__(self, exc_type, exc_value, traceback): 64 """Marks exiting of a cell/prompt.""" 65 pass 66 67 return MockedGetIpython()