def test_enqueue_measure4(self): # Test enqueueing a measure passing the tests using instruments. core = self.workbench.get_plugin(u'enaml.workbench.core') cmd = u'enaml.workbench.ui.select_workspace' core.invoke_command(cmd, {'workspace': u'hqc_meas.measure.workspace'}, self) plugin = self.workbench.get_plugin(u'hqc_meas.measure') false_instr_user = FalseInstrTask(selected_profile=' dummy ', selected_driver='PanelTestDummy') measure = Measure(plugin=plugin, name='Test') measure.root_task = RootTask(default_path=self.test_dir) measure.root_task.children_task = [false_instr_user] plugin.edited_measure = measure res = plugin.workspace.enqueue_measure(plugin.edited_measure) assert_true(res) assert_false(measure.root_task.run_time) assert_true(plugin.enqueued_measures) en_meas = plugin.enqueued_measures[0] assert_is_not(en_meas, measure) assert_equal(en_meas.status, 'READY') assert_equal(en_meas.infos, 'The measure is ready to be performed by an engine.') assert_in('build_deps', en_meas.store) assert_equal([' dummy '], en_meas.store['profiles']) assert_in('drivers', en_meas.root_task.run_time) instr_plugin = self.workbench.get_plugin('hqc_meas.instr_manager') assert_in(' dummy ', instr_plugin.available_profiles)
def runTest(self): log.debug('sys.stdout is the initial value: {}'.format( sys.stdout is _cached_stdout)) assert_is_not(sys.stdout, _cached_stdout) # sys.stdout should be replaced log.debug('sleeping {} seconds'.format(wait)) time.sleep(wait)
def test_execute(self): cm = ComputationManager() df = pd.DataFrame(np.random.randn(30, 3), columns=['a', 'bob', 'c']) source = "df.rolling(5).sum()" entry = cm_get(cm, source, locals(), globals()) # execute first time val = cm.execute(entry) correct = df.rolling(5).sum() nt.assert_is_not(val, correct) tm.assert_frame_equal(val, correct) # execute again should return existing value val2 = cm.execute(entry) nt.assert_is(val, val2) entry2 = cm_get(cm, source, locals(), globals()) nt.assert_is(entry, entry2) nt.assert_true(entry2.executed) # override keyword val3 = cm.execute(entry, override=True) nt.assert_is_not(val, val3) tm.assert_frame_equal(val, val3) cm = ComputationManager()
def test_pickle_func(): def f(x): return x + 23 assert_equal(f(1), 24) f2 = unpickle(pickle(f)) assert_is_not(f, f2) assert_equal(f(2), 25)
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(SSG.root_graph, SSG._graph) assert_is_not(SG.root_graph, SG._graph) 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.root_graph, RSG._graph) assert_edges_equal(RSG.edges, CG.edges)
def test_no_data_leak(): cols_before = diamonds.columns.copy() import numpy as np p = ggplot(aes(x="np.log(price)"), data=diamonds) cols_after = diamonds.columns.copy() assert_same_elements(cols_before, cols_after) assert_is_not(diamonds, p.data)
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')
def test_remap(): src = np.array([1, 2, 3, 4]) mapping = np.array([-1, 10, 20, 30, 40]) rtn = remap(src, mapping) assert_array_equal(rtn, [10, 20, 30, 40]) assert_is_not(rtn, src)
def test_getslice_lazy(self): seq = self.get_sequence([1, 2, 3]) sliced = seq[:2] tools.assert_is_not(sliced, seq) tools.assert_items_equal(sliced, [1, 2]) tools.assert_true(seq.iterable) tools.eq_(list(seq._results.__iter__()), [1, 2])
def test_driver_reload(self): # Test reloading a driver. self.workbench.register(InstrManagerManifest()) self.workbench.register(InstrUser1()) core = self.workbench.get_plugin(u'enaml.workbench.core') com = u'hqc_meas.instr_manager.driver_types_request' d_types, _ = core.invoke_command(com, {'driver_types': ['Dummy']}, self) com = u'hqc_meas.instr_manager.drivers_request' drivers, _ = core.invoke_command(com, {'drivers': ['PanelTestDummy']}, self) com = u'hqc_meas.instr_manager.reload_driver' re_driver = core.invoke_command(com, {'driver': 'PanelTestDummy'}, self) assert_is_not(re_driver, drivers['PanelTestDummy']) assert_equal(re_driver.__name__, 'PanelTestDummy') com = u'hqc_meas.instr_manager.driver_types_request' re_d_types, _ = core.invoke_command(com, {'driver_types': ['Dummy']}, self) assert_is_not(re_d_types['Dummy'], d_types['Dummy']) assert_equal(re_d_types['Dummy'].__name__, 'DummyInstrument')
def test_enqueue_measure1(self): # Test enqueueing a measure passing the tests using no instruments. core = self.workbench.get_plugin(u'enaml.workbench.core') cmd = u'enaml.workbench.ui.select_workspace' core.invoke_command(cmd, {'workspace': u'hqc_meas.measure.workspace'}, self) plugin = self.workbench.get_plugin(u'hqc_meas.measure') measure = Measure(plugin=plugin, name='Test') measure.root_task = RootTask(default_path=self.test_dir) plugin.edited_measure = measure res = plugin.workspace.enqueue_measure(plugin.edited_measure) assert_true(res) assert_false(measure.root_task.run_time) assert_true(plugin.enqueued_measures) en_meas = plugin.enqueued_measures[0] assert_is_not(en_meas, measure) assert_equal(en_meas.status, 'READY') assert_equal(en_meas.infos, 'The measure is ready to be performed by an engine.') assert_in('build_deps', en_meas.store) assert_not_in('profiles', en_meas.store)
def test_copy_msg(self): x = NetParameter() assert_is_not_none(x) y = pu.copy_msg(x, NetParameter) assert_is_not(x, y) assert_is_not_none(y)
def test_flip_copy(): x = np.arange(12.0) y = sgrid.reshape_array((3, 4), x, flip_vertically=True, copy=True) assert_equal(y.shape, (3, 4)) assert_array_equal(y, np.array([[8.0, 9.0, 10.0, 11.0], [4.0, 5.0, 6.0, 7.0], [0.0, 1.0, 2.0, 3.0]])) assert_true(y.flags["C_CONTIGUOUS"]) assert_is_not(y.base, x)
def test_set_with_save_preserves_identity(self): first_get = self.get() self.set(self.new_value) self.block.save() second_get = self.get() assert_is(self.new_value, second_get) assert_is_not(first_get, second_get)
def test_set_preserves_identity(self): first_get = self.get() assert_is_not(self.new_value, first_get) self.set(self.new_value) second_get = self.get() assert_is(self.new_value, second_get) assert_is_not(first_get, second_get)
def test_retrieval(self): user = self.User.items.create(uid=123) token = self.Token(uid=123, token='abc') tools.assert_not_in('_user_cache', vars(token)) tools.eq_(dict(token), {'uid': 123, 'token': 'abc'}) tools.eq_(token.user, user) tools.assert_is_not(token.user, user) tools.assert_in('_user_cache', vars(token))
def test_duplicate_creation(self): db = create(db="test").database.create() db2 = create(db="test").database.create() assert_is_not(db, None) assert_is_not(db2, None) # assert_equal(db, db2) db.delete() db2.delete()
def test_deep_const(self): l = [1, 2, 3] assert_is_not(SD(l)(), l) (SD(l).append(_))(4) not_formula_and_eq(l, [1, 2, 3]) (SC(l).append(_))(4) not_formula_and_eq(l, [1, 2, 3, 4])
def test_get_value_copy(): model = BmiHeat() model.initialize() z0 = model.get_value('plate_surface__temperature') z1 = model.get_value('plate_surface__temperature') assert_is_not(z0, z1) assert_array_almost_equal(z0, z1)
def list_comprehension_generator_is_not_in_same_scope_as_element(): target = nodes.ref("target") ref = nodes.ref("target") iterable = nodes.ref("target") node = nodes.list_comprehension(target, ref, iterable) declarations = _create_declarations(["target"]) references = resolve(node, declarations) assert_is_not(references.referenced_declaration(target), references.referenced_declaration(iterable))
def class_definitions_assignments_shadow_variables_of_same_name_in_outer_scope(): ref = nodes.ref("x") body = [nodes.assign([ref], nodes.none())] node = nodes.class_("User", body) declarations = _create_declarations(["x", "User"]) references = resolve(node, declarations) assert_is_not(declarations.declaration("x"), references.referenced_declaration(ref))
def test_geom_with_data(): gg = ggplot(mtcars, aes("wt", "mpg")) + geom_point() cols_before = gg.data.columns.copy() _text = geom_text(aes(label="name"), data=mtcars[mtcars.cyl == 6]) g2 = gg + _text # Datasets are shared between ggplot objects but it is not allowed to change the columns in a # dataset after the initial ggplot(aes) call. assert_is_not(g2.data, mtcars, "Adding a dataset to a geom changed the data in ggplot") assert_same_elements(cols_before, g2.data.columns)
def test_flip_copy(): x = np.arange(12.) y = sgrid.reshape_array((3, 4), x, flip_vertically=True, copy=True) assert_equal(y.shape, (3, 4)) assert_array_equal(y, np.array([[8., 9., 10., 11.], [4., 5., 6., 7.], [0., 1., 2., 3.]])) assert_true(y.flags['C_CONTIGUOUS']) assert_is_not(y.base, x)
def function_definitions_assignments_shadow_variables_of_same_name_in_outer_scope(): args = nodes.arguments([]) ref = nodes.ref("x") body = [nodes.assign([ref], nodes.none())] node = nodes.func("f", args, body, type=None) declarations = _create_declarations(["x", "f"]) references = resolve(node, declarations) assert_is_not(declarations.declaration("x"), references.referenced_declaration(ref))
def test_clip_x_infinite(): """ Test correctly clipping (-inf, 0, inf, 10) with (-inf, -inf, inf, inf) """ box1 = Box(Rectangle(-inf, -inf, inf, inf)) box2 = Box(Rectangle(-inf, 0, inf, 10)) clipped = box1.clip(box2) assert_is_not(clipped, Box.empty_box) assert_equals(clipped.rect, (-inf, 0, inf, 10))
def test_miss_cache(self): with NamedTemporaryFile() as f: f.write("meh") f.flush() s3.upload_image(f.name, self.uri) f = s3.get_image(self.uri, use_cache=True) assert_is_not(f, None) assert_equal(f.read(), "meh") f.close()
def test_only_generate_classes_once(self): assert_is( self.mixologist.mix(FieldTester), self.mixologist.mix(FieldTester), ) assert_is_not( self.mixologist.mix(FieldTester), self.mixologist.mix(TestXBlock), )
def test_clip_identity(): """ Test clipping a box with itself results in the same box """ box1 = Box(Rectangle(-inf, -inf, inf, inf)) box2 = Box(Rectangle(-inf, -inf, inf, inf)) clipped = box1.clip(box2) assert_is_not(clipped, Box.empty_box) assert_equals(clipped.rect, box1.rect)
def test_replace_change_shape(self): """When a descriptor changes the shape, the old item must be discarded and ``None`` used in its place. The version must be bumped.""" ig = spead2.ItemGroup() ig.add_item(0x1000, 'item 1', 'item 1', (), np.int32, value=np.int32(4)) item1 = ig[0x1000] item1_version = item1.version ig.add_item(0x1000, 'item 1', 'bigger', (3, 4), np.int32) assert_is_not(item1, ig[0x1000]) assert_is_none(ig[0x1000].value) assert_greater(ig[0x1000].version, item1_version)
def _test_copy_state(defn, initialize_fn, bind_fn): Y = toy_dataset(defn) view = cxx_numpy_dataview(Y) r = rng() state = initialize_fn(defn, view, r) state_shallow = copy.copy(state) state_deep = copy.deepcopy(state) assert_is_not(state, state_shallow) assert_is_not(state, state_deep) _assert_copy(state, state_shallow, bind_fn, view, r) _assert_copy(state, state_deep, bind_fn, view, r)
ax = sns.heatmap(data, vmax=50000, annot=True, fmt='g') #Sets the tite and labels plt.title('Confusion matrix for kNN (k=48)') plt.yticks(r, ['Delayed', 'Not delayed']) plt.xticks(r, ['Not delayed', 'Delayed']) return ax # In[92]: ax = plot_confusion() # In[93]: assert_equal(isinstance(ax, mpl.axes.Axes), True, msg="Your function should return a matplotlib.axes.Axes object.") texts = [t.get_text() for t in ax.texts] assert_equal(texts, ['10558', '3370', '52604', '1725']) x_tick_labels = [l.get_text() for l in ax.get_xticklabels()] y_tick_labels = [l.get_text() for l in ax.get_yticklabels()] assert_equal(y_tick_labels, ['Delayed', 'Not delayed']) assert_is_not(len(ax.title.get_text()), 0, msg="Your plot doesn't have a title.") # In[ ]:
# In[5]: rug_no_jitter = plot_rugplot(df=local, jitter=0, seed=0) # In[6]: assert_is_instance(rug_no_jitter, mpl.axes.Axes) assert_equal(len(rug_no_jitter.lines), len(local)) for i in range(len(local)): xdata, ydata = rug_no_jitter.lines[i].get_xydata().T assert_array_equal(xdata, local.iloc[i, 0]) assert_equal(ydata[1] - ydata[0] > 0, True) assert_is_not(rug_no_jitter.xaxis.get_label_text(), '', msg="Change the x-axis label to something more descriptive.") # A rug plot with random jitter. Adding jitter improves visualization. # In[7]: rug_jittered = plot_rugplot(df=local, jitter=0.1, seed=0) # In[8]: assert_equal(len(rug_jittered.lines), len(local)) np.random.seed(0) for i in range(len(local)): xdata, ydata = rug_jittered.lines[i].get_xydata().T
def test_duplicate(self): fpath = os.path.join(os.path.dirname(ROOT_PKG_PATH), TEST_DATA_DIRNAME, TEST_NET_FILENAME) n1 = Parser().from_net_params_file(fpath) n2 = Parser().from_net_params_file(fpath) n1_tmp = NetParameter(); n1_tmp.CopyFrom(n1) n2_tmp = NetParameter(); n2_tmp.CopyFrom(n2) s = mrg.merge_indep_net_spec([n1_tmp, n2_tmp]) assert_is_not_none(s) assert_is_instance(s, str) assert_greater(len(s), 0) n = NetParameter() text_format.Merge(s, n) assert_is_not_none(n) # Data Layer from first network for l in n.layer: if l.type.lower() == 'data': for l1 in n1.layer: if l1.type.lower() == 'data': dat_phase = [x.phase for x in l.include] # compare test with test and train with train if dat_phase == [x.phase for x in l1.include]: assert_is_not(l.top, l1.top) assert_list_equal(list(l.top), list(l1.top)) assert_equal(l.data_param.source, l1.data_param.source) assert_equal(l.data_param.backend, l1.data_param.backend) assert_equal(l.data_param.batch_size, l1.data_param.batch_size) assert_equal(l.transform_param.scale, l1.transform_param.scale) # For non-data layers # back up merged net for ni in [n1, n2]: for l1 in ni.layer: found = False if l1.type.lower() != 'data': for l in n.layer: if l.type.lower() == l1.type.lower() and \ [t.split('_nidx')[0] for t in l.top] == list(l1.top) and \ [b.split('_nidx')[0] for b in l.bottom] == list(l1.bottom): assert_true(l.name.startswith(l1.name)) fnames1 = [f.name for f in l1.DESCRIPTOR.fields] fnames = [f.name for f in l.DESCRIPTOR.fields] assert_list_equal(fnames, fnames1) l.ClearField('name') l.ClearField('top') l.ClearField('bottom') l1.ClearField('name') l1.ClearField('top') l1.ClearField('bottom') assert_equal(text_format.MessageToString(l), text_format.MessageToString(l1)) found = True else: continue # skip for data layers assert_true(found, "Failed to find %s in merged network!" % (l1.name,))
def test_get_entry_by_device_attr(self): """Test if the get_entry_by_attr method works for device attr""" for device in ('sda', 'sdb', 'sdc', ): assert_is_not(self.fstab.get_entry_by_attr('device', '/dev/%s' % device), None)
def test_geom_with_data(): gg = ggplot(mtcars, aes("wt", "mpg")) + geom_point() cols_before = gg.data.columns.copy() _text = geom_text(aes(label="name"), data=mtcars[mtcars.cyl == 6]) g2 = gg + _text assert_is_not(g2.data, _text.data, "Adding a dataset to a geom replaced the data in ggplot")
# In[46]: vc = plot_validation_curve(f_selected, c, check_random_state(0)) # In[47]: assert_is_instance( vc, mpl.axes.Axes, msg="Your function should return a matplotlib.axes.Axes object.") assert_equal(len(vc.lines), 2) assert_is_not(len(vc.title.get_text()), 0, msg="Your plot doesn't have a title.") assert_is_not(vc.xaxis.get_label_text(), '', msg="Change the x-axis label to something more descriptive.") assert_is_not(vc.yaxis.get_label_text(), '', msg="Change the y-axis label to something more descriptive.") # check lines x_train, y_train = vc.lines[0].get_xydata().T assert_array_almost_equal(x_train, np.arange(1, 20)) assert_array_almost_equal(y_train, [ 0.22635556, 0.38835901, 0.54027221, 0.60997869, 0.71045737, 0.7825216, 0.84086324, 0.91471541, 0.94298356, 0.9663274, 0.9742014, 0.97935748, 0.97663546, 0.98165637, 0.99128017, 0.98225592, 0.98481485, 0.98539211,
def test_stack_copy(self): """Should create an exact of the PDA stack.""" stack = PDAStack(['a', 'b']) stack_copy = stack.copy() nose.assert_is_not(stack, stack_copy) nose.assert_equal(stack, stack_copy)
def test_getitem(self): assert_is_not(self.adjview[1], self.adj[1]) assert_is(self.adjview[3][0][3], self.adjview[0][3][3]) assert_equal(self.adjview[3][2][3]['color'], 1) assert_raises(KeyError, self.adjview.__getitem__, 4)
ax.set_title('Attributes not scaled') return ax # In[10]: naive_var = plot_naive_variance(pca_naive) # In[11]: assert_is_instance(naive_var, mpl.axes.Axes) assert_equal(len(naive_var.lines), 1) assert_is_not(len(naive_var.title.get_text()), 0, msg="Your plot doesn't have a title.") assert_is_not(naive_var.xaxis.get_label_text(), '', msg="Change the x-axis label to something more descriptive.") assert_is_not(naive_var.yaxis.get_label_text(), '', msg="Change the y-axis label to something more descriptive.") xdata, ydata = naive_var.lines[0].get_xydata().T assert_array_equal(xdata, list(range(df.shape[1]))) assert_array_almost_equal(ydata, pca_naive.explained_variance_ratio_) # Taking this naive approach, we can see that the first principal component accounts for 99.9% of the variance in the data. (Note the y-axis is on a log scale.) Looking more closely, we see that the first principle component is just the range in miles. # In[12]:
# # Writing the tests first, and *then* writing the actual code is actually a perfectly valid approach (preferred by many) to programming. It's called [test-driven development](https://en.wikipedia.org/wiki/Test-driven_development). So, you should learn what [assert](https://wiki.python.org/moin/UsingAssertionsEffectively) means in Python, and study [nose](http://nose.readthedocs.org/en/latest/testing.html). We will also use [Numpy testing tools](http://docs.scipy.org/doc/numpy/reference/routines.testing.html) to test arrays and [Pandas testing](http://pandas.pydata.org/developers.html#testing) to test pandas.Series and DataFrame objects. # In[15]: assert_equal(isinstance(ax1, mpl.axes.Axes), True, msg="Your function should return a matplotlib.axes.Axes object.") assert_equal(len(ax1.lines), 1) assert_equal(len(ax1.collections), 2, msg="Your plot doesn't have a regression line.") assert_is_not(len(ax1.title.get_text()), 0, msg="Your plot doesn't have a title.") assert_is_not(ax1.xaxis.get_label_text(), "AirTime", msg="Change the x-axis label to something more descriptive.") assert_is_not(ax1.yaxis.get_label_text(), "Distance", msg="Change the y-axis label to something more descriptive.") x, y = ax1.collections[0].get_offsets().T assert_array_equal(x, local["AirTime"]) assert_array_equal(y, local["Distance"]) # ## Split a DataFrame into a testing and a test set # # Now, we will include another predictor variable `ArrDelay` in the regression model in addition to `AirTime`. At the same time, we will split our data set into a training set and a test. We will use only the training set to learn a multivariate regresion model, predict `Distance` in the test set, and compare the predictions with the truth values in the test set.
def test_is_not(self): assert_is_not(TestToolsBIT.mylist, TestToolsBIT.mytupleptr)
def test_requirement__new_obj_if_checks_differ(): obj1 = versions.Requirement("echo", "", versions.GE(1)) obj2 = versions.Requirement("echo", "", versions.LT(1)) assert_is_not(obj1, obj2)
def test_call(self): nodes = self.nv assert_is(nodes, nodes()) assert_is_not(nodes, nodes(data=True)) assert_is_not(nodes, nodes(data='weight'))
def test_viewtype(self): nv = self.G.nodes ndvfalse = nv.data(False) assert_is(nv, ndvfalse) assert_is_not(nv, self.ndv)
def test_optimize(self): t = self.s.transpose(signal_axes=['f', 'a', 'b'], optimize=False) nt.assert_is(t.data.base, self.s.data) t = self.s.transpose(signal_axes=['f', 'a', 'b'], optimize=True) nt.assert_is_not(t.data.base, self.s.data)
def test_requirement__new_obj_if_search_differ(): obj1 = versions.Requirement("echo", r"(\d+)", versions.LT(1)) obj2 = versions.Requirement("echo", "", versions.LT(1)) assert_is_not(obj1, obj2)
def test_update_result_dmesg(self): """dmesg.BaseDmesg.update_result: records new dmesg content in result""" self.dmesg.update_result(self.result) nt.assert_is_not(self.result.dmesg, mock.sentinel.dmesg)
def test_get_by_one(self): assert_is_not(User.get_by(username="******"), None)
def test_get_entry_by_mountpoint_attr(self): """Test if the get_entry_by_attr method works for mountpoint attr""" for mnt in ('sda', 'sdb', 'sdc', ): assert_is_not(self.fstab.get_entry_by_attr('mountpoint', '/mnt/%s' % mnt), None)