def test_render(): fake_env = FakeEnv() fake_agent = FakeAgent(observation_space=None, action_space=None) trainer = Trainer(environment=fake_env, agent=fake_agent) trainer.render() assert fake_env.step_done == 0 and fake_env.reset_done == 0 and fake_env.render_done == 1 from IPython.testing.globalipapp import get_ipython get_ipython().run_line_magic('matplotlib', 'inline') sys.stdout = FakeOutStream() # init inline trainer.render() assert fake_env.step_done == 0 and fake_env.reset_done == 0 and fake_env.render_done == 2 # maj inline trainer.render() assert fake_env.step_done == 0 and fake_env.reset_done == 0 and fake_env.render_done == 3 ## Test when rgba mode is not supported from gym env fake_env = FakeEnvRaise() trainer = Trainer(environment=fake_env, agent=fake_agent) # init inline trainer.render()
def my_func(): ip0 = get_ipython() if ip0 is None: return func() # We have a real ipython running... user_ns = ip0.user_ns user_global_ns = ip0.user_global_ns # Previously the isolation was attempted with a deep copy of the user # dicts, but we found cases where this didn't work correctly. I'm not # quite sure why, but basically it did damage the user namespace, such # that later tests stopped working correctly. Instead we use a simpler # approach, just computing the list of added keys to the namespace and # eliminating those afterwards. Existing keys that may have been # modified remain modified. So far this has proven to be robust. # Compute set of old local/global keys old_locals = set(user_ns.keys()) old_globals = set(user_global_ns.keys()) try: out = func() finally: # Find new keys, and if any, remove them new_locals = set(user_ns.keys()) - old_locals new_globals = set(user_global_ns.keys()) - old_globals for k in new_locals: del user_ns[k] for k in new_globals: del user_global_ns[k] return out
def test_webgl_loading(): """Test if the vispy.ipython extension loads the webGL backend on IPython 3.0 and greater. Test if it fails to load the webGL backend for IPython versions less that 3.0 """ import IPython from distutils.version import LooseVersion from IPython.testing.globalipapp import get_ipython ipy = get_ipython() ipy.run_cell("from vispy import app") if LooseVersion(IPython.__version__) >= LooseVersion("3.0.0"): ipy.run_cell("%load_ext vispy.ipython") ipy.run_cell("backend_name = app.use_app().backend_name") # make sure that the webgl backend got loaded assert_equal(ipy.user_ns["backend_name"], "ipynb_webgl") else: ipy.run_cell("%load_ext vispy.ipython") ipy.run_cell("backend_name = app.use_app().backend_name") # the above call should have failed, and thus the key # backend_name should not exist in the namespace def invalid_backend_access(ipy): ipy.user_ns["backend_name"] assert_raises(KeyError, invalid_backend_access, ipy)
def test_display_extension(self): # noinspection PyUnresolvedReferences import pyrasterframes.rf_ipython self.create_layer() ip = globalipapp.get_ipython() num_rows = 2 result = {} def counter(data, md): nonlocal result result['payload'] = (data, md) result['row_count'] = data.count('<tr>') ip.mime_renderers['text/html'] = counter # ip.mime_renderers['text/markdown'] = lambda a, b: print(a, b) self.df.display(num_rows=num_rows) # Plus one for the header row. self.assertIs(result['row_count'], num_rows + 1, msg=f"Received: {result['payload']}")
def test_webgl_loading(): """Test if the vispy.ipython extension loads the webGL backend on IPython 3.0 and greater. Test if it fails to load the webGL backend for IPython versions less that 3.0""" import IPython from distutils.version import LooseVersion from IPython.testing.globalipapp import get_ipython ipy = get_ipython() ipy.run_cell("from vispy import app") if LooseVersion(IPython.__version__) >= LooseVersion("3.0.0"): ipy.run_cell("%load_ext vispy.ipython") ipy.run_cell("backend_name = app.use_app().backend_name") # make sure that the webgl backend got loaded assert_equal(ipy.user_ns["backend_name"], "ipynb_webgl") else: ipy.run_cell("%load_ext vispy.ipython") ipy.run_cell("backend_name = app.use_app().backend_name") # the above call should have failed, and thus the key # backend_name should not exist in the namespace def invalid_backend_access(ipy): ipy.user_ns["backend_name"] assert_raises(KeyError, invalid_backend_access, ipy)
def get_ip(): ip = get_ipython() ip.run_cell('%load_ext autoreload') ip.run_cell('%autoreload 2') ip.run_cell('import numpy as np') ip.run_cell('import matplotlib.pylab as plt') return ip
def setUp(self): os.environ['DJANGO_SETTINGS_MODULE'] = 'mydjangosettings' sys.modules['mydjangosettings'] = Settings() import django django.setup() self.ipshell = globalipapp.get_ipython() import django_tabcomplete
def register(db, test=False): global get_ipython if test: from IPython.testing.globalipapp import get_ipython ip = get_ipython() magics = SqlMagic(ip, db) ip.register_magics(magics) return ip
def ipython_with_magic(): if IPython is None: return None ip = get_ipython() # This is just to get a minimally modified version of the changes # working ip.magic('load_ext rpy2.ipython') return ip
def setUp(self): self._ip = get_ipython() if self._ip is None: self._ip = start_test_ip() self.style = GruvboxStyle() # self.colorscheme = self._ip.highlighting_style.style_rules self.colorscheme = self.style.style_rules
def setup_class(cls): cls.ip = get_ipython() cls.ip.run_cell('import random') cls.ip.run_cell('import numpy as np') if 'USE_OCTAVE' in os.environ: matlab = 'octave' else: matlab = 'matlab' pymat.load_ipython_extension(cls.ip, matlab=matlab)
def setUpClass(cls): '''Set up an IPython session just once. It'd be safer to set it up for each test, but for now, I'm mimicking the IPython team's logic. ''' cls.ip = get_ipython() # This is just to get a minimally modified version of the changes # working cls.ip.magic('load_ext rpy2.ipython')
def setUp(self): Settings.DEFAULT_EXTENSION_TYPES.clear() Settings.DEFAULT_EXTENSION_TYPES.append( "tests.test_yuuno.SupportedTestExtension") YuunoIPythonEnvironment.feature_classes = [ "tests.test_ipython_environment.TestFeature" ] self.shell = globalipapp.get_ipython()
def cc(): import matplotlib.pyplot from IPython.testing.globalipapp import get_ipython # https://pmbaumgartner.github.io/blog/testing-ipython-magics/ ip = get_ipython() matplotlib.pyplot.close("all") #IPython.get_ipython().run_line_magic('reset', " -f in") # ref: https://ipython.readthedocs.io/en/stable/interactive/magics.html #ip.run_line_magic('reset', " -f in") # short form works ip.run_line_magic('reset', '-f ') # short form works
def setUp(self): Settings.DEFAULT_EXTENSION_TYPES.clear() Settings.DEFAULT_EXTENSION_TYPES.append("tests.test_ipython_formatter.TestClipExtension") YuunoIPythonEnvironment.feature_classes = [ "tests.test_ipython_magic.TestMagicFeature" ] self.shell = globalipapp.get_ipython() load_ipython_extension(self.shell) self.loaded = True
def setUpClass(cls): '''Set up an IPython session just once. It'd be safer to set it up for each test, but for now, I'm mimicking the IPython team's logic. ''' if not sys.stdin.encoding: sys.stdin.encoding = 'utf-8' # needed for py.test cls.ip = get_ipython() # This is just to get a minimally modified version of the changes # working cls.ip.magic('load_ext oct2py.ipython') cls.ip.ex('import numpy as np') cls.svgs_generated = 0
def setUp(self): Settings.DEFAULT_EXTENSION_TYPES.clear() Settings.DEFAULT_EXTENSION_TYPES.append( "tests.test_ipython_formatter.TestClipExtension") YuunoIPythonEnvironment.feature_classes = [ "yuuno_ipython.ipython.formatter.Formatter" ] self.shell = globalipapp.get_ipython() load_ipython_extension(self.shell) Yuuno.instance().output.icc_profile = None self.loaded = True
def setUp(self): Settings.DEFAULT_EXTENSION_TYPES.clear() Settings.DEFAULT_EXTENSION_TYPES.append( 'tests.test_ipython_namespace.TestExtension') YuunoIPythonEnvironment.feature_classes = [ "yuuno_ipython.ipython.namespace.Namespace" ] self.shell = globalipapp.get_ipython() load_ipython_extension(self.shell) self.loaded = True self.yuuno = Yuuno.instance()
def setUpClass(cls): """Set up an IPython session just once. It'd be safer to set it up for each test, but for now, I'm mimicking the IPython team's logic. """ if not sys.stdin.encoding: # needed for py.test sys.stdin = codecs.getreader("utf-8")(sys.stdin) cls.ip = get_ipython() # This is just to get a minimally modified version of the changes # working cls.ip.run_line_magic("load_ext", "oct2py.ipython") cls.ip.ex("import numpy as np") cls.svgs_generated = 0
def setup_class(cls): cls.ip = get_ipython() cls.ip.run_cell('import random') cls.ip.run_cell('import numpy as np') if 'USE_OCTAVE' in os.environ: matlab = 'octave' else: matlab = 'matlab' # We will test the passing of kwargs through to the Matlab or Octave # objects, by assigning the socket address out here: socket_addr = "tcp://127.0.0.1" if sys.platform == "win32" else "ipc:///tmp/pymatbridge-%s"%str(uuid4()) pymat.load_ipython_extension(cls.ip, matlab=matlab, socket_addr=socket_addr)
def test_init(self): ip = get_ipython() ip.run_line_magic('load_ext', 'line_profiler') ip.run_cell(raw_cell='def func():\n return 2**20') lprof = ip.run_line_magic('lprun', '-r -f func func()') timings = lprof.get_stats().timings self.assertEqual(len(timings), 1) # 1 function func_data, lines_data = next(iter(timings.items())) self.assertEqual(func_data[1], 1) # lineno of the function self.assertEqual(func_data[2], "func") # function name self.assertEqual(len(lines_data), 1) # 1 line of code self.assertEqual(lines_data[0][0], 2) # lineno self.assertEqual(lines_data[0][1], 1) # hits
def test_ipython_magics(): """Test that the %aiida magic can be loaded and adds the QueryBuilder and Node variables.""" ipy = get_ipython() register_ipython_extension(ipy) cell = """ %aiida qb=QueryBuilder() qb.append(Node) qb.all() Dict().store() """ result = ipy.run_cell(cell) assert result.success
def test_myinput(): ip = get_ipython() test_cell = "foo\nbar" assert not ip.register_magic_function(replace_input, magic_kind="cell") assert not ip.run_cell_magic("replace_input", None, test_cell) for line in test_cell.split("\n"): c = ip.run_cell("input()") print(c.result) assert c.success assert c.result == line c = ip.run_cell("input()") assert not c.success assert isinstance(c.error_in_exec, StopIteration)
def setup_class(cls): cls.ip = get_ipython() cls.ip.run_cell('import random') cls.ip.run_cell('import numpy as np') if 'USE_OCTAVE' in os.environ: matlab = 'octave' else: matlab = 'matlab' # We will test the passing of kwargs through to the Matlab or Octave # objects, by assigning the socket address out here: socket_addr = "tcp://127.0.0.1" if sys.platform == "win32" else "ipc:///tmp/pymatbridge-%s" % str( uuid4()) pymat.load_ipython_extension(cls.ip, matlab=matlab, socket_addr=socket_addr)
def test_graph_notebook_config(self): ip = get_ipython() ip.magic('load_ext graph_notebook.magics') res: Configuration = ip.run_line_magic('graph_notebook_config', '') config_dict = res.to_dict() self.assertEqual(self.config.to_dict(), res.to_dict()) config_dict['host'] = 'this-was-changed' res2: Configuration = ip.run_cell_magic('graph_notebook_config', '', json.dumps(config_dict)) config_dict2 = res2.to_dict() res3: Configuration = ip.run_line_magic('graph_notebook_config', '') config_dict3 = res3.to_dict() self.assertEqual(config_dict2, config_dict3)
def _get_interpreter(): """ Get iPython interpreter. If it has been previously initialized, return it. Otherwise, start it. Further work: implement some mechanism to get an interpreter configured with some virtual environment or kernel. Returns ------- callable iPython interpreter. """ if not globals()['IPYTHON_INTERPRETER']: globals()['IPYTHON_INTERPRETER'] = get_ipython() return IPYTHON_INTERPRETER
def exec_line_magic(context, command): """Execute line magic function """ ip = get_ipython() ip.magic(command)
# third party import nose.tools as nt # our own packages from IPython.core import autocall from IPython.testing import tools as tt from IPython.testing.globalipapp import get_ipython from IPython.utils import py3compat #----------------------------------------------------------------------------- # Globals #----------------------------------------------------------------------------- # Get the public instance of IPython ip = get_ipython() failures = [] num_tests = 0 #----------------------------------------------------------------------------- # Test functions #----------------------------------------------------------------------------- class CallableIndexable(object): def __getitem__(self, idx): return True def __call__(self, *args, **kws): return True
"""Tests for input manipulation machinery.""" #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- import nose.tools as nt from IPython.core.prefilter import AutocallChecker from IPython.testing import tools as tt, decorators as dec from IPython.testing.globalipapp import get_ipython #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- ip = get_ipython() @dec.parametric def test_prefilter(): """Test user input conversions""" # pairs of (raw, expected correct) input pairs = [ ('2+2','2+2'), ('>>> 2+2','2+2'), ('>>> # This is a comment\n' '... 2+2', '# This is a comment\n' '2+2'), # Some IPython input ('In [1]: 1', '1'), ('In [2]: for i in range(5):\n' ' ...: print i,',
def tearDownClass(cls) -> None: globalipapp.get_ipython().atexit_operations()
def setUpClass(self): self.ip = get_ipython() self.ip.magic('load_ext ipython_cells') self.ip.magic('load_file example.py')
def test_register_magics(julia): magic.load_ipython_extension(globalipapp.get_ipython())
def julia_magics(julia): return magic.JuliaMagics(shell=globalipapp.get_ipython())
def ipy_with_magic(julia): ip = get_ipython() magic.load_ipython_extension(ip) return ip