Python nose.tools.assert_in() Examples

The following are 30 code examples of nose.tools.assert_in(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module nose.tools , or try the search function .
Example #1
Source File: test_storemagic.py    From Computable with MIT License 6 votes vote down vote up
def test_store_restore():
    ip.user_ns['foo'] = 78
    ip.magic('alias bar echo "hello"')
    tmpd = tempfile.mkdtemp()
    ip.magic('cd ' + tmpd)
    ip.magic('store foo')
    ip.magic('store bar')
    
    # Check storing
    nt.assert_equal(ip.db['autorestore/foo'], 78)
    nt.assert_in('bar', ip.db['stored_aliases'])
    
    # Remove those items
    ip.user_ns.pop('foo', None)
    ip.alias_manager.undefine_alias('bar')
    ip.magic('cd -')
    ip.user_ns['_dh'][:] = []
    
    # Check restoring
    ip.magic('store -r')
    nt.assert_equal(ip.user_ns['foo'], 78)
    nt.assert_in('bar', ip.alias_manager.alias_table)
    nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh'])
    
    os.rmdir(tmpd) 
Example #2
Source File: test_completer.py    From Computable with MIT License 6 votes vote down vote up
def test_line_cell_magics():
    from IPython.core.magic import register_line_cell_magic

    @register_line_cell_magic
    def _bar_cellm(line, cell):
        pass
    
    ip = get_ipython()
    c = ip.Completer

    # The policy here is trickier, see comments in completion code.  The
    # returned values depend on whether the user passes %% or not explicitly,
    # and this will show a difference if the same name is both a line and cell
    # magic.
    s, matches = c.complete(None, '_bar_ce')
    nt.assert_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches)
    s, matches = c.complete(None, '%_bar_ce')
    nt.assert_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches)
    s, matches = c.complete(None, '%%_bar_ce')
    nt.assert_not_in('%_bar_cellm', matches)
    nt.assert_in('%%_bar_cellm', matches) 
Example #3
Source File: test_interactiveshell.py    From Computable with MIT License 6 votes vote down vote up
def test_var_expand_local(self):
        """Test local variable expansion in !system and %magic calls"""
        # !system
        ip.run_cell('def test():\n'
                    '    lvar = "ttt"\n'
                    '    ret = !echo {lvar}\n'
                    '    return ret[0]\n')
        res = ip.user_ns['test']()
        nt.assert_in('ttt', res)
        
        # %magic
        ip.run_cell('def makemacro():\n'
                    '    macroname = "macro_var_expand_locals"\n'
                    '    %macro {macroname} codestr\n')
        ip.user_ns['codestr'] = "str(12)"
        ip.run_cell('makemacro()')
        nt.assert_in('macro_var_expand_locals', ip.user_ns) 
Example #4
Source File: test_magic.py    From Computable with MIT License 6 votes vote down vote up
def test_file_amend():
    """%%file -a amends files"""
    ip = get_ipython()
    with TemporaryDirectory() as td:
        fname = os.path.join(td, 'file2')
        ip.run_cell_magic("file", fname, u'\n'.join([
            'line1',
            'line2',
        ]))
        ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
            'line3',
            'line4',
        ]))
        with open(fname) as f:
            s = f.read()
        nt.assert_in('line1\n', s)
        nt.assert_in('line3\n', s) 
Example #5
Source File: test_magic.py    From Computable with MIT License 6 votes vote down vote up
def test_alias_magic():
    """Test %alias_magic."""
    ip = get_ipython()
    mm = ip.magics_manager

    # Basic operation: both cell and line magics are created, if possible.
    ip.run_line_magic('alias_magic', 'timeit_alias timeit')
    nt.assert_in('timeit_alias', mm.magics['line'])
    nt.assert_in('timeit_alias', mm.magics['cell'])

    # --cell is specified, line magic not created.
    ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
    nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
    nt.assert_in('timeit_cell_alias', mm.magics['cell'])

    # Test that line alias is created successfully.
    ip.run_line_magic('alias_magic', '--line env_alias env')
    nt.assert_equal(ip.run_line_magic('env', ''),
                    ip.run_line_magic('env_alias', '')) 
Example #6
Source File: test_start_kernel.py    From Computable with MIT License 6 votes vote down vote up
def test_ipython_start_kernel_userns():
    cmd = ('from IPython import start_kernel\n'
           'ns = {"tre": 123}\n'
           'start_kernel(user_ns=ns)')

    with setup_kernel(cmd) as client:
        msg_id = client.object_info('tre')
        msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
        content = msg['content']
        assert content['found']
        nt.assert_equal(content['string_form'], u'123')

        # user_module should be an instance of DummyMod
        msg_id = client.execute("usermod = get_ipython().user_module")
        msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
        content = msg['content']
        nt.assert_equal(content['status'], u'ok')
        msg_id = client.object_info('usermod')
        msg = client.get_shell_msg(block=True, timeout=TIMEOUT)
        content = msg['content']
        assert content['found']
        nt.assert_in('DummyMod', content['string_form']) 
Example #7
Source File: test_rmagic.py    From Computable with MIT License 6 votes vote down vote up
def test_push_dataframe():
    from pandas import DataFrame
    rm = rmagic.RMagics(ip)
    df = DataFrame([{'a': 1, 'b': 'bar'}, {'a': 5, 'b': 'foo', 'c': 20}])
    ip.push({'df':df})
    ip.run_line_magic('Rpush', 'df')
    
    # This is converted to factors, which are currently converted back to Python
    # as integers, so for now we test its representation in R.
    sio = StringIO()
    rinterface.set_writeconsole(sio.write)
    try:
        rm.r('print(df$b[1])')
        nt.assert_in('[1] bar', sio.getvalue())
    finally:
        rinterface.set_writeconsole(None)
    
    # Values come packaged in arrays, so we unbox them to test.
    nt.assert_equal(rm.r('df$a[2]')[0], 5)
    missing = rm.r('df$c[1]')[0]
    assert np.isnan(missing), missing 
Example #8
Source File: test_magic.py    From Computable with MIT License 6 votes vote down vote up
def test_save():
    """Test %save."""
    ip = get_ipython()
    ip.history_manager.reset()   # Clear any existing history.
    cmds = [u"a=1", u"def b():\n  return a**2", u"print(a, b())"]
    for i, cmd in enumerate(cmds, start=1):
        ip.history_manager.store_inputs(i, cmd)
    with TemporaryDirectory() as tmpdir:
        file = os.path.join(tmpdir, "testsave.py")
        ip.run_line_magic("save", "%s 1-10" % file)
        with open(file) as f:
            content = f.read()
            nt.assert_equal(content.count(cmds[0]), 1)
            nt.assert_in('coding: utf-8', content)
        ip.run_line_magic("save", "-a %s 1-10" % file)
        with open(file) as f:
            content = f.read()
            nt.assert_equal(content.count(cmds[0]), 2)
            nt.assert_in('coding: utf-8', content) 
Example #9
Source File: test_asyncresult.py    From Computable with MIT License 6 votes vote down vote up
def test_await_data(self):
        """asking for ar.data flushes outputs"""
        self.minimum_engines(1)
        
        v = self.client[-1]
        ar = v.execute('\n'.join([
            "import time",
            "from IPython.kernel.zmq.datapub import publish_data",
            "for i in range(5):",
            "    publish_data(dict(i=i))",
            "    time.sleep(0.1)",
        ]), block=False)
        found = set()
        tic = time.time()
        # timeout after 10s
        while time.time() <= tic + 10:
            if ar.data:
                found.add(ar.data['i'])
                if ar.data['i'] == 4:
                    break
            time.sleep(0.05)
        
        ar.get(5)
        nt.assert_in(4, found)
        self.assertTrue(len(found) > 1, "should have seen data multiple times, but got: %s" % found) 
Example #10
Source File: test_action.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def test_harvest_job_create_as_sysadmin(self):
        source = factories.HarvestSource(**SOURCE_DICT.copy())

        site_user = toolkit.get_action('get_site_user')(
            {'model': model, 'ignore_auth': True}, {})['name']
        data_dict = {
            'source_id': source['id'],
            'run': True
            }
        job = toolkit.get_action('harvest_job_create')(
            {'user': site_user}, data_dict)

        assert_equal(job['source_id'], source['id'])
        assert_equal(job['status'], 'Running')
        assert_equal(job['gather_started'], None)
        assert_in('stats', job.keys()) 
Example #11
Source File: test_key_value_field.py    From django_model_helpers with MIT License 6 votes vote down vote up
def test_key_value_field():

    team = Team(name="Team1")
    test.assert_equal(team.options, {})
    team.options = "name = Ramast"
    test.assert_equal(team.options, {"name": "Ramast"})
    test.assert_equal(str(team.options), "name = Ramast\n")
    team.options = {"Age": 30}
    test.assert_equal(str(team.options), "Age = 30\n")
    # Notice int has been converted to string since we don't store value data type
    test.assert_equal(team.options, {"Age": "30"})
    team.options.update({"Name": "Ramast"})
    # Output should be
    #     Name = Ramast
    #     Age = 30
    # but since dictionary doesn't maintain order, I can't predict which one of the two lines will show first
    test.assert_in("Age = 30", str(team.options))
    test.assert_in("Name = Ramast", str(team.options))
    # Test invalid string
    try:
        team.options = "Name ?? Ramast"
        assert False, "Assigning invalid string should raise ValidationError"
    except ValidationError:
        pass 
Example #12
Source File: test_interaction.py    From pySINDy with MIT License 5 votes vote down vote up
def check_widgets(container, **to_check):
    """Check that widgets are created as expected"""
    # build a widget dictionary, so it matches
    widgets = {}
    for w in container.children:
        if not isinstance(w, Output):
            widgets[w.description] = w

    for key, d in to_check.items():
        nt.assert_in(key, widgets)
        check_widget(widgets[key], **d) 
Example #13
Source File: test_completer.py    From Computable with MIT License 5 votes vote down vote up
def test_func_kw_completions():
    ip = get_ipython()
    c = ip.Completer
    ip.ex('def myfunc(a=1,b=2): return a+b')
    s, matches = c.complete(None, 'myfunc(1,b')
    nt.assert_in('b=', matches)
    # Simulate completing with cursor right after b (pos==10):
    s, matches = c.complete(None, 'myfunc(1,b)', 10)
    nt.assert_in('b=', matches)
    s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
    nt.assert_in('b=', matches)
    #builtin function
    s, matches = c.complete(None, 'min(k, k')
    nt.assert_in('key=', matches) 
Example #14
Source File: test_choices.py    From django_model_helpers with MIT License 5 votes vote down vote up
def test_dir_method():
    choices1 = model_helpers.Choices({"X": 1, "Y": 2})
    tools.assert_in("X", dir(choices1))
    tools.assert_in("Y", dir(choices1))
    # parent attributes should also be mentioned
    tools.assert_in("items", dir(choices1)) 
Example #15
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_script_defaults():
    ip = get_ipython()
    for cmd in ['sh', 'bash', 'perl', 'ruby']:
        try:
            find_cmd(cmd)
        except Exception:
            pass
        else:
            nt.assert_in(cmd, ip.magics_manager.magics['cell']) 
Example #16
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_script_config():
    ip = get_ipython()
    ip.config.ScriptMagics.script_magics = ['whoda']
    sm = script.ScriptMagics(shell=ip)
    nt.assert_in('whoda', sm.magics['cell']) 
Example #17
Source File: test_redis_config.py    From stolos with Apache License 2.0 5 votes vote down vote up
def test_set_config(app1, cli, td):
    dct = {
        '1': '1',
        2: 2,
        1.1: 1.1,
        'a': 1,
        3: ['1', 2],
        4: {'a': 1, '1': '1', 2: 2}}

    # verify set_config does not delete old keys
    nt.assert_in('key1', td[app1])
    nt.assert_equal(1, td[app1]['key1'])
    td = RedisMapping()  # reset's RedisMapping's cache, from prev line
    set_config(app1, dct, cli=cli)
    nt.assert_in('key1', td[app1])
    nt.assert_equal(1, td[app1]['key1'])

    # verify set_config adds new keys
    nt.assert_equal(
        len(list(td[app1].keys())), len(list(dct.keys()) + ['key1']))
    nt.assert_true(all(
        x in (list(dct.keys()) + ['key1']) for x in td[app1].keys()))
    nt.assert_equal('1', td[app1]['1'])
    nt.assert_equal(2, td[app1][2])
    nt.assert_equal(1.1, td[app1][1.1])
    nt.assert_equal(1, td[app1]['a'])
    nt.assert_is_instance(
        td[app1][3], JSONSequence)
    nt.assert_is_instance(
        td[app1][4], JSONMapping)

    nt.assert_list_equal(list(td[app1][3]), dct[3])
    nt.assert_dict_equal(dict(td[app1][4]), dct[4]) 
Example #18
Source File: test_plugin.py    From ckanext-showcase with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_rich_text_editor_is_shown_when_configured(self):
        app = self._get_test_app()
        sysadmin = factories.Sysadmin()
        factories.Dataset(name='my-showcase', type='showcase')

        env = {'REMOTE_USER': sysadmin['name'].encode('ascii')}
        response = app.get(
            url=url_for(controller='ckanext.showcase.controller:ShowcaseController',
                        action='edit',
                        id='my-showcase'),
            extra_environ=env,
        )
        nosetools.assert_in('<textarea id="editor"', response.ubody) 
Example #19
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_file_var_expand():
    """%%file $filename"""
    ip = get_ipython()
    with TemporaryDirectory() as td:
        fname = os.path.join(td, 'file1')
        ip.user_ns['filename'] = fname
        ip.run_cell_magic("file", '$filename', u'\n'.join([
            'line1',
            'line2',
        ]))
        with open(fname) as f:
            s = f.read()
        nt.assert_in('line1\n', s)
        nt.assert_in('line2', s) 
Example #20
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_file():
    """Basic %%file"""
    ip = get_ipython()
    with TemporaryDirectory() as td:
        fname = os.path.join(td, 'file1')
        ip.run_cell_magic("file", fname, u'\n'.join([
            'line1',
            'line2',
        ]))
        with open(fname) as f:
            s = f.read()
        nt.assert_in('line1\n', s)
        nt.assert_in('line2', s) 
Example #21
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_numpy_reset_array_undec():
    "Test '%reset array' functionality"
    _ip.ex('import numpy as np')
    _ip.ex('a = np.empty(2)')
    nt.assert_in('a', _ip.user_ns)
    _ip.magic('reset -f array')
    nt.assert_not_in('a', _ip.user_ns) 
Example #22
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_magic_magic():
    """Test %magic"""
    ip = get_ipython()
    with capture_output() as captured:
        ip.magic("magic")
    
    stdout = captured.stdout
    nt.assert_in('%magic', stdout)
    nt.assert_in('IPython', stdout)
    nt.assert_in('Available', stdout) 
Example #23
Source File: test_plugin.py    From ckanext-showcase with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_custom_div_content_is_used_with_ckeditor(self):
        app = self._get_test_app()
        sysadmin = factories.Sysadmin()
        factories.Dataset(name='my-showcase', type='showcase')

        env = {'REMOTE_USER': sysadmin['name'].encode('ascii')}
        response = app.get(
            url=url_for(controller='ckanext.showcase.controller:ShowcaseController',
                        action='read',
                        id='my-showcase'),
            extra_environ=env,
        )
        nosetools.assert_in('<div class="ck-content">', response.ubody) 
Example #24
Source File: test_magic.py    From Computable with MIT License 5 votes vote down vote up
def test_macro():
    ip = get_ipython()
    ip.history_manager.reset()   # Clear any existing history.
    cmds = ["a=1", "def b():\n  return a**2", "print(a,b())"]
    for i, cmd in enumerate(cmds, start=1):
        ip.history_manager.store_inputs(i, cmd)
    ip.magic("macro test 1-3")
    nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
    
    # List macros
    nt.assert_in("test", ip.magic("macro")) 
Example #25
Source File: test_completer.py    From Computable with MIT License 5 votes vote down vote up
def test_cell_magics():
    from IPython.core.magic import register_cell_magic

    @register_cell_magic
    def _foo_cellm(line, cell):
        pass
    
    ip = get_ipython()
    c = ip.Completer

    s, matches = c.complete(None, '_foo_ce')
    nt.assert_in('%%_foo_cellm', matches)
    s, matches = c.complete(None, '%%_foo_ce')
    nt.assert_in('%%_foo_cellm', matches) 
Example #26
Source File: test_completer.py    From Computable with MIT License 5 votes vote down vote up
def test_line_magics():
    ip = get_ipython()
    c = ip.Completer
    s, matches = c.complete(None, 'lsmag')
    nt.assert_in('%lsmagic', matches)
    s, matches = c.complete(None, '%lsmag')
    nt.assert_in('%lsmagic', matches) 
Example #27
Source File: common.py    From python-tabulate with MIT License 5 votes vote down vote up
def assert_in(result, expected_set):
        nums = xrange(1, len(expected_set)+1)
        for i, expected in zip(nums, expected_set):
            print("Expected %d:\n%s\n" % (i, expected))
        print("Got:\n%s\n" % result)
        assert result in expected_set 
Example #28
Source File: test_magic_terminal.py    From Computable with MIT License 5 votes vote down vote up
def test_paste_leading_commas(self):
        "Test multiline strings with leading commas"
        tm = ip.magics_manager.registry['TerminalMagics']
        s = '''\
a = """
,1,2,3
"""'''
        ip.user_ns.pop('foo', None)
        tm.store_or_execute(s, 'foo')
        nt.assert_in('foo', ip.user_ns) 
Example #29
Source File: nose_assert_methods.py    From Computable with MIT License 5 votes vote down vote up
def assert_in(item, collection):
    assert item in collection, '%r not in %r' % (item, collection) 
Example #30
Source File: tools.py    From Computable with MIT License 5 votes vote down vote up
def help_all_output_test(subcommand=''):
    """test that `ipython [subcommand] --help-all` works"""
    cmd = ' '.join(get_ipython_cmd() + [subcommand, '--help-all'])
    out, err, rc = get_output_error_code(cmd)
    nt.assert_equal(rc, 0, err)
    nt.assert_not_in("Traceback", err)
    nt.assert_in("Options", out)
    nt.assert_in("Class parameters", out)
    return out, err