def test_tvtk_name(self): """Test VTK to TVTK class name conversion.""" v_name = ["vtkFooBar", "vtkXMLDataReader", "vtk3DSReader", "vtk2000Bug"] t_name = ["FooBar", "XMLDataReader", "ThreeDSReader", "Two000Bug"] for i, vn in enumerate(v_name): tn = get_tvtk_name(vn) self.assertEqual(tn, t_name[i]) num = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] for i in range(10): vn = "vtk%dA" % i tn = get_tvtk_name(vn) self.assertEqual(tn, "%sA" % num[i])
def test_all_instantiable(self): """Test if all the TVTK classes are instantiable.""" # This is a comprehensive test that instantiates every single # non-abstract tvtk class. This takes a while. ok = True # Turn off VTK warnings. vtk.vtkObject.GlobalWarningDisplayOff() for name in dir(vtk): klass = getattr(vtk, name) if hasattr(klass, '__bases__') \ and not issubclass(klass, object): try: obj = klass() except TypeError: # These classes are abstract and can't/shouldn't # be instantiated. pass else: t_name = get_tvtk_name(name) skip = ['ObjectBase'] if t_name not in skip: k = getattr(tvtk, t_name) try: obj = k() except TraitError, msg: print "class:", t_name, msg ok = False
def test_no_trait_has_ptr_address_as_value(self): '''Test if none of the TVTK classes' traits has a value of "*_p_void" ''' errors_trait_is_ptr = [] for name in self.names: tvtk_klass_name = get_tvtk_name(name) try: obj = getattr(tvtk, tvtk_klass_name)() except Exception: # testing for instantiation is above pass # Had to use `_full_traitnames_list_` instead of calling # editable_traits(), otherwise looping over the trait name # and getting the attribute (getattr) cause Segfault for # AxisActor.title_prop3d, DataSetCellIterator.cell_type # DataSetCellIterator.number_of_points ...etc for trait_name in obj._full_traitnames_list_: try: trait = getattr(obj, trait_name) except (TypeError, TraitError): pass # this is tested in another test else: if isinstance(trait, str) and trait.endswith('_p_void'): errors_trait_is_ptr.append( (tvtk_klass_name, trait_name, trait)) if errors_trait_is_ptr: message = 'These traits are invalid:\n' message += '\n'.join(('tvtk.{0}.{1} = {2!r}'.format(*error) for error in errors_trait_is_ptr)) self.fail(message)
def test_tvtk_name(self): """Test VTK to TVTK class name conversion.""" v_name = ['vtkFooBar', 'vtkXMLDataReader', 'vtk3DSReader', 'vtk2000Bug'] t_name = ['FooBar', 'XMLDataReader', 'ThreeDSReader', 'Two000Bug'] for i, vn in enumerate(v_name): tn = get_tvtk_name(vn) self.assertEqual(tn, t_name[i]) num = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] for i in range(10): vn = 'vtk%dA' % i tn = get_tvtk_name(vn) self.assertEqual(tn, '%sA' % num[i])
def test_tvtk_name(self): """Test VTK to TVTK class name conversion.""" v_name = ['vtkFooBar', 'vtkXMLDataReader', 'vtk3DSReader', 'vtk2000Bug'] t_name = ['FooBar', 'XMLDataReader', 'ThreeDSReader', 'Two000Bug'] for i, vn in enumerate(v_name): tn = get_tvtk_name(vn) self.assertEqual(tn, t_name[i]) num = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'] for i in range(10): vn = 'vtk%dA'%i tn = get_tvtk_name(vn) self.assertEqual(tn, '%sA'%num[i])
def get_tvtk_class_names(): """Returns 4 lists: 1. A list of all the TVTK class names that are not abstract. 2. A list of the TVTK sources (have only outputs and no inputs) 3. A list of the TVTK filters (both inputs and outputs) 4. A list of the TVTK sinks (only inputs and no outputs) """ # Shut of VTK warnings for the time being. o = vtk.vtkObject w = o.GetGlobalWarningDisplay() o.SetGlobalWarningDisplay(0) # Turn it off. all = [] src = [] filter = [] sink = [] for name in dir(vtk): if name.startswith('vtk'): klass = getattr(vtk, name) try: c = klass() except TypeError: continue tvtk_name = get_tvtk_name(name) all.append(tvtk_name) has_input = has_output = False if hasattr(klass, 'GetNumberOfInputPorts'): if c.GetNumberOfInputPorts() > 0: has_input = True if hasattr(klass, 'GetNumberOfOutputPorts'): if c.GetNumberOfOutputPorts() > 0: has_output = True if has_input: if has_output: filter.append(tvtk_name) else: sink.append(tvtk_name) elif has_output: src.append(tvtk_name) o.SetGlobalWarningDisplay(w) result = (all, src, filter, sink) for x in result: x.sort() return result
def get_tvtk_class_names(): """Returns 4 lists: 1. A list of all the TVTK class names that are not abstract. 2. A list of the TVTK sources (have only outputs and no inputs) 3. A list of the TVTK filters (both inputs and outputs) 4. A list of the TVTK sinks (only inputs and no outputs) """ # Shut of VTK warnings for the time being. o = vtk.vtkObject w = o.GetGlobalWarningDisplay() o.SetGlobalWarningDisplay(0) # Turn it off. all = [] src = [] filter = [] sink = [] for name in dir(vtk): if name.startswith('vtk'): klass = getattr(vtk, name) try: c = klass() except (TypeError, NotImplementedError): continue tvtk_name = get_tvtk_name(name) all.append(tvtk_name) has_input = has_output = False if hasattr(klass, 'GetNumberOfInputPorts'): if c.GetNumberOfInputPorts() > 0: has_input = True if hasattr(klass, 'GetNumberOfOutputPorts'): if c.GetNumberOfOutputPorts() > 0: has_output = True if has_input: if has_output: filter.append(tvtk_name) else: sink.append(tvtk_name) elif has_output: src.append(tvtk_name) o.SetGlobalWarningDisplay(w) result = (all, src, filter, sink) for x in result: x.sort() return result
def test_all_instantiable(self): """Test if all the TVTK classes can be instantiated""" errors = [] for name in self.names: tvtk_name = get_tvtk_name(name) tvtk_klass = getattr(tvtk, tvtk_name, None) try: tvtk_klass() except TraitError: errors.append(traceback.format_exc()) if len(errors) > 0: message = "Not all classes could be instantiated:\n{0}\n" raise AssertionError(message.format(''.join(errors)))
def test_trait_with_range(self): '''Test if all the attributes with MinValue/MaxValue are traits with Range ''' def to_camel_case(text): """ Convert text to CamelCase""" def replace_func(matched): word = matched.group(0).strip("_") return word[0].upper()+word[1:].lower() return re.sub(r'(_?[a-zA-Z]+)', replace_func, text) def get_min_max_value(vtk_klass, vtk_attr_name): """ Return (min, max) of a VTK attribute If MaxValue or MinValue is not available (None, None) is returned """ get_min_method = 'Get' + vtk_attr_name + 'MinValue' get_max_method = 'Get' + vtk_attr_name + 'MaxValue' try: return (getattr(vtk_klass(), get_min_method)(), getattr(vtk_klass(), get_max_method)()) except AttributeError: return None, None for name in self.names: vtk_klass = getattr(vtk, name) tvtk_klass_name = get_tvtk_name(name) try: obj = getattr(tvtk, tvtk_klass_name)() except Exception: # testing for instantiation is above pass for trait_name in obj.editable_traits(): if trait_name in ['_in_set', '_vtk_obj']: continue vtk_attr_name = to_camel_case(trait_name) min_value, max_value = get_min_max_value(vtk_klass, vtk_attr_name) # Explicitly checking for None instead of bool(value) # since min_value/max_value could be int(0) if max_value is not None and min_value is not None: # If max and min values are defined, setting the trait # to outside this range should fail with self.assertRaises(TraitError): setattr(obj, trait_name, (min_value-1, max_value)) with self.assertRaises(TraitError): setattr(obj, trait_name, (min_value, max_value+1))
def test_trait_with_range(self): '''Test if all the attributes with MinValue/MaxValue are traits with Range ''' def to_camel_case(text): """ Convert text to CamelCase""" def replace_func(matched): word = matched.group(0).strip("_") return word[0].upper()+word[1:].lower() return re.sub(r'(_?[a-zA-Z]+)', replace_func, text) def get_min_max_value(vtk_klass, vtk_attr_name): """ Return (min, max) of a VTK attribute If MaxValue or MinValue is not available (None, None) is returned """ get_min_method = 'Get' + vtk_attr_name + 'MinValue' get_max_method = 'Get' + vtk_attr_name + 'MaxValue' try: return (getattr(vtk_klass(), get_min_method)(), getattr(vtk_klass(), get_max_method)()) except AttributeError: return None, None for name in self.names: vtk_klass = getattr(vtk, name) tvtk_klass_name = get_tvtk_name(name) try: obj = getattr(tvtk, tvtk_klass_name)() except Exception: # testing for instantiation is above pass for trait_name in obj.editable_traits(): vtk_attr_name = to_camel_case(trait_name) min_value, max_value = get_min_max_value(vtk_klass, vtk_attr_name) # Explicitly checking for None instead of bool(value) # since min_value/max_value could be int(0) if max_value is not None and min_value is not None: # If max and min values are defined, setting the trait # to outside this range should fail with self.assertRaises(TraitError): setattr(obj, trait_name, (min_value-1, max_value)) with self.assertRaises(TraitError): setattr(obj, trait_name, (min_value, max_value+1))
def setUp(self): vtk.vtkObject.GlobalWarningDisplayOff() self.names = [] # Filter the ones that are abstract or not implemented for name in dir(vtk): if (not name.startswith('vtk') or name.startswith('vtkQt') or len(name) <= 3): continue vtk_klass = getattr(vtk, name) tvtk_klass_name = get_tvtk_name(name) tvtk_klass = getattr(tvtk, tvtk_klass_name, None) if hasattr(vtk_klass, '__bases__') and tvtk_klass is not None: try: obj = vtk_klass() except (TypeError, NotImplementedError): continue else: self.names.append(name)
def test_all_instantiable(self): """Test if all the TVTK classes can be instantiated""" errors = [] for name in self.names: klass = getattr(vtk, name) if hasattr(klass, '__bases__') and not issubclass(klass, object): try: klass() except (TypeError, NotImplementedError): # These classes are abstract and can't/shouldn't # be instantiated. pass else: tvtk_name = get_tvtk_name(name) tvtk_klass = getattr(tvtk, tvtk_name) try: tvtk_klass() except TraitError: errors.append(traceback.format_exc()) if len(errors) > 0: message = "Not all classes could be instantiated:\n{0}\n" raise AssertionError(message.format(''.join(errors)))
def test_all_traits_can_be_obtained(self): '''Test if all of the traits can be obtained ''' errors_getting_trait = [] for name in self.names: tvtk_klass_name = get_tvtk_name(name) try: obj = getattr(tvtk, tvtk_klass_name)() except Exception: # testing for instantiation is above pass for trait_name in obj._full_traitnames_list_: try: trait = getattr(obj, trait_name) except Exception as exception: errors_getting_trait.append( (tvtk_klass_name, trait_name, str(exception))) if errors_getting_trait: message = 'These traits cannot be obtained:\n' message += '\n'.join(('tvtk.{0}.{1} : {2}'.format(*error) for error in errors_getting_trait)) self.fail(message)
def test_all_instantiable(self): """Test if all the TVTK classes are instantiable.""" # This is a comprehensive test that instantiates every single # non-abstract tvtk class. This takes a while. ok = True ignore = [] if vtk.vtkVersion.GetVTKMajorVersion() >= 5 and \ vtk.vtkVersion.GetVTKMinorVersion() == 8: ignore = ['vtkAxesTransformRepresentation'] # Turn off VTK warnings. vtk.vtkObject.GlobalWarningDisplayOff() names = [name for name in dir(vtk) \ if name.startswith('vtk') and \ not name.startswith('vtkQt')] for name in names: if name in ignore: continue klass = getattr(vtk, name) if hasattr(klass, '__bases__') \ and not issubclass(klass, object): try: obj = klass() except (TypeError, NotImplementedError): # These classes are abstract and can't/shouldn't # be instantiated. pass else: t_name = get_tvtk_name(name) skip = ['ObjectBase'] if t_name not in skip: k = getattr(tvtk, t_name) try: obj = k() except TraitError, msg: print "class:", t_name, msg ok = False
def get_tvtk_class_names(): """Returns 4 lists: 1. A list of all the TVTK class names that are not abstract. 2. A list of the TVTK sources (have only outputs and no inputs) 3. A list of the TVTK filters (both inputs and outputs) 4. A list of the TVTK sinks (only inputs and no outputs) """ # Shut of VTK warnings for the time being. o = vtk.vtkObject w = o.GetGlobalWarningDisplay() o.SetGlobalWarningDisplay(0) # Turn it off. old_stdout = sys.stdout old_stderr = sys.stderr all = [] src = [] filter = [] sink = [] for name in dir(vtk): if name.startswith('vtk') and not name.startswith('vtkQt'): klass = getattr(vtk, name) try: c = klass() # Some classes hijack sys.stdout/sys.stderr. # Restore it when that happens. if sys.stdout != old_stdout or sys.stderr != old_stderr: sys.stdout = old_stdout sys.stderr = old_stderr except (TypeError, NotImplementedError): continue tvtk_name = get_tvtk_name(name) all.append(tvtk_name) has_input = has_output = False if hasattr(klass, 'GetNumberOfInputPorts'): if c.GetNumberOfInputPorts() > 0: has_input = True if hasattr(klass, 'GetNumberOfOutputPorts'): if c.GetNumberOfOutputPorts() > 0: has_output = True if has_input: if has_output: filter.append(tvtk_name) else: sink.append(tvtk_name) elif has_output: src.append(tvtk_name) o.SetGlobalWarningDisplay(w) result = (all, src, filter, sink) for x in result: x.sort() return result
def search(self, word): """ Search for word in class documentation and return matching classes. This is also case insensitive. The searching supports the 'and' and 'or' keywords that allow for fairly complex searches. A space between words assumes that the two words appear one after the other. Parameters ---------- word -- name to search for. """ assert type(word) in types.StringTypes, \ "Sorry, passed argument, %s is not a string."%word if len(word.strip()) == 0: return [] lword = word.lower().strip() tmp_list = lword.split() wlist = [] prev = "" for w in tmp_list: z = w.strip() if z in ('and', 'or'): if prev and prev not in ('and', 'or'): wlist.append(prev) wlist.append(z) prev = z else: if prev and prev not in ('and', 'or'): prev = prev + ' ' + z else: prev = z if prev in ('and', 'or'): del wlist[-1] elif prev: wlist.append(prev) ret = [] i = 0 vtk_classes = self.vtk_classes vtk_c_doc = self.vtk_c_doc N = len(vtk_classes) while i < N: stored_test = 0 do_test = '' for w in wlist: if w == 'and': do_test = 'and' elif w == 'or': do_test = 'or' else: test = (vtk_c_doc[i].find(w) > -1) if do_test == 'and': stored_test = stored_test and test elif do_test == 'or': stored_test = stored_test or test elif do_test == '': stored_test = test if stored_test: ret.append(vtk_classes[i]) i = i + 1 return [get_tvtk_name(x) for x in ret]
def search(self, word): """ Search for word in class documentation and return matching classes. This is also case insensitive. The searching supports the 'and' and 'or' keywords that allow for fairly complex searches. A space between words assumes that the two words appear one after the other. Parameters ---------- word -- name to search for. """ assert type(word) is str, \ "Sorry, passed argument, %s is not a string."%word if len(word.strip()) == 0: return [] lword = word.lower().strip() tmp_list = lword.split() wlist = [] prev = "" for w in tmp_list: z = w.strip() if z in ('and', 'or'): if prev and prev not in ('and', 'or'): wlist.append(prev) wlist.append(z) prev = z else: if prev and prev not in ('and', 'or'): prev = prev + ' ' + z else: prev = z if prev in ('and', 'or'): del wlist[-1] elif prev: wlist.append(prev) ret = [] i = 0 vtk_classes = self.vtk_classes vtk_c_doc = self.vtk_c_doc N = len(vtk_classes) while i < N: stored_test = 0 do_test = '' for w in wlist: if w == 'and': do_test = 'and' elif w == 'or': do_test = 'or' else: test = (vtk_c_doc[i].find(w) > -1) if do_test == 'and': stored_test = stored_test and test elif do_test == 'or': stored_test = stored_test or test elif do_test == '': stored_test = test if stored_test: ret.append(vtk_classes[i]) i = i + 1 return [get_tvtk_name(x) for x in ret]