Format: text/x-python
⬇ Download File (2.0 KB)
   1  from IPython.utils.capture import capture_output
   2  
   3  import pytest
   4  
   5  def test_alias_lifecycle():
   6      name = 'test_alias1'
   7      cmd = 'echo "Hello"'
   8      am = _ip.alias_manager
   9      am.clear_aliases()
  10      am.define_alias(name, cmd)
  11      assert am.is_alias(name)
  12      assert am.retrieve_alias(name) == cmd
  13      assert (name, cmd) in am.aliases
  14      
  15      # Test running the alias
  16      orig_system = _ip.system
  17      result = []
  18      _ip.system = result.append
  19      try:
  20          _ip.run_cell('%{}'.format(name))
  21          result = [c.strip() for c in result]
  22          assert result == [cmd]
  23      finally:
  24          _ip.system = orig_system
  25      
  26      # Test removing the alias
  27      am.undefine_alias(name)
  28      assert not am.is_alias(name)
  29      with pytest.raises(ValueError):
  30          am.retrieve_alias(name)
  31      assert (name, cmd) not in am.aliases
  32      
  33  
  34  def test_alias_args_error():
  35      """Error expanding with wrong number of arguments"""
  36      _ip.alias_manager.define_alias('parts', 'echo first %s second %s')
  37      # capture stderr:
  38      with capture_output() as cap:
  39          _ip.run_cell('parts 1')
  40  
  41      assert cap.stderr.split(":")[0] == "UsageError"
  42  
  43  
  44  def test_alias_args_commented():
  45      """Check that alias correctly ignores 'commented out' args"""
  46      _ip.run_line_magic("alias", "commentarg echo this is %%s a commented out arg")
  47  
  48      with capture_output() as cap:
  49          _ip.run_cell("commentarg")
  50  
  51      # strip() is for pytest compat; testing via iptest patch IPython shell
  52      # in testing.globalipapp and replace the system call which messed up the
  53      # \r\n
  54      assert cap.stdout.strip() ==  'this is %s a commented out arg'
  55  
  56  def test_alias_args_commented_nargs():
  57      """Check that alias correctly counts args, excluding those commented out"""
  58      am = _ip.alias_manager
  59      alias_name = 'comargcount'
  60      cmd = 'echo this is %%s a commented out arg and this is not %s'
  61      
  62      am.define_alias(alias_name, cmd)
  63      assert am.is_alias(alias_name)
  64      
  65      thealias = am.get_alias(alias_name)
  66      assert thealias.nargs == 1
  67