Example #1
0
def exception_handler_targets_cannot_be_accessed_from_nested_function():
    target_node = nodes.ref("error")
    ref_node = nodes.ref("error")
    body = [nodes.ret(ref_node)]
    func_node = nodes.func("f", nodes.arguments([]), body, type=None)
    try_node = nodes.try_(
        [],
        handlers=[
            nodes.except_(nodes.none(), target_node, [func_node])
        ],
    )
    
    declaration = name_declaration.ExceptionHandlerTargetNode("error")
    references = References([
        (target_node, declaration),
        (ref_node, declaration),
        (func_node, name_declaration.VariableDeclarationNode("f")),
    ])
    
    try:
        _updated_bindings(try_node, references=references)
        assert False, "Expected error"
    except errors.UnboundLocalError as error:
        assert_equal(ref_node, error.node)
        assert_is("error", error.name)
Example #2
0
    def test_lowess_regression(self):

        p = lm._RegressionPlotter("x", "y", data=self.df, lowess=True)
        grid, yhat, err_bands = p.fit_regression(x_range=(-3, 3))

        nt.assert_equal(len(grid), len(yhat))
        nt.assert_is(err_bands, None)
Example #3
0
    def test_establish_variables_from_series(self):

        p = lm._LinearPlotter()
        p.establish_variables(None, x=self.df.x, y=self.df.y)
        pdt.assert_series_equal(p.x, self.df.x)
        pdt.assert_series_equal(p.y, self.df.y)
        nt.assert_is(p.data, None)
 def test_no_github_link(self):
     self.repo.index.commit('my root commit')
     self.commit_detail.options = {'commit': True, 'no_github_link': True}
     self.repo.create_remote('origin', self.commit_detail.github_nonce_url)
     nodes = self.commit_detail.run()
     list_markup = BeautifulSoup(str(nodes[0]), features='xml')
     assert_is(list_markup.reference, None)
Example #5
0
def test_create_basic():
    assert_is(type(std_bal), Balance)
    assert_equal(len(std_bal), len(movements))
    assert len(std_bal) == 3
    assert_equal(std_bal[0]['money'], 100)
    assert_equal(std_bal[1]['money'], 0)
    assert_equal(std_bal[2]['money'], -20)
Example #6
0
 def test_access_component_by_index(self):
     m = self.model
     g1 = hs.model.components.Gaussian()
     g2 = hs.model.components.Gaussian()
     g2.name = "test"
     m.extend((g1, g2))
     nt.assert_is(m[1], g2)
Example #7
0
def test_ExecutionTimeExternalsProtocol(path1, path2):

    timer_protocol = ExecutionTimeExternalsProtocol()
    runner = Runner(protocol=timer_protocol)

    # test external command:
    cmd = ['git', 'init']
    os.mkdir(path1)
    runner.run(cmd, cwd=path1)
    assert_equal(len(timer_protocol), 1, str(runner.protocol))
    assert_equal(cmd, timer_protocol[0]['command'])
    ok_(timer_protocol[0]['end'] >= timer_protocol[0]['start'])
    ok_(timer_protocol[0]['duration'] >= 0)
    assert_is(timer_protocol[0]['exception'], None)

    # now with exception, since path2 doesn't exist yet:
    try:
        runner.run(cmd, cwd=path2)
    except Exception as e:
        catched_exception = e
    finally:
        assert_equal(len(timer_protocol), 2)
        assert_equal(cmd, timer_protocol[1]['command'])
        ok_(timer_protocol[1]['end'] >= timer_protocol[1]['start'])
        ok_(timer_protocol[1]['duration'] >= 0)
        assert_is(timer_protocol[1]['exception'], catched_exception)

    # test callable (no entry added):
    new_runner = Runner(cwd=path2, protocol=timer_protocol)
    git_repo = GitRepo(path2, runner=new_runner)
    assert_equal(len(timer_protocol), 2)
Example #8
0
def test_connect_systems():
    '''check the connect_systems routine'''
    r = sysdiag.System('root')
    s1 = sysdiag.System('s1', parent=r)
    s2 = sysdiag.System('s2') # parent is None 
    # add some ports
    s1.add_port(sysdiag.Port('p1', 'type1'))
    s2.add_port(sysdiag.Port('p2', 'type1'))
    p_other = sysdiag.Port('p_other', 'other type')
    s2.add_port(p_other)

    # failure if no common parents
    with assert_raises(ValueError):
        w1 = sysdiag.connect_systems(s1,s2, 'p1', 'p2')
    r.add_subsystem(s2)
    w1 = sysdiag.connect_systems(s1,s2, 'p1', 'p2')
    assert_equal(len(w1.ports), 2)

    # failure if wrong types of ports:
    assert_equal(w1.is_connect_allowed(p_other, 'sibling'), False)
    with assert_raises(TypeError):
        w = sysdiag.connect_systems(s1,s2, 'p1', 'p_other')

    # double connection: no change is performed
    w2 = sysdiag.connect_systems(s1,s2, 'p1', 'p2')
    assert_is(w2,w1)
    assert_equal(len(w1.ports), 2)
Example #9
0
def test_from_json():
    '''basic test of JSON deserialization'''
    s_json = '''{
      "__class__": "sysdiag.System",
      "__sysdiagclass__": "System",
      "name": "my syst",
      "params": {},
      "ports": [],
      "subsystems": [],
      "wires": []
    }'''
    s = sysdiag.json_load(s_json)
    assert_is(type(s), sysdiag.System)
    assert_equal(s.name, "my syst")

    # Test a port:
    p_json = '''{
      "__class__": "sysdiag.Port",
      "__sysdiagclass__": "Port",
      "name": "my port",
      "type": ""
    }'''
    p = sysdiag.json_load(p_json)
    assert_is(type(p), sysdiag.Port)
    assert_equal(p.name, "my port")

    # Test a wire:
    w_json = '''{
Example #10
0
def class_definition_base_classes_are_resolved():
    ref = nodes.ref("object")
    node = nodes.class_("User", [], base_classes=[ref])
    
    declarations = _create_declarations(["User", "object"])
    references = resolve(node, declarations)
    assert_is(declarations.declaration("object"), references.referenced_declaration(ref))
 def test_get_site_notification_impressions_under(self, request, response, SiteNotification):
     note = SiteNotification.current.return_value
     note._id = 'deadbeef'
     note.impressions = 2
     request.cookies = {'site-notification': 'deadbeef-1-false'}
     assert_is(ThemeProvider().get_site_notification(), note)
     response.set_cookie.assert_called_once_with('site-notification', 'deadbeef-2-False', max_age=timedelta(days=365))
def test_with_out_keyword():
    """Test with out keyword."""
    out = np.empty((1, 4))
    rtn = rmg.calculate_gradient_across_cell_corners(
        values_at_nodes, 5, out=out)
    assert_is(rtn, out)
    assert_array_equal(out, np.array([[6., 4., -6., -4.]]) / np.sqrt(2))
Example #13
0
 def test_getitem(self):
     assert_is_not(self.adjview[1], self.s[1])
     assert_is(self.adjview[0][7], self.adjview[0][3])
     assert_equal(self.adjview[2]['key']['color'], 1)
     assert_equal(self.adjview[2][1]['span'], 2)
     assert_raises(KeyError, self.adjview.__getitem__, 4)
     assert_raises(KeyError, self.adjview[1].__getitem__, 'key')
Example #14
0
    def test_computeDescriptor_validType_existingVector_overwrite(self):
        expected_image_type = 'image/png'
        expected_existing_vector = numpy.random.randint(0, 100, 10)
        expected_new_vector = numpy.random.randint(0, 100, 10)
        expected_uuid = "a unique ID"

        # Set up mock classes/responses
        mDataElement = mock.Mock(spec=smqtk.representation.DataElement)
        m_data = mDataElement()
        m_data.content_type.return_value = expected_image_type
        m_data.uuid.return_value = expected_uuid

        mDescrElement = mock.Mock(spec=smqtk.representation.DescriptorElement)
        mDescrElement().has_vector.return_value = True
        mDescrElement().vector.return_value = expected_existing_vector

        mDescriptorFactory = mock.Mock(spec=smqtk.representation.DescriptorElementFactory)
        m_factory = mDescriptorFactory()
        m_factory.new_descriptor.return_value = mDescrElement()

        cd = DummyDescriptorGenerator()
        cd.valid_content_types = mock.Mock(return_value={expected_image_type})
        cd._compute_descriptor = mock.Mock(return_value=expected_new_vector)

        # Call: matching content types, existing descriptor for data
        d = cd.compute_descriptor(m_data, m_factory, overwrite=True)

        ntools.assert_false(mDescrElement().has_vector.called)
        ntools.assert_true(cd._compute_descriptor.called)
        cd._compute_descriptor.assert_called_once_with(m_data)
        ntools.assert_true(mDescrElement().set_vector.called)
        mDescrElement().set_vector.assert_called_once_with(expected_new_vector)
        ntools.assert_is(d, mDescrElement())
Example #15
0
    def test_regplot_scatter_kws_alpha(self):

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_is(ax.collections[0]._alpha, None)
        nt.assert_equal(ax.collections[0]._facecolors[0, 3], 0.5)

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_equal(ax.collections[0]._alpha, 0.8)

        f, ax = plt.subplots()
        color = np.array([[0.3, 0.8, 0.5]])
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color,
                                                        'alpha': 0.4})
        nt.assert_equal(ax.collections[0]._alpha, 0.4)

        f, ax = plt.subplots()
        color = 'r'
        ax = lm.regplot("x", "y", self.df, scatter_kws={'color': color})
        nt.assert_equal(ax.collections[0]._alpha, 0.8)

        plt.close("all")
Example #16
0
    def test_request_is_passed_through_on_post(self):
        request = object()
        form = FlatCommentMultiForm(self.content_object, self.user, data={'comment': 'Works!'})
        form.post(request)

        tools.assert_equals(1, len(self._posted))
        tools.assert_is(request, self._posted[0][1]['request'])
Example #17
0
    def test_array_init(self):

        # normal initialization
        store = dict()
        init_array(store, shape=100, chunks=10)
        a = Array(store)
        assert_is_instance(a, Array)
        eq((100,), a.shape)
        eq((10,), a.chunks)
        eq('', a.path)
        assert_is_none(a.name)
        assert_is(store, a.store)

        # initialize at path
        store = dict()
        init_array(store, shape=100, chunks=10, path='foo/bar')
        a = Array(store, path='foo/bar')
        assert_is_instance(a, Array)
        eq((100,), a.shape)
        eq((10,), a.chunks)
        eq('foo/bar', a.path)
        eq('/foo/bar', a.name)
        assert_is(store, a.store)

        # store not initialized
        store = dict()
        with assert_raises(KeyError):
            Array(store)

        # group is in the way
        store = dict()
        init_group(store, path='baz')
        with assert_raises(KeyError):
            Array(store, path='baz')
def test_lookup_by_type():
    f = PlainTextFormatter()
    f.for_type(C, foo_printer)
    nt.assert_is(f.lookup_by_type(C), foo_printer)
    type_str = '%s.%s' % (C.__module__, 'C')
    with nt.assert_raises(KeyError):
        f.lookup_by_type(A)
Example #19
0
def test_initialize_reset_scheme():
	solver = Solver(Scheme_init_once(.1), System(f))
	solver.initialize(u0=1., name='first')
	nt.assert_is(solver.current_scheme, None)
	solver.run(1.)
	solver.initialize(u0=2.,name='second')
	solver.run(1.)
Example #20
0
 def test_get_component_by_component(self):
     m = self.model
     g1 = hs.model.components.Gaussian()
     g2 = hs.model.components.Gaussian()
     g2.name = "test"
     m.extend((g1, g2))
     nt.assert_is(m._get_component(g2), g2)
def test_translationservice():
    """Test TranslationService prototype."""
    machine = TranslationService()
    assert_is_instance(machine._state, ExampleLayer)

    # Test ExampleLayer with chord
    event = ProtoKeyEvent(event='down', switch_vector=[1, 0, 1], is_chord=True)
    expected_char = 'c'
    expected_event = 'down'

    observed_char, observed_event = machine.process_protokey_event(event)

    assert_equals(expected_char, observed_char)
    assert_equals(expected_event, observed_event)

    # Test ExampleLayer with single switch
    event = ProtoKeyEvent(event='up', switch_vector=[0, 1, 0], is_chord=True)
    expected_char = 'd'
    expected_event = 'up'

    observed_char, observed_event = machine.process_protokey_event(event)

    assert_equals(expected_char, observed_char)
    assert_equals(expected_event, observed_event)

    # Do a reset
    event = ProtoKeyEvent(
        event='reset',
        switch_vector=[1, 1, 1],
        is_chord=True)
    expected_char = 'EmptyKey'
    expected_event = 'reset'

    observed_char, observed_event = machine.process_protokey_event(event)

    assert_equals(expected_char, observed_char)
    assert_equals(expected_event, observed_event)

    # This should be ignored - accumulating!
    event = ProtoKeyEvent(
        event='down',
        switch_vector=[1, 0, 0],
        is_chord=False)
    observed = machine.process_protokey_event(event)
    assert_is(observed, None)

    # Switch layer (right now there's no key for that!)
    machine._state = ExampleNonChordedLayer()

    event = ProtoKeyEvent(
        event='down',
        switch_vector=[0, 0, 1],
        is_chord=False)
    expected_char = 'c'
    expected_event = 'down'

    observed_char, observed_event = machine.process_protokey_event(event)

    assert_equals(expected_char, observed_char)
    assert_equals(expected_event, observed_event)
Example #22
0
def test_unpack_frame_of_data_natnet2700():
    expected_rb = [
        (-0.053690, 0.099419, -1.398518),
        (0.047905, 0.115714, -1.436263),
        (0.023839, 0.072290, -1.388070)]

    expected_om = [
        (-0.254053, 0.055445, -1.432309),
        (-0.281266, 0.049510, -1.421349)]

    for i in range(1, 1 + 2):
        with open("test/data/frame-motive-1.7.2-%03d.bin" % i, "rb") as f:
            binary = f.read()
            parsed = rx.unpack(binary, (2, 7, 0, 0))
            print(parsed)
            assert_is(type(parsed), rx.FrameOfData)
            assert_in(parsed.frameno, [411213, 411214, 411215])
            assert_in(b"all", parsed.sets)
            assert_in(b"Rigid Body 1", parsed.sets)
            assert_almost_equal(parsed.sets[b"Rigid Body 1"], expected_rb, 4)
            assert_equal(parsed.rigid_bodies[0].mrk_ids, (1, 2, 3))
            assert_equal(len(parsed.other_markers), 2)
            assert_almost_equal(parsed.other_markers, expected_om, 3)
            assert_equal(parsed.skeletons, [])
            assert_equal(len(parsed.labeled_markers), 3)
Example #23
0
def compare_grad_implementations(*args, **kwargs):
  results = {}
  for method in ["theano_op", "naive", "theano_cpu"]:
    m = globals()["%s_multi_batch_beam_grad" % method]
    try:
      res = m(*args, **kwargs)
    except NotImplementedError:
      pass
    else:
      results[method] = res
  assert len(results) > 1
  for k, v in sorted(results.items()):
    print("bwd %s:" % k)
    print(v)
  reference = sorted(results.keys())[0]
  for k in sorted(results.keys())[1:]:
    assert_equal(len(results[k]), len(results[reference]))
    for i in range(len(results[k])):
      if i > 0: break  # XXX: This is for D_pad_left / D_pad_right...
      if results[k][i] is None or results[reference][i] is None:
        assert_is(results[k][i], results[reference][i])
        continue
      assert_equal(results[k][i].shape, results[reference][i].shape)
      # The summation of the grad can be quite numerically unstable, thus the low decimal.
      numpy.testing.assert_almost_equal(results[k][i], results[reference][i], decimal=4)
  return results[reference]
Example #24
0
 def test_root_graph(self):
     G = self.Graph([(0, 1), (1, 2)])
     assert_is(G, G.root_graph)
     DG = G.to_directed(as_view=True)
     SDG = DG.subgraph([0, 1])
     RSDG = SDG.reverse(copy=False)
     assert_is(G, RSDG.root_graph)
def test_lookup():
    f = PlainTextFormatter()

    f.for_type(C, foo_printer)
    nt.assert_is(f.lookup(C()), foo_printer)
    with nt.assert_raises(KeyError):
        f.lookup(A())
Example #26
0
 def _test():
     rmg = RasterModelGrid(4, 5)
     number_of_elements = rmg.number_of_elements(element)
     rtn_values = rmg.add_ones(element, 'name')
     assert_is(rtn_values, rmg.field_values(element, 'name'))
     assert_array_equal(
         rtn_values, np.ones(number_of_elements, dtype=np.float))
Example #27
0
    def test_annotation(self):

        g = dist.jointplot("x", "y", self.data)
        nt.assert_equal(len(g.ax_joint.legend_.get_texts()), 1)

        g = dist.jointplot("x", "y", self.data, stat_func=None)
        nt.assert_is(g.ax_joint.legend_, None)
Example #28
0
    def test_model_navigation_indexer_slice(self):
        self.model.axes_manager.indices = (0, 0)
        self.model[0].active = False

        # Make sure the array we copy has been appropriatelly updated before
        # slicing
        _test = self.model[0]._active_array[0, 0]
        while _test:
            time.sleep(0.1)
            _test = self.model[0]._active_array[0, 0]

        m = self.model.inav[0::2]
        np.testing.assert_array_equal(
            m.chisq.data, self.model.chisq.data[:, 0::2])
        np.testing.assert_array_equal(m.dof.data, self.model.dof.data[:, 0::2])
        nt.assert_is(m.inav[:2][0].A.ext_force_positive,
                     m[0].A.ext_force_positive)
        nt.assert_equal(m.chisq.data.shape, (4, 2))
        nt.assert_false(m[0]._active_array[0, 0])
        for ic, c in enumerate(m):
            np.testing.assert_equal(
                c._active_array,
                self.model[ic]._active_array[:, 0::2])
            for p_new, p_old in zip(c.parameters, self.model[ic].parameters):
                nt.assert_true((p_old.map[:, 0::2] == p_new.map).all())
Example #29
0
def import_multiple_aliases_using_same_name_resolve_to_same_node():
    declarations = _create_declarations(["x"])
    first_alias_node = nodes.import_alias("x.y", None)
    second_alias_node = nodes.import_alias("x", None)
    node = nodes.Import([first_alias_node, second_alias_node])
    references = resolve(node, declarations)
    assert_is(references.referenced_declaration(first_alias_node), references.referenced_declaration(second_alias_node))
Example #30
0
def test_with_mixins():
    # Testing model metaclass with mixins
    class FieldsMixin(object):
        """Toy class for field testing"""
        field_a = Integer(scope=Scope.settings)

    class BaseClass(object):
        """Toy class for ModelMetaclass testing"""
        __metaclass__ = ModelMetaclass

    class ChildClass(FieldsMixin, BaseClass):
        """Toy class for ModelMetaclass and field testing"""
        pass

    class GrandchildClass(ChildClass):
        """Toy class for ModelMetaclass and field testing"""
        pass

    # `ChildClass` and `GrandchildClass` both obtain the `fields` attribute
    # from the `ModelMetaclass`. Since this is not understood by static analysis,
    # silence this error for the duration of this test.
    # pylint: disable=E1101

    assert hasattr(ChildClass, 'field_a')
    assert_is(ChildClass.field_a, ChildClass.fields['field_a'])

    assert hasattr(GrandchildClass, 'field_a')
    assert_is(GrandchildClass.field_a, GrandchildClass.fields['field_a'])
Example #31
0
def test_lookup_by_type_string():
    f = PlainTextFormatter()
    type_str = '%s.%s' % (C.__module__, 'C')
    f.for_type(type_str, foo_printer)
    
    # verify insertion
    nt.assert_in(_mod_name_key(C), f.deferred_printers)
    nt.assert_not_in(C, f.type_printers)
    
    nt.assert_is(f.lookup_by_type(type_str), foo_printer)
    # lookup by string doesn't cause import
    nt.assert_in(_mod_name_key(C), f.deferred_printers)
    nt.assert_not_in(C, f.type_printers)
    
    nt.assert_is(f.lookup_by_type(C), foo_printer)
    # should move from deferred to imported dict
    nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
    nt.assert_in(C, f.type_printers)
Example #32
0
    def test_from_iterable(self):
        # from list
        expected_list = [[0.4, 0], [1, 1.123], [2.253, 4.768124]]
        ea = EigenArray.from_iterable(expected_list, target_shape=(3, 2))
        numpy.testing.assert_array_equal(ea, expected_list)

        # from ndarray
        expected_ndar = numpy.array(expected_list)
        ea = EigenArray.from_iterable(expected_ndar, target_shape=(3, 2))
        numpy.testing.assert_array_equal(ea, expected_ndar)

        # from EigenArray, which should return the input object
        ea = EigenArray(3, 2)
        ea[:] = expected_list
        ea2 = EigenArray.from_iterable(ea, target_shape=(3, 2))
        numpy.testing.assert_array_equal(ea2, ea)
        ntools.assert_is(ea, ea2)
        ntools.assert_true(ea is ea2)
Example #33
0
def test_parse_script_with_existing_cache(parse_mock):
    name = 'foo'
    content = ""
    cache = {name: object()}
    script = parse_script(
        name=name,
        content=content,
        cache=cache,
    )

    assert_is(parse_mock.return_value, script)
    parse_mock.assert_called_once_with(
        name=name,
        content=content,
        script_class=ANY,
        get_script_by_name=ANY,
    )
    assert_equal({name: parse_mock.return_value}, cache)
Example #34
0
def test_check_phi():
    """Tests the _check_phi function"""
    numeaf = 175

    def set_phi(f):
        tm.phi = f

    # First check that None is properly converted
    tm._phi = None
    assert_is(tm.phi, None)
    tm.phi = np.ones(numeaf)
    assert_array_equal(tm.phi, np.ones(numeaf))
    # Check that incorrect number of entries raises an exception
    assert_raises(ValueError, set_phi, np.ones((50, 1)))
    # Check that a negative entry raises an exception
    x = np.ones(numeaf)
    x[123] = -1
    assert_raises(ValueError, set_phi, x)
Example #35
0
def test_display_id():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle = display.display('x')
        nt.assert_is(handle, None)
        handle = display.display('y', display_id='secret')
        nt.assert_is_instance(handle, display.DisplayHandle)
        handle2 = display.display('z', display_id=True)
        nt.assert_is_instance(handle2, display.DisplayHandle)
    nt.assert_not_equal(handle.display_id, handle2.display_id)

    nt.assert_equal(pub.call_count, 3)
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('y')
            },
            'metadata': {},
            'transient': {
                'display_id': handle.display_id,
            },
        })
    args, kwargs = pub.call_args_list[2]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('z')
            },
            'metadata': {},
            'transient': {
                'display_id': handle2.display_id,
            },
        })
Example #36
0
    def test_model_signal_indexer_slice(self):
        s = self.model.signal.isig[:300]
        m = self.model.isig[:300]
        m1 = self.model.isig[300:]
        m2 = self.model.isig[:0.]
        nt.assert_is(m1[0].A.ext_bounded, m[0].A.ext_bounded)
        np.testing.assert_array_almost_equal(s.data, m.signal.data)
        np.testing.assert_array_almost_equal(s.data, m2.signal.data)
        np.testing.assert_array_equal(m.dof.data, self.model.dof.data)
        for ic, c in enumerate(m):
            for p_new, p_old in zip(c.parameters, self.model[ic].parameters):
                np.testing.assert_array_equal(p_old.map, p_new.map)
        np.testing.assert_array_almost_equal(m.chisq.data + m1.chisq.data,
                                             self.model.chisq.data)

        self.model.channel_switches[0] = False
        m = self.model.isig[:-100.]
        nt.assert_false(m.channel_switches[0])
        nt.assert_true(np.all(m.channel_switches[1:]))
Example #37
0
def test_geom_basics():
    # mock the validd aes and get the geom to accept the color
    # mapping -> only subclasses normally declare which aes mappings
    # are valid and geom.DEFAULT_AES is a empty list
    geom.DEFAULT_AES = {"color": None}
    g = geom(data=meat)
    assert_is(meat, g.data)
    g = geom(meat)
    assert_is(meat, g.data)
    g = geom(aes(color="beef"))
    assert_equal("beef", g.aes["color"])
    g = geom(mapping=aes(color="pork"))
    assert_equal("pork", g.aes["color"])
    with assert_raises(Exception):
        g = geom(aes(color="beef"), mapping=aes(color="pork"))
    assert_equal("pork", g.aes["color"])
    # setting, not mapping
    g = geom(color="blue")
    assert_equal("blue", g.manual_aes["color"])
Example #38
0
def test_parse_argstring_or_throw():
    parse_argstring = MagicMock(side_effect=UsageError('OOGABOOGABOOGA'))
    try:
        parse_argstring_or_throw(MagicMock(),
                                 MagicMock(),
                                 parse_argstring=parse_argstring)
        assert False
    except BadUserDataException as e:
        assert_equals(str(e), str(parse_argstring.side_effect))

    parse_argstring = MagicMock(
        side_effect=ValueError('AN UNKNOWN ERROR HAPPENED'))
    try:
        parse_argstring_or_throw(MagicMock(),
                                 MagicMock(),
                                 parse_argstring=parse_argstring)
        assert False
    except ValueError as e:
        assert_is(e, parse_argstring.side_effect)
Example #39
0
    def test_to_node(self):
        rmg = RasterModelGrid((4, 5), spacing=(1., 1.))
        rmg.add_empty('node', 'values')

        node_values = rmg.at_node['values']
        node_values[:] = np.arange(rmg.number_of_nodes)

        link_values = maps.map_link_tail_node_to_link(rmg, 'values')

        assert_array_equal(
            link_values,
            np.array([
                0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8, 9, 10, 11,
                12, 13, 10, 11, 12, 13, 14, 15, 16, 17, 18
            ]))
        out = np.empty_like(link_values)
        rtn = maps.map_link_tail_node_to_link(rmg, 'values', out=out)
        assert_array_equal(out, link_values)
        assert_is(rtn, out)
Example #40
0
    def test_view1(self):
        # Intantiate a view with no selected interface and select one after
        window = enaml.widgets.api.Window()
        core = self.workbench.get_plugin('enaml.workbench.core')
        view = SetDcVoltageView(window, task=self.task, core=core)
        window.show()

        process_app_events()

        assert_in('YokogawaGS200', view.drivers)
        self.task.selected_driver = 'YokogawaGS200'
        process_app_events()
        assert_is(self.task.interface, None)

        assert_in('TinyBilt', view.drivers)
        self.task.selected_driver = 'TinyBilt'
        process_app_events()
        assert_is_instance(self.task.interface,
                           MultiChannelVoltageSourceInterface)
Example #41
0
    def test_to_dictionary(self):
        m = self.model
        d = m.as_dictionary()

        print(d['low_loss'])
        np.testing.assert_almost_equal(m.low_loss.data, d['low_loss']['data'])
        np.testing.assert_almost_equal(m.chisq.data, d['chisq.data'])
        np.testing.assert_almost_equal(m.dof.data, d['dof.data'])
        np.testing.assert_equal(d['free_parameters_boundaries'],
                                m.free_parameters_boundaries)
        nt.assert_is(d['convolved'], m.convolved)

        for num, c in enumerate(m):
            tmp = c.as_dictionary()
            remove_empty_numpy_strings(tmp)
            nt.assert_equal(d['components'][num]['name'], tmp['name'])
            nt.assert_equal(d['components'][num]['_id_name'], tmp['_id_name'])
        np.testing.assert_equal(d['components'][-1]['signal1D'],
                                (m.signal * 0.3)._to_dictionary())
Example #42
0
 def test_periodic_and_combos(self):
     assert_equal((self.pvolA & self.pvolB),
                  volume.PeriodicCVDefinedVolume(op_id, 50, 75))
     assert_equal((self.pvolA & self.pvolB)(60), True)
     assert_equal((self.pvolA & self.pvolB)(80), False)
     assert_equal((self.pvolB & self.pvolC), volume.EmptyVolume())
     assert_equal((self.pvolC & self.pvolB), volume.EmptyVolume())
     assert_is((self.pvolA & self.pvolA), self.pvolA)
     assert_equal((self.pvolA & self.pvolA_), volume.EmptyVolume())
     assert_equal((self.pvolE & self.pvolD), self.pvolD)
     # go to special case for cyclic permutation
     assert_equal((self.pvolB & self.pvolD), self.pvolB)
     # go to special case
     assert_equal((self.pvolE & self.pvolA_),
                  volume.UnionVolume(
                      volume.PeriodicCVDefinedVolume(op_id, -150, -100),
                      volume.PeriodicCVDefinedVolume(op_id, 75, 150)))
     # go to super if needed
     assert_equal(type(self.pvolA & volA), volume.IntersectionVolume)
Example #43
0
    def test_assert_remove_add_all(self):
        """Test if removing/adding all the entries works"""
        for entry in self.fstab.entries:
            assert_is(self.fstab.remove_entry(entry), True)

        for device in (
                'sda',
                'sdb',
                'sdc',
        ):
            self.fstab.add_entry(
                Fstab.Entry('/dev/%s' % device, '/mnt/%s' % device, 'ext3',
                            None))

        self.fstab.add_entry(
            Fstab.Entry('UUID=3af44368-c50b-4768-8e58-aff003cef8be', '/',
                        'ext4', 'errors=remount-ro', 0, 1))

        assert_equal(sorted(GENERATED_FSTAB_FILE.splitlines()),
                     sorted(str(entry) for entry in self.fstab.entries))
Example #44
0
File: tests.py Project: fvbehr/cmdx
def test_nodereuse():
    """Node re-use works ok"""

    import cmdx
    nodeA = cmdx.createNode("transform", name="myNode")
    nodeB = cmdx.createNode("transform", parent=nodeA)
    assert_is(cmdx.encode("|myNode"), nodeA)
    assert_is(nodeB.parent(), nodeA)

    with tempdir() as tmp:
        fname = os.path.join(tmp, "myScene.ma")
        cmds.file(rename=fname)
        cmds.file(save=True, type="mayaAscii")
        cmds.file(fname, open=True, force=True)

        # On scene open, the current scene is closed, triggering
        # the nodeDestroyed callback which invalidates the node
        # for cmdx. Upon encoding this node anew, cmdx will
        # allocate a new instance for it.
        assert_is_not(cmdx.encode("|myNode"), nodeA)
Example #45
0
def test_geom_basics():
    # mock the validd aes and get the geom to accept the color
    # mapping -> only subclasses normally declare which aes mappings
    # are valid and geom.VALID_AES is a empty list
    geom.VALID_AES = ["color"]
    g = geom(data=meat)
    assert_is(meat, g.data)
    g = geom(meat)
    assert_is(meat, g.data)
    g = geom(aes(color="beef"))
    assert_equal("beef", g.aes["color"])
    g = geom(mapping=aes(color="pork"))
    assert_equal("pork", g.aes["color"])
    # It would probably be better to throw an exception if
    # two aes are given...
    g = geom(aes(color="beef"), mapping=aes(color="pork"))
    assert_equal("pork", g.aes["color"])
    # setting, not mapping
    g = geom(color="blue")
    assert_equal("blue", g.manual_aes["color"])
Example #46
0
    def test_life_cycle1(self):
        """ Test life cycle: auto_show on, proxy active on closing.

        """
        assert_false(Window.windows)
        self.monitor.start(None)
        process_app_events()
        assert_true(self.monitor._view.proxy_is_active)
        assert_true(Window.windows)

        self.monitor._view.minimize()
        process_app_events()
        self.monitor.show_monitor(None)
        process_app_events()
        assert_false(self.monitor._view.is_minimized())

        self.monitor.stop()
        process_app_events()
        assert_false(Window.windows)
        assert_is(self.monitor._view, None)
Example #47
0
    def test_enum_behavior(self):
        e = enum(['one', 'two', 'three'])

        # case-insensitive level name and level value may all
        # be used for equality comparisons.
        assert_equal(e.one, 'one')
        assert_equal(e.one, 'ONE')
        assert_equal(e.one, 0)
        assert_not_equal(e.one, '0')

        # ditto for enum membership tests
        assert_in('one', e.levels)
        assert_in(2, e.levels)
        assert_not_in('five', e.levels)

        # The same level object returned, only when
        # passing in a valid level name/value.
        assert_is(e('one'), e('ONE'))
        assert_is(e('one'), e(0))
        assert_raises(ValueError, e, 'five')
Example #48
0
def test_iter():
    mats = {
        0: Material({
            'H1': 1.0,
            'K39': 1.0
        }, density=42.0),
        1: Material({
            'H1': 0.1,
            'O16': 1.0
        }, density=43.0),
        2: Material({'He4': 42.0}, density=44.0),
        3: Material({'Tm171': 171.0}, density=45.0),
    }
    m = gen_mesh(mats=mats)
    j = 0
    idx_tag = m.mesh.tag_get_handle('idx')
    for i, mat, ve in m:
        assert_equal(j, i)
        assert_is(mats[i], mat)
        assert_equal(j, m.mesh.tag_get_data(idx_tag, ve, flat=True)[0])
        j += 1
Example #49
0
    def test_get_page_elements_and_web_elements(self):
        self.driver_wrapper.driver.find_elements.return_value = child_elements
        inputs = LoginPageObject().inputs
        page_elements = inputs.page_elements
        web_elements = inputs.web_elements

        # Check that find_elements has been called just one time
        self.driver_wrapper.driver.find_elements.assert_called_once_with(
            By.XPATH, '//input')
        self.driver_wrapper.driver.find_element.assert_not_called()

        # Check that the response is a list of 2 PageElement with the expected web element
        assert_equal(len(page_elements), 2)
        assert_is_instance(page_elements[0], PageElement)
        assert_equal(page_elements[0]._web_element, child_elements[0])
        assert_is_instance(page_elements[1], PageElement)
        assert_equal(page_elements[1]._web_element, child_elements[1])

        # Check that web_elements are the same elements as page_element._web_element
        assert_is(web_elements[0], page_elements[0]._web_element)
        assert_is(web_elements[1], page_elements[1]._web_element)
Example #50
0
def test_iter():
    mats = {
        0: Material({
            'H1': 1.0,
            'K39': 1.0
        }, density=42.0),
        1: Material({
            'H1': 0.1,
            'O16': 1.0
        }, density=43.0),
        2: Material({'He4': 42.0}, density=44.0),
        3: Material({'Tm171': 171.0}, density=45.0),
    }
    m = gen_mesh(mats=mats)
    j = 0
    idx_tag = m.mesh.getTagHandle('idx')
    for i, mat, ve in m:
        assert_equal(j, i)
        assert_is(mats[i], mat)
        assert_equal(j, idx_tag[ve])
        j += 1
Example #51
0
def test_pop_string():
    f = PlainTextFormatter()
    type_str = '%s.%s' % (C.__module__, 'C')

    with nt.assert_raises(KeyError):
        f.pop(type_str)

    f.for_type(type_str, foo_printer)
    f.pop(type_str)
    with nt.assert_raises(KeyError):
        f.lookup_by_type(C)
    with nt.assert_raises(KeyError):
        f.pop(type_str)

    f.for_type(C, foo_printer)
    nt.assert_is(f.pop(type_str, None), foo_printer)
    with nt.assert_raises(KeyError):
        f.lookup_by_type(C)
    with nt.assert_raises(KeyError):
        f.pop(type_str)
    nt.assert_is(f.pop(type_str, None), None)
Example #52
0
def test_pop():
    f = PlainTextFormatter()
    f.for_type(C, foo_printer)
    nt.assert_is(f.lookup_by_type(C), foo_printer)
    nt.assert_is(f.pop(C, None), foo_printer)
    f.for_type(C, foo_printer)
    nt.assert_is(f.pop(C), foo_printer)
    with nt.assert_raises(KeyError):
        f.lookup_by_type(C)
    with nt.assert_raises(KeyError):
        f.pop(C)
    with nt.assert_raises(KeyError):
        f.pop(A)
    nt.assert_is(f.pop(A, None), None)
Example #53
0
def test_add_ones_return_value():
    fields = ModelDataFields()
    fields.new_field_location('node', 12)
    fields.new_field_location('cell', 2)

    rtn_value = fields.add_ones('z', at='node')
    assert_array_equal(rtn_value, np.ones(12))
    assert_is(rtn_value, fields['node']['z'])
    assert_is(rtn_value, fields.field_values('node', 'z'))

    rtn_value = fields.add_ones('z', at='cell')
    assert_array_equal(rtn_value, np.ones(2))
    assert_is(rtn_value, fields['cell']['z'])
    assert_is(rtn_value, fields.field_values('cell', 'z'))
Example #54
0
    def test_restricted_induced_subgraph_chains(self):
        """ Test subgraph chains that both restrict and show nodes/edges.

        A restricted_view subgraph should allow induced subgraphs using
        G.subgraph that automagically without a chain (meaning the result
        is a subgraph view of the original graph not a subgraph-of-subgraph.
        """
        hide_nodes = [3, 4, 5]
        hide_edges = [(6, 7)]
        RG = nx.restricted_view(self.G, hide_nodes, hide_edges)
        nodes = [4, 5, 6, 7, 8]
        SG = nx.induced_subgraph(RG, nodes)
        SSG = RG.subgraph(nodes)
        assert_is(RG._graph, self.G)
        assert_is(SSG._graph, self.G)
        assert_is(SG._graph, RG)
        assert_edges_equal(SG.edges, SSG.edges)
        # should be same as morphing the graph
        CG = self.G.copy()
        CG.remove_nodes_from(hide_nodes)
        CG.remove_edges_from(hide_edges)
        assert_edges_equal(CG.edges(nodes), SSG.edges)
        CG.remove_nodes_from([0, 1, 2, 3])
        assert_edges_equal(CG.edges, SSG.edges)
        # switch order: subgraph first, then restricted view
        SSSG = self.G.subgraph(nodes)
        RSG = nx.restricted_view(SSSG, hide_nodes, hide_edges)
        assert_is_not(RSG._graph, self.G)
        assert_edges_equal(RSG.edges, CG.edges)
Example #55
0
def test_get_backend():
    """ Generate tests to get various backends """
    # We use a hand generated list here to ensure that we are getting what we
    # expect
    backends = {
        'json': results.JSONBackend,
    }

    check = lambda n, i: nt.assert_is(results.get_backend(n), i)

    for name, inst in backends.iteritems():
        check.description = 'get_backend({0}) returns {0} backend'.format(name)
        yield check, name, inst
Example #56
0
    def test_col_wrap(self):

        g = ag.FacetGrid(self.df, col="d")
        nt.assert_equal(g.axes.shape, (1, 10))
        nt.assert_is(g.facet_axis(0, 8), g.axes[0, 8])

        g_wrap = ag.FacetGrid(self.df, col="d", col_wrap=4)
        nt.assert_equal(g_wrap.axes.shape, (10, ))
        nt.assert_is(g_wrap.facet_axis(0, 8), g_wrap.axes[8])
        nt.assert_equal(g_wrap._ncol, 4)
        nt.assert_equal(g_wrap._nrow, 3)

        with nt.assert_raises(ValueError):
            g = ag.FacetGrid(self.df, row="b", col="d", col_wrap=4)

        df = self.df.copy()
        df.loc[df.d == "j"] = np.nan
        g_missing = ag.FacetGrid(df, col="d")
        nt.assert_equal(g_missing.axes.shape, (1, 9))

        g_missing_wrap = ag.FacetGrid(df, col="d", col_wrap=4)
        nt.assert_equal(g_missing_wrap.axes.shape, (9, ))
Example #57
0
    def test_plugin_find_next_measure2(self):
        """ Test plugin.find_next_measure when measures should be skipped.

        """
        plugin = self.workbench.get_plugin(u'hqc_meas.measure')
        measure1 = Measure(plugin=plugin, name='Test1')
        measure1.root_task = RootTask()
        measure1.status = 'SKIPPED'
        plugin.enqueued_measures.append(measure1)

        measure2 = Measure(plugin=plugin, name='Test2')
        measure2.root_task = RootTask()
        measure2.status = 'EDITING'
        plugin.enqueued_measures.append(measure2)

        measure3 = Measure(plugin=plugin, name='Test3')
        measure3.root_task = RootTask()
        measure3.status = 'READY'
        plugin.enqueued_measures.append(measure3)

        meas = plugin.find_next_measure()
        assert_is(measure3, meas)
Example #58
0
 def test_different_shapes(self):
     im = self.im
     imt = im.deepcopy()
     angles = hs.signals.BaseSignal([0, 45])
     for s, t in zip([im, imt], [False, True]):
         s.map(rotate, angle=angles.T, reshape=True, show_progressbar=None,
               parallel=t)
         # the dtype
         nt.assert_is(s.data.dtype, np.dtype('O'))
         # the special slicing
         nt.assert_is(s.inav[0].data.base, s.data[0])
         # actual values
         np.testing.assert_allclose(s.data[0],
                                    np.arange(9.).reshape((3, 3)),
                                    atol=1e-7)
         np.testing.assert_allclose(s.data[1],
                                    np.array([[0.,   0.,   0.,   0.],
                                              [0.,  10.34834957,
                                                  13.88388348,   0.],
                                              [0.,  12.11611652,
                                                  15.65165043,   0.],
                                              [0.,   0.,   0.,   0.]]))
Example #59
0
def test_trim_disconnected():
    # 3 connected components, one disconnected (state 4)

    for arr_type in ARR_TYPES:
        given = arr_type([[1, 2, 0, 0],
                          [2, 1, 0, 1],
                          [0, 0, 1, 0],
                          [0, 1, 0, 2]])

        mapping, trimmed = trim_disconnected(given)
        assert_is(type(trimmed), type(given))

        expected_tcounts = np.array([[1, 2, 0],
                                     [2, 1, 1],
                                     [0, 1, 2]])

        try:
            trimmed = trimmed.toarray()
        except AttributeError:
            pass

        assert_array_equal(trimmed, expected_tcounts)

        expected_mapping = TrimMapping([(0, 0), (1, 1), (3, 2)])
        assert_equal(mapping, expected_mapping)

        mapping, trimmed = trim_disconnected(given, threshold=2)

        try:
            trimmed = trimmed.toarray()
        except AttributeError:
            pass

        expected_tcounts = np.array([[1, 2],
                                     [2, 1]])
        assert_array_equal(trimmed, expected_tcounts)

        expected_mapping = TrimMapping([(0, 0), (1, 1)])
        assert_equal(mapping, expected_mapping)
Example #60
0
 def test_graph_chain(self):
     G = self.Graph([(0, 1), (1, 2)])
     DG = G.to_directed(as_view=True)
     SDG = DG.subgraph([0, 1])
     RSDG = SDG.reverse(copy=False)
     assert_is(G, DG._graph)
     assert_is(DG, SDG._graph)
     assert_is(SDG, RSDG._graph)