How to use get_data_type_chain method in autotest

Best Python code snippet using autotest_python

clazzbase.py

Source:clazzbase.py Github

copy

Full Screen

...407 verbose_name = re.sub(r'([a-z])([A-Z])',r'\1 \2', verbose_name)408 verbose_name = verbose_name.replace('_', ' ')409 verbose_name = verbose_name[0].upper() + verbose_name[1:].lower()410 return verbose_name411def get_data_type_chain(element):412 if isinstance(element, str):413 return element414 name = cleanupName(element.getCleanName())415 simplebase = element.getSimpleBase()416 if simplebase:417 if len(simplebase) == 1:418 base_name = "%s" % (simplebase[0], )419 else:420 base_name = simplebase421 else:422 element1 = ElementDict.get(name)423 if element1:424 base_name = "%s" % element1.getType()425 else:426 base_name = "%s" % (element.getType(), )427 return base_name428def get_data_type(element):429 data_type = get_data_type_chain(element)430 if isinstance(data_type, list):431 if len(data_type) > 0:432 return data_type[-1]433 else:434 return 'xs:string'435 else:436 return data_type437def get_prefix_name(tag):438 prefix = ''439 name = ''440 items = tag.split(':')441 if len(items) == 2:442 prefix = items[0]443 name = items[1]444 elif len(items) == 1:445 name = items[0]446 return prefix, name447#448# Classes449class Writer(object):450 def __init__(self, outfilename, stdout_also=False):451 self.outfilename = outfilename452 self.outfile = open(outfilename, 'w')453 self.stdout_also = stdout_also454 self.line_count = 0455 def get_count(self):456 return self.line_count457 def write(self, content):458 self.outfile.write(content)459 if self.stdout_also:460 sys.stdout.write(content)461 count = content.count('\n')462 self.line_count += count463 def close(self):464 self.outfile.close()465class Clazz(object):466 ClazzDict = OrderedDict()467 simple_type_table = None468 def __str__(self):469 s1 = '<Clazz name: "%s" elt: "%s">' % \470 (self.name, self.schema_element, )471 return s1472 __repr__ = __str__473 @classmethod474 def extract_descriptors(cls, xschemaFileName):475 cls.ClazzDict = OrderedDict()476 cls.simple_type_table = extract_descriptors(xschemaFileName)477 @classmethod478 def get_clazz_for_element(cls, element):479 if isinstance(element, XschemaElementBase):480 data_type = get_data_type(element)481 if cls.ClazzDict.has_key(data_type):482 return cls.ClazzDict[data_type]483 else:484 return None485 @classmethod486 def is_one_to_many(cls, member):487 dummy, data_type = get_prefix_name(member.get_data_type())488 return data_type not in Simple_type_table \489 and data_type not in cls.simple_type_table \490 and data_type != 'myString' \491 and member.is_one_to_many()492 @classmethod493 def is_valid_one_to_many(cls, member):494 if cls.is_one_to_many(member):495 data_type = member.get_data_type()496 child_clazz = cls.ClazzDict[data_type]497 return isinstance(child_clazz.backreference, ClazzBaseMember) or \498 isinstance(child_clazz.backreference, tuple)499 @classmethod500 def has_multiple_one_to_many_references(cls, member):501 '''502 Returns True if member is the many side of more than one one-to-many reference, False otherwise.503 '''504 if cls.is_one_to_many(member):505 data_type = member.get_data_type()506 child_clazz = cls.ClazzDict[data_type]507 if isinstance(child_clazz.backreference, tuple) and len(child_clazz.backreference) > 1:508 return True509 return False510 511 @classmethod512 def establish_one_to_many(cls):513 for clazz in cls.ClazzDict.values():514 for member in clazz.members:515 if cls.is_one_to_many(member):516 child_clazz = cls.ClazzDict[member.get_data_type()]517 # establish backward connection518 child_clazz.set_one_to_many(member)519 def __init__(self, prefix, name, parentName, element):520 self.prefix = prefix521 self.name = name522 self.parentName = parentName523 self.schema_element = element524 self.members = list()525 self.backreference = None526 self.schema_fields = list()527 self.schema_classes = OrderedDict()528 self.embedded_enums = list()529 self.choice_of = list()530 self.choice_parent = None531 self.inlines = list()532 self.dependants = list()533 self.visited = False534 def _update_schema_classes(self, name, data_type):535 """536 Updates self.schema_classes adding name->data_type if possible.537 Prints a warning to the logger if a name is used with multiple types.538 """539 if not name in self.schema_classes.keys():540 self.schema_classes[name] = data_type541 elif self.schema_classes[name] != data_type:542 logging.warn('__schema_classes__[{!r}] seems multi-' \543 'typed: {} != {}'.format(name, data_type,544 self.schema_classes[name]))545 def addMember(self, clazz_member):546 self.members.append(clazz_member)547 def set_one_to_many(self, clazz_member):548 if self.backreference is None:549 self.backreference = ()550 self.backreference += (clazz_member, )551 def is_empty(self):552 return not self.members553 def collect_data(self):554 """555 This method will generate all the anonymous choice types,556 as well as compute the __schema_XXX__ fields of Christian557 Furthermore, it collects information which types depend on others558 either because:559 - a member of self points to another type560 - self has a back reference and depends on the "parent" type561 - self is a choice type (depends on the choice types)562 563 """564 class_name = self.name565 # Luckily, back references are not a dependency, only schema_classes!566 #if self.backreference:567 # member = self.backreference568 # data_type = member.get_generated_type(member.source.name)569 # back_clazz = self.ClazzDict[data_type]570 # back_clazz.dependants.append(self)571 for member in self.members:572 name = member.get_generated_name()573 data_type = member.get_generated_type(member.get_data_type())574 if isinstance(member.child, XschemaElementBase):575 if member.child.choice:576 if self.ClazzDict.has_key(data_type):577 choice_type = self.ClazzDict[data_type]578 self.choice_of.append((member.name, choice_type))579 # self must be defined before choice_type since it's580 # its superclass581 if not choice_type in self.dependants:582 self.dependants.append(choice_type)583 if choice_type.choice_parent:584 logging.error('Element used twice in choice: ' \585 '{}'.format(data_type))586 else:587 choice_type.choice_parent = self588 _inline_classname_suffix = ''589 # Choice admin model inlines may not be collapsed,590 # so do not use the INLINE_COLLAPSE_SNIPPET591 _inline_template_snippets = ''592 self.inlines.append((member.name, _inline_classname_suffix, data_type, _inline_template_snippets))593 else:594 self.choice_of.append((member.name, data_type))595 # do not generate ordinary fields for this member596 continue597 else:598 if self.choice_of:599 logging.warn('Mixture of choice and non-choice ' \600 'members: {}'.format(name))601 else:602 #print(member.child)603 pass604 if data_type in Simple_type_table:605 if data_type in Integer_type_table:606 if isinstance(member.get_data_type_chain(), list) and \607 member.get_values():608 _choice_name = class_name.upper()609 _choice_values = []610 _line = ''611 for _choice_value in member.get_values():612 _line = '{0}{1}, '.format(_line, int(_choice_value))613 _choice_values.append(int(_choice_value))614 615 616 self.embedded_enums.append('\n{}_{}_CHOICES = ' \617 '_make_choices_from_int_list([\n{}\n])\n'.format(618 _choice_name, name.upper(),619 _line))620 elif data_type in Float_type_table:621 pass622 elif data_type in Date_type_table:623 pass624 elif data_type in DateTime_type_table:625 pass626 elif data_type in Boolean_type_table:627 pass628 elif data_type in String_type_table:629 if isinstance(member.get_data_type_chain(), list) and \630 member.get_values():631 _choice_name = class_name.upper()632 _choice_values = []633 _line = ' '634 for _choice_value in member.get_values():635 if len(_line) + len(_choice_value) + 4 < 77:636 _line += '{!r}, '.format(_choice_value)637 else:638 _choice_values.append(_line.rstrip())639 _line = ' {!r},'.format(_choice_value)640 641 _choice_values.append(_line)642 643 self.embedded_enums.append('\n{}_{}_CHOICES = ' \644 '_make_choices_from_list([\n{}\n])\n'.format(645 _choice_name, name.upper(),646 '\n'.join(_choice_values)))647 else:648 logging.warn('Unhandled simple type: %s %s\n' % (649 name, data_type, ))650 else:651 if (data_type != 'myString'):652 self._update_schema_classes(name, data_type)653 member_clazz = self.ClazzDict[data_type]654 if not member.is_unbounded():655 # one-to-one relation, maybe optional656 pass657 else:658 # ManyToManyField, backward pointer in case of one-to-many659 if self.is_valid_one_to_many(member):660 # replace by backward pointing shadow field661 _inline_classname_suffix = ''662 _inline_template_snippets = ''663 _optional = member.get_required() != 'REQUIRED'664 _inline_type = member.child.getAppInfo('inline-type')665 _tabular = (_inline_type == 'tabular')666 if _tabular:667 _inline_template_snippets += INLINE_SNIPPET_TABULAR668 if _optional and not _tabular:669 _inline_template_snippets += INLINE_SNIPPET_COLLAPSE670 if self.has_multiple_one_to_many_references(member):671 member_data_type = member.get_generated_type(member.source.name)672 # TODO: remove warning673 logging.warn('Multiple one-to-many: {}->{}'.format(member_data_type, data_type ))674 _inline_classname_suffix = '_{}_model'.format(member_data_type)675 _inline_template_snippets += INLINE_SNIPPET_FK_NAME.format(member_data_type.lower())676 self.inlines.append((name, _inline_classname_suffix, data_type, _inline_template_snippets))677 else:678 #schema_classes[name] = data_type679 pass680 def generate_simple_field(self, name, field_name, options, required):681 options += required682 683 if name == 'metaShareId':684 options += 'default="NOT_DEFINED_FOR_V2", '685 686 # XmlCharField, MetaBooleanField and MultiSelectField don't need the687 # "models." prefix as they are custom fields imported from688 # "metashare.repository.fields".689 if field_name in ('XmlCharField', 'MetaBooleanField',690 'MultiSelectField'):691 self.wrtmodels(' %s = %s(%s)\n' % ( name, field_name, options, ))692 else:693 self.wrtmodels(' %s = models.%s(%s)\n' % ( name, field_name, options, ))694 self.wrtforms(' %s = forms.%s(%s)\n' % ( name, field_name, options, ))695 def generate_simple_member(self, member, name, data_type, multi_id, options):696 if not member.is_required():697 required = 'blank=True, null=True, '698 else:699 required = ''700 if isinstance(member.child, XschemaElement):701 helptext = member.child.getHelpText()702 if helptext:703 _help_text = _truncate_long_string(helptext, 72, 6)704 options += '\n help_text={},\n '.format(_help_text)705 if data_type in Integer_type_table:706 if isinstance(member.get_data_type_chain(), list) and \707 member.get_values():708 _choice_name = self.name.upper()709 choice_name = '{}_{}_CHOICES' \710 .format(_choice_name, name.upper(), member.get_values())711 maxlen = member.get_maxlength()712 if maxlen:713 logging.warn("max_length overwritten for choice of " \714 "strings: {}".format(member))715 if member.is_unbounded():716 choice_options = \717 CHOICES_TEMPLATE_MAXLEN.format(choice_name, maxlen)718 else:719 choice_options = \720 SORTED_INT_CHOICES_TEMPLATE_MAXLEN.format(choice_name, maxlen)721 else:722 choice_options = CHOICES_TEMPLATE.format(choice_name)723 724 # cfedermann: MultiSelectField generation...725 if member.is_unbounded():726 choice_options = MULTI_CHOICES_TEMPLATE.format(choice_name)727 728 self.generate_simple_field(name, 'MultiSelectField',729 options + choice_options, required)730 else:731 # here we do not need anything larger than `xs:int`, even if732 # it is defined as such; we probably can safely assume that733 # none of the enumeration values has more than 2 billion734 # digits ...; still we log this assumption735 if Integer_type_table[data_type] != 'IntegerField':736 logging.warn('Ignoring a probably too broad type (%s) '737 'for "%s". Using a standard "IntegerField" instead.',738 data_type, name)739 self.generate_simple_field(name, 'IntegerField',740 options + choice_options, required)741 else:742 self.generate_simple_field(name, Integer_type_table[data_type],743 options, required)744 elif data_type in Float_type_table:745 self.generate_simple_field(name, 'FloatField', options, required)746 elif data_type in Date_type_table:747 self.generate_simple_field(name, 'DateField', options, required)748 elif data_type in DateTime_type_table:749 self.generate_simple_field(name, 'DateTimeField', options, required)750 elif data_type in Boolean_type_table:751 if not member.is_required():752 required = 'blank=True, '753 self.generate_simple_field(name, 'MetaBooleanField', options, required)754 elif data_type in String_type_table:755 fixed_value = member.get_fixed()756 if fixed_value:757 options += 'default="{0}", editable=False, '.format(fixed_value)758 if not member.is_required():759 options += 'blank=True, '760 if isinstance(member.get_data_type_chain(), list) and \761 member.get_values():762 _choice_name = self.name.upper()763 choice_name = '{}_{}_CHOICES' \764 .format(_choice_name, name.upper(), member.get_values())765 maxlen = member.get_maxlength()766 if maxlen:767 logging.warn("max_length overwritten for choice of " \768 "strings: {}".format(member))769 if member.is_unbounded():770 choice_options = \771 CHOICES_TEMPLATE_MAXLEN.format(choice_name, maxlen)772 else:773 choice_options = \774 SORTED_CHOICES_TEMPLATE_MAXLEN.format(choice_name, maxlen)775 else:776 choice_options = CHOICES_TEMPLATE.format(choice_name)777 778 # cfedermann: MultiSelectField generation...779 if member.is_unbounded():780 choice_options = MULTI_CHOICES_TEMPLATE.format(choice_name)781 782 self.generate_simple_field(name, 'MultiSelectField',783 options + choice_options, '')784 else:785 self.generate_simple_field(name, 'CharField',786 options + choice_options, '')787 else:788 if data_type == 'gYear':789 options += GYEAR_VALIDATOR_OPTION_SNIPPET790 maxlen = member.get_maxlength()791 if not maxlen:792 maxlen = DEFAULT_MAXLENGTH793 choice_options = "max_length={}, ".format(maxlen)794 if not member.is_unbounded():795 self.generate_simple_field(name, 'XmlCharField',796 options + choice_options, '')797 else:798 if not 'validators=' in options:799 options += 'validators=[validate_matches_xml_char_production], '800 self.wrtmodels(801 ' %s = MultiTextField(%swidget=MultiFieldWidget('802 'widget_id=%d, max_length=%s), %s)\n' % (803 name, choice_options, multi_id, maxlen, options, ))804 self.wrtforms(805 ' %s = forms.CharField(%s%s)### FIX_ME: MULTITEXT %d\n' % (806 name, choice_options, options, multi_id, ))807 multi_id += 1808 else:809 logging.warn('Unhandled simple type: {} {}\n'.format(name, data_type))810 return multi_id811 def generate_myString_member(self, member, name, options):812 maxlen = member.get_maxlength()813 if maxlen:814 options += "\n max_val_length={}, ".format(maxlen)815 help_string = member.child.getHelpText()816 if help_string:817 _help_text = _truncate_long_string(help_string, 72, 6)818 options += '\n help_text={},\n '.format(_help_text)819 if not member.is_required():820 options += 'blank=True'821 self.wrtmodels(822 ' %s = DictField(validators=[validate_lang_code_keys, validate_dict_values],\n'823 ' default_retriever=best_lang_value_retriever, %s)\n' % (824 name, options, ))825 def generate_complex_member(self, member, name, data_type, options):826 help_string = member.child.getHelpText()827 if help_string:828 _help_text = _truncate_long_string(help_string, 72, 6)829 options += '\n help_text={},\n '.format(_help_text)830 if data_type == 'myString':831 # myString is handled in a special way832 # the s after %(class) is important, _ gives errors833 #options =', related_name="%(class)s_{}_{}_model"'.format(name, data_type)834 #related_name=', related_name="{}_{}_{}_model"'.format(class_name, name, data_type)835 self.generate_myString_member(member, name, options)836 else:837 if not member.is_unbounded():838 field_type = member.child.getAppInfo('relation')839 model_field_name = 'OneToOneField'840 if field_type:841 if field_type == 'many-to-one':842 # A reusable component which can occur only once in this context:843 model_field_name = 'ForeignKey'844 elif field_type == 'many-to-many' or field_type == 'one-to-many':845 # Complain but default to one-to-one846 logging.warn(('wrong {} declaration for member {} '+ \847 'with at most one element').format(field_type, member))848 # this is a many-to-one or a one-to-one relation, maybe optional849 if not member.is_required():850 options += 'blank=True, null=True, on_delete=models.SET_NULL, '851 self.wrtmodels(852 ' %s = models.%s("%s_model", %s)\n' % (853 name, model_field_name, data_type, options, ))854 self.wrtforms(855 ' %s = forms.MultipleChoiceField(%s_model.objects.all())\n' % (856 name, data_type, ))857 #else: # This was the previous solution: many-to-many is default858 elif not self.is_valid_one_to_many(member):859 if not member.is_required():860 options += 'blank=True, null=True, '861 options += 'related_name="{}_%(class)s_related", '.format(name)862 self.wrtmodels(863 ' %s = models.ManyToManyField("%s_model", %s)\n' % (864 name, data_type, options, ))865 self.wrtforms(866 ' %s = forms.MultipleChoiceField(%s_model.objects.all())### FIX_ME: ManyToMany\n' % (867 name, data_type, ))868 else:869 self.wrtmodels(' # OneToMany field: {0}\n'.format(name))870 self.wrtforms(' # OneToMany field: {0}\n'.format(name))871 def generate_backref_members(self):872 """873 Generate a backreference (inverse one-to-many pointer)874 This only generates a back reference if it's in this Clazz object.875 876 """877 # treat a one-to-many relation as reverse foreign key878 if isinstance(self.backreference, ClazzBaseMember):879 self.generate_one_backref_member(self.backreference, required=True)880 elif isinstance(self.backreference, tuple):881 for member in self.backreference:882 self.generate_one_backref_member(member, required=False)883 def generate_one_backref_member(self, member, required):884 #name = member.get_generated_name()885 data_type = member.get_generated_type(member.source.name)886 # cfedermann: disabled related_name generation as it breaks export887 # of _model_set fields at the moment. This needs to be checked!888 options = ''#'related_name=\'back_to_{0}_model_from_{1}_model\', '\889 # .format(data_type.lower(), self.name.lower())890 # Marc, 27 Feb 12: for the editor we need back references to corpusMediaType891 # to be optional at least in the database:892 if data_type == 'corpusMediaTypeType':893 required = False894 if not required:895 options += ' blank=True, null=True'896 # back reference fields are ALWAYS required897 #if not member.is_required():898 # options = options + ', blank=True'899 #else:900 # options = options + ', blank=False'901 self.wrtmodels(#' %s_BACK = models.ForeignKey("%s_model"%s)\n\n' % (902 ' back_to_{0}_model = models.ForeignKey("{1}_model", {2})\n\n'903 .format(data_type.lower(), data_type, options, ))904 # TODO what about forms905 def generate_unicode_method(self):906 rendering_hint = self.schema_element.getAppInfo('render-short')907 if not rendering_hint:908 self.wrtmodels(UNICODE_DEFAULT_TEMPLATE)909 else:910 start = 0911 formatstring = ''912 formatargs = ''913 for match in re.finditer(r'{([^}]*)}', rendering_hint):914 formatstring += _escape_non_ascii_chars(915 rendering_hint[start:match.start(1)]) \916 + rendering_hint[match.end(1):match.end(0)]917 start = match.end(0)918 formatargs += '\'' + match.group(1) + '\', '919 formatstring += _escape_non_ascii_chars(rendering_hint[start:])920 self.wrtmodels(UNICODE_METHOD_TEMPLATE.format(formatstring,921 formatargs))922 def generate_choice_model_(self):923 """924 Generate a model for the given choice class925 choices is a list of the choice classes that this class represents.926 927 """928 verbose_name = self.schema_element.getAppInfo("label")929 if not verbose_name:930 verbose_name = getVerboseName(self.name)931 verbose_name_plural = self.schema_element.getAppInfo("label-plural")932 plural_snippet = ''933 if verbose_name_plural:934 plural_snippet = VERBOSE_NAME_PLURAL_SNIPPET.format(verbose_name_plural)935 self.wrtmodels(CHOICE_SUPERCLASS_TEMPLATE.format(936 self.name, CHOICE_TYPE_SUPERCLASS,937 self.schema_element.getDocumentation(), verbose_name, plural_snippet))938 939 self.wrtforms('\nclass %s_form(forms.Form):\n' % (self.name, ))940 self.generate_backref_members()941 def generate_model_(self):942 """943 Generate a model for the given clazz self944 """945 for enum in self.embedded_enums:946 self.wrtmodels(enum)947 documentation = ''948 if isinstance(self.schema_element, XschemaElement):949 documentation = self.schema_element.getDocumentation()950 model_superclass = MODELS_SUPERCLASS951 if self.choice_parent:952 model_superclass = self.choice_parent.name + "_model"953 verbose_name = self.schema_element.getAppInfo("label")954 if not verbose_name:955 verbose_name = getVerboseName(self.name)956 verbose_name_plural = self.schema_element.getAppInfo("label-plural")957 plural_snippet = ''958 if verbose_name_plural:959 plural_snippet = VERBOSE_NAME_PLURAL_SNIPPET.format(verbose_name_plural)960 self.wrtmodels(COMPLEX_MODEL_TEMPLATE.format(self.name,961 model_superclass, documentation, verbose_name, plural_snippet))962 self.wrtforms('\nclass %s_form(forms.Form):\n' % (self.name, ))963 if self.is_empty():964 self.wrtforms(' pass\n')965 _schema_name = self.name966 if self.name == 'resourceInfoType':967 _schema_name = 'resourceInfo'968 self.wrtmodels("\n __schema_name__ = '{}'\n".format(_schema_name))969 if self.members:970 self.wrtmodels(' __schema_fields__ = (\n')971 for member in self.members:972 data_type = member.get_generated_type(member.get_data_type())973 django_field_name = member.get_generated_name()974 if not data_type in Simple_type_table \975 and member.is_unbounded() \976 and self.is_valid_one_to_many(member):977 django_field_name = data_type.lower() + '_model_set'978 # choice child will only be not None if this member points to979 # a type that represents a type which is a xs:choice980 choice_child = None981 if self.ClazzDict.has_key(data_type):982 choice_child = self.ClazzDict[data_type]983 if not choice_child.choice_of:984 choice_child = None985 if not choice_child:986 self.wrtmodels(' ( {!r}, {!r}, {!s} ),\n'.format(987 member.get_generated_name(), django_field_name,988 member.get_required()))989 else:990 for sub_choice in choice_child.choice_of:991 if isinstance(sub_choice[1], Clazz):992 data_type = sub_choice[1].name993 else:994 data_type = sub_choice[0] + "String"995 parent_type = choice_child.name + "_model"996 if not data_type in CHOICE_STRING_SUB_CLASSES.keys():997 CHOICE_STRING_SUB_CLASSES[data_type] = [parent_type]998 else:999 if not parent_type in CHOICE_STRING_SUB_CLASSES[data_type]:1000 CHOICE_STRING_SUB_CLASSES[data_type].append(parent_type)1001 self.wrtmodels(' ( \'{}/{}\', \'{}' \1002 '\', {!s} ),\n'.format(member.get_name(),1003 sub_choice[0], django_field_name,1004 member.get_required()))1005 # For xs:choice fields, we don't have to generate a1006 # class information entry for the super class; hence1007 # we remove it from self.schema_classes now.1008 if member.get_name() in self.schema_classes.keys():1009 self.schema_classes.pop(member.get_name())1010 self._update_schema_classes(sub_choice[0], data_type)1011 self.wrtmodels(' )\n')1012 if self.schema_classes:1013 self.wrtmodels(" __schema_classes__ = {\n")1014 _class_names = self.schema_classes.keys()1015 _class_names.sort()1016 for class_name in _class_names:1017 data_type = self.schema_classes[class_name]1018 self.wrtmodels(' {!r}: "{}_model",\n'.format(class_name,1019 data_type))1020 self.wrtmodels(' }\n')1021 self.wrtmodels('\n')1022 # cfedermann: is this block EVER reached? If not, remove it!1023 if self.parentName:1024 raise AssertionError('self.parentName if block actually reached!')1025 self.wrtmodels(' %s = models.ForeignKey("%s_model")\n' % (1026 self.parentName, self.parentName, ))1027 global MULTI_ID1028 multi_id = MULTI_ID1029 for member in self.members:1030 name = member.get_generated_name()1031 data_type = member.get_generated_type(member.get_data_type())1032 verbose_name = None1033 if isinstance(member.child, XschemaElement):1034 verbose_name = member.child.getAppInfo('label')1035 if not verbose_name:1036 verbose_name = getVerboseName(name)1037 options = '\n verbose_name=\'{}\', '.format(verbose_name)1038 1039 if member.get_data_type() == 'xs:anyURI':1040 options += 'validators=[HTTPURI_VALIDATOR], '1041 1042 elif member.name == 'email':1043 options += 'validators=[EMAILADDRESS_VALIDATOR], '1044 1045 if data_type == 'myString':1046 self.generate_myString_member(member, name, options)1047 elif data_type in Simple_type_table:1048 # simple type member1049 multi_id = self.generate_simple_member(member, name, data_type,1050 multi_id, options)1051 MULTI_ID = multi_id1052 else:1053 # complex type member1054 self.generate_complex_member(member, name, data_type, options)1055 self.wrtmodels('\n')1056 if not self.choice_parent:1057 self.generate_backref_members()1058 if self.name in REUSABLE_ENTITIES:1059 self.wrtmodels(REUSABLE_ENTITY_SNIPPET)1060 if self.name == 'documentInfoType':1061 self.wrtmodels(''' def save(self, *args, **kwargs):1062 """1063 Prevents id collisions for documentationInfoType_model sub classes.1064 """1065 # pylint: disable-msg=E02031066 if not self.id:1067 # pylint: disable-msg=W02011068 self.id = _compute_documentationInfoType_key()1069 super(documentInfoType_model, self).save(*args, **kwargs)1070''')1071 self.generate_unicode_method()1072 if self.name == 'resourceInfoType':1073 self.wrtmodels(TOP_LEVEL_TYPE_EXTRA_CODE_TEMPLATE)1074 # end generate_model1075 def topo_sort_rec(self, result):1076 self.visited = 11077 for dependant in self.dependants:1078 if not dependant.visited:1079 dependant.topo_sort_rec(result)1080 elif dependant.visited == 1:1081 logging.error('dependency graph is cyclic')1082 self.visited = 21083 result.append(self)1084 @classmethod1085 def topo_sort(cls, clazz_list):1086 for clazz in clazz_list:1087 clazz.visited = 01088 result = list()1089 while clazz_list:1090 clazz = clazz_list.pop()1091 if not clazz.visited:1092 cls.topo_sort_rec(clazz, result)1093 result.reverse()1094 return result1095 @classmethod1096 def generate(cls, outDirName, prefix, root, target_ns, schema_version,1097 package_prefix):1098 cls.establish_one_to_many()1099 models_file_name = os.path.join(outDirName, 'models.py')1100 forms_file_name = os.path.join(outDirName, 'forms.py')1101 admin_file_name = os.path.join(outDirName, 'admin.py')1102 models_writer = Writer(models_file_name)1103 forms_writer = Writer(forms_file_name)1104 admin_writer = Writer(admin_file_name)1105 cls.wrtmodels = models_writer.write1106 cls.wrtforms = forms_writer.write1107 cls.wrtadmin = admin_writer.write1108 cls.wrtmodels(MODEL_HEADER.format(package_prefix, target_ns,1109 schema_version))1110 cls.wrtforms('from django import forms\n\n')1111 exportableClassList = list()1112 cls.wrtadmin('from django.contrib import admin\n')1113 cls.wrtadmin('from {0}editor.superadmin import SchemaModelAdmin\n'.format(1114 package_prefix))1115 cls.wrtadmin('from {0}editor.inlines import SchemaModelInline\n'.format(1116 package_prefix))1117 for clazz in cls.ClazzDict.values():1118 clazz.collect_data()1119 if clazz.is_empty():1120 if clazz.schema_element.isComplex():1121 exportableClassList.append(clazz)1122 logging.warn('empty type {}'.format(clazz))1123 # cfedermann: this would not be written inside the class.1124 # Hence we have to remove it later!1125 #1126 #cls.wrtforms(' pass\n')1127 else:1128 exportableClassList.append(clazz)1129 clazz_list = Clazz.topo_sort(exportableClassList)1130 if False: # to debug dependencies1131 for clazz in exportableClassList:1132 sys.stdout.write("{}: ".format(clazz.name))1133 for dep in clazz.dependants:1134 sys.stdout.write("{}, ".format(dep.name))1135 sys.stdout.write('\n')1136 sys.stdout.write('\n')1137 for clazz in clazz_list:1138 sys.stdout.write("{}, ".format(clazz.name))1139 sys.stdout.write('\n')1140 for clazz in clazz_list:1141 if clazz.choice_of:1142 clazz.generate_choice_model_()1143 else:1144 clazz.generate_model_()1145 _choice_names = CHOICE_STRING_SUB_CLASSES.keys()1146 _choice_names.sort()1147 for class_name in _choice_names:1148 parent_types = CHOICE_STRING_SUB_CLASSES[class_name]1149 cls.wrtmodels(CHOICE_STRING_SUB_CLASS_TEMPLATE.format(class_name,1150 ', '.join(parent_types)))1151 cls.wrtadmin(CHOICE_STRING_SUB_CLASS_ADMIN_TEMPLATE.format(class_name))1152 # Sort clazzes to achieve consistent output order in admin.py.1153 clazz_list.sort(key=lambda x:x.name)1154 cls.wrtadmin('\nfrom {0}models import \\\n'.format(package_prefix))1155 first_time = True1156 for clazz in clazz_list:1157 if first_time:1158 cls.wrtadmin(' %s_model' % (clazz.name, ))1159 first_time = False1160 else:1161 cls.wrtadmin(', \\\n %s_model' % (clazz.name, ))1162 cls.wrtadmin('\n\n\n')1163 _inlines = []1164 for clazz in clazz_list:1165 _inlines.extend(clazz.inlines)1166 _inlines.sort(key=lambda x:x[0])1167 for _inline in _inlines:1168 cls.wrtadmin(INLINE_TEMPLATE.format(_inline[0], _inline[1],1169 _inline[2], _inline[3]))1170 for clazz in clazz_list:1171 cls.wrtadmin('admin.site.register({}_model, SchemaModelAdmin)\n'.format(1172 clazz.name))1173 cls.wrtadmin(MANUAL_ADMIN_REGISTRATION_TEMPLATE)1174 cls.wrtadmin('\n')1175 models_writer.close()1176 forms_writer.close()1177 admin_writer.close()1178 cls.wrtmodels = None1179 cls.wrtforms = None1180 cls.wrtadmin = None1181 print 'Wrote %d lines to models.py' % (models_writer.get_count(), )1182 print 'Wrote %d lines to forms.py' % (forms_writer.get_count(), )1183 print 'Wrote %d lines to admin.py' % (admin_writer.get_count(), )1184class ClazzBaseMember(object):1185 def get_name(self):1186 return self.name1187 def get_generated_name(self):1188 name = self.get_name()1189 dummy, name = get_prefix_name(name)1190 name = cleanupName(name)1191 if name == 'id':1192 name += 'x'1193 elif name.endswith('_'):1194 name += 'x'1195 #name = name[0].upper() + name[1:]1196 return name1197 def get_generated_type(self, data_type):1198 dummy, data_type = get_prefix_name(data_type)1199 if data_type in Clazz.simple_type_table:1200 data_type = Clazz.simple_type_table[data_type]1201 dummy, data_type = get_prefix_name(data_type.type_name)1202 data_type = cleanupName(data_type)1203 #data_type = data_type[0].upper() + data_type[1:]1204 return data_type1205 def get_required(self):1206 if self.is_required():1207 if isinstance(self.child, XschemaElement):1208 if self.child.getAppInfo('recommended') == 'true':1209 logging.warn('{} is required, but tagged *recommended*'\1210 .format(self))1211 return 'REQUIRED'1212 else:1213 if isinstance(self.child, XschemaElement):1214 if self.child.getAppInfo('recommended') == 'true':1215 return 'RECOMMENDED'1216 return 'OPTIONAL'1217 def get_maxlength(self):1218 if isinstance(self.child, XschemaElementBase):1219 result = self.child.getRestrictionMaxLength()1220 if result != -1:1221 return result1222 return None1223class ClazzAttributeMember(ClazzBaseMember):1224 def __init__(self, source_clazz, name, child):1225 # the clazz where this member is embedded1226 self.source = source_clazz1227 # the name of the attribute1228 self.name = name1229 # the name of the base class1230 self.child = child1231 def get_data_type_chain(self):1232 return self.child.getType()1233 def get_data_type(self):1234 return self.child.getType()1235 # TODO1236 def is_required(self):1237 return 0 #(self.child.getMinOccurs() != 0)1238 def is_unbounded(self):1239 return 01240 def get_values(self):1241 return []1242class ClazzMember(ClazzBaseMember):1243 def __init__(self, source_clazz, name, child):1244 # the clazz where this member is embedded1245 self.source = source_clazz1246 # the name of the attribute1247 self.name = name1248 # the value (type) of this member1249 self.child = child1250 def get_data_type_chain(self):1251 return get_data_type_chain(self.child)1252 def get_data_type(self):1253 return get_data_type(self.child)1254 def is_required(self):1255 if isinstance(self.child, str):1256 return False1257 return (self.child.getMinOccurs() != 0)1258 def is_unbounded(self):1259 if isinstance(self.child, str):1260 return False1261 return (self.child.getMaxOccurs() > 1)1262 def get_values(self):1263 if isinstance(self.child, str):1264 return []1265 return self.child.getValues()...

Full Screen

Full Screen

generatedssuper.py

Source:generatedssuper.py Github

copy

Full Screen

...273 data_type = "string"274 string, help_attr = cls.extract_string_help_select(275 spec.get_name(), spec_doc, unique_labels276 )277 if len(spec.get_data_type_chain()) == 0 or not isinstance(278 spec.get_data_type_chain(), list279 ):280 original_st = data_type281 else:282 original_st = spec.get_data_type_chain()[0]283 if is_optional:284 options = 'string="{}"'.format(string)285 else:286 if len(string) + len(field_name) > 30:287 options = 'string="{}",\n xsd_required=True'.format(string)288 else:289 options = 'string="{}", xsd_required=True'.format(string)290 if choice is not None:291 options = """choice='{}',\n {}""".format(choice, options)292 options_nohelp = options293 if data_type in Simple_type_table: # and original_st != 'string':294 options = '{},\n xsd_type="{}"'.format(options, original_st)295 if help_attr:296 options = "{},\n {}".format(...

Full Screen

Full Screen

gends_generate_odoo.py

Source:gends_generate_odoo.py Github

copy

Full Screen

...136 need_textwrap = True137 for spec in cls.member_data_items_:138 if spec.get_container() == 1: # o2m139 name = spec.get_name()140 related = spec.get_data_type_chain()141 if isinstance(related, list):142 related = related[0]143 implicit_many2ones[related].append((class_name, name))144 data_type = spec.get_data_type()145 if len(spec.get_data_type_chain()) == 0:146 original_st = data_type147 else:148 original_st = spec.get_data_type_chain()[0]149 if Defined_simple_type_table.get(original_st):150 simple_type_usages[original_st].append(class_name)151 if spec.get_container() == 1:152 print(153 "!!!WARNING!!!"154 "\n%s of class %s"155 "\nis actually a multi-select"156 "\ninstead of a fields.Selection!"157 "\n!!!WARNING!!!" % (name, class_name)158 )159 # TODO if spec.get_container() == 1 then160 # it's a m2o of string class, like a multi-select161 # example cInfManu of type cInfManu_natCarga162 # in cte cteModalAereo that we currently deal...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful