How to use _name method in assertpy

Best Python code snippet using assertpy_python

event_rpcgen.py

Source:event_rpcgen.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright (c) 2005 Niels Provos <provos@citi.umich.edu>4# All rights reserved.5#6# Generates marshaling code based on libevent.7import sys8import re9#10_NAME = "event_rpcgen.py"11_VERSION = "0.1"12_STRUCT_RE = '[a-z][a-z_0-9]*'13# Globals14line_count = 015white = re.compile(r'^\s+')16cppcomment = re.compile(r'\/\/.*$')17headerdirect = []18cppdirect = []19# Holds everything that makes a struct20class Struct:21 def __init__(self, name):22 self._name = name23 self._entries = []24 self._tags = {}25 print >>sys.stderr, ' Created struct: %s' % name26 def AddEntry(self, entry):27 if self._tags.has_key(entry.Tag()):28 print >>sys.stderr, ( 'Entry "%s" duplicates tag number '29 '%d from "%s" around line %d' ) % (30 entry.Name(), entry.Tag(),31 self._tags[entry.Tag()], line_count)32 sys.exit(1)33 self._entries.append(entry)34 self._tags[entry.Tag()] = entry.Name()35 print >>sys.stderr, ' Added entry: %s' % entry.Name()36 def Name(self):37 return self._name38 def EntryTagName(self, entry):39 """Creates the name inside an enumeration for distinguishing data40 types."""41 name = "%s_%s" % (self._name, entry.Name())42 return name.upper()43 def PrintIdented(self, file, ident, code):44 """Takes an array, add indentation to each entry and prints it."""45 for entry in code:46 print >>file, '%s%s' % (ident, entry)47 def PrintTags(self, file):48 """Prints the tag definitions for a structure."""49 print >>file, '/* Tag definition for %s */' % self._name50 print >>file, 'enum %s_ {' % self._name.lower()51 for entry in self._entries:52 print >>file, ' %s=%d,' % (self.EntryTagName(entry),53 entry.Tag())54 print >>file, ' %s_MAX_TAGS' % (self._name.upper())55 print >>file, '};\n'56 def PrintForwardDeclaration(self, file):57 print >>file, 'struct %s;' % self._name58 def PrintDeclaration(self, file):59 print >>file, '/* Structure declaration for %s */' % self._name60 print >>file, 'struct %s_access_ {' % self._name61 for entry in self._entries:62 dcl = entry.AssignDeclaration('(*%s_assign)' % entry.Name())63 dcl.extend(64 entry.GetDeclaration('(*%s_get)' % entry.Name()))65 if entry.Array():66 dcl.extend(67 entry.AddDeclaration('(*%s_add)' % entry.Name()))68 self.PrintIdented(file, ' ', dcl)69 print >>file, '};\n'70 print >>file, 'struct %s {' % self._name71 print >>file, ' struct %s_access_ *base;\n' % self._name72 for entry in self._entries:73 dcl = entry.Declaration()74 self.PrintIdented(file, ' ', dcl)75 print >>file, ''76 for entry in self._entries:77 print >>file, ' ev_uint8_t %s_set;' % entry.Name()78 print >>file, '};\n'79 print >>file, \80"""struct %(name)s *%(name)s_new(void);81void %(name)s_free(struct %(name)s *);82void %(name)s_clear(struct %(name)s *);83void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);84int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);85int %(name)s_complete(struct %(name)s *);86void evtag_marshal_%(name)s(struct evbuffer *, ev_uint32_t, 87 const struct %(name)s *);88int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,89 struct %(name)s *);""" % { 'name' : self._name }90 # Write a setting function of every variable91 for entry in self._entries:92 self.PrintIdented(file, '', entry.AssignDeclaration(93 entry.AssignFuncName()))94 self.PrintIdented(file, '', entry.GetDeclaration(95 entry.GetFuncName()))96 if entry.Array():97 self.PrintIdented(file, '', entry.AddDeclaration(98 entry.AddFuncName()))99 print >>file, '/* --- %s done --- */\n' % self._name100 def PrintCode(self, file):101 print >>file, ('/*\n'102 ' * Implementation of %s\n'103 ' */\n') % self._name104 print >>file, \105 'static struct %(name)s_access_ __%(name)s_base = {' % \106 { 'name' : self._name }107 for entry in self._entries:108 self.PrintIdented(file, ' ', entry.CodeBase())109 print >>file, '};\n'110 # Creation111 print >>file, (112 'struct %(name)s *\n'113 '%(name)s_new(void)\n'114 '{\n'115 ' struct %(name)s *tmp;\n'116 ' if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {\n'117 ' event_warn("%%s: malloc", __func__);\n'118 ' return (NULL);\n'119 ' }\n'120 ' tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }121 for entry in self._entries:122 self.PrintIdented(file, ' ', entry.CodeNew('tmp'))123 print >>file, ' tmp->%s_set = 0;\n' % entry.Name()124 print >>file, (125 ' return (tmp);\n'126 '}\n')127 # Adding128 for entry in self._entries:129 if entry.Array():130 self.PrintIdented(file, '', entry.CodeAdd())131 print >>file, ''132 133 # Assigning134 for entry in self._entries:135 self.PrintIdented(file, '', entry.CodeAssign())136 print >>file, ''137 # Getting138 for entry in self._entries:139 self.PrintIdented(file, '', entry.CodeGet())140 print >>file, ''141 142 # Clearing143 print >>file, ( 'void\n'144 '%(name)s_clear(struct %(name)s *tmp)\n'145 '{'146 ) % { 'name' : self._name }147 for entry in self._entries:148 self.PrintIdented(file, ' ', entry.CodeClear('tmp'))149 print >>file, '}\n'150 # Freeing151 print >>file, ( 'void\n'152 '%(name)s_free(struct %(name)s *tmp)\n'153 '{'154 ) % { 'name' : self._name }155 156 for entry in self._entries:157 self.PrintIdented(file, ' ', entry.CodeFree('tmp'))158 print >>file, (' free(tmp);\n'159 '}\n')160 # Marshaling161 print >>file, ('void\n'162 '%(name)s_marshal(struct evbuffer *evbuf, '163 'const struct %(name)s *tmp)'164 '{') % { 'name' : self._name }165 for entry in self._entries:166 indent = ' '167 # Optional entries do not have to be set168 if entry.Optional():169 indent += ' '170 print >>file, ' if (tmp->%s_set) {' % entry.Name()171 self.PrintIdented(172 file, indent,173 entry.CodeMarshal('evbuf', self.EntryTagName(entry), 'tmp'))174 if entry.Optional():175 print >>file, ' }'176 print >>file, '}\n'177 178 # Unmarshaling179 print >>file, ('int\n'180 '%(name)s_unmarshal(struct %(name)s *tmp, '181 ' struct evbuffer *evbuf)\n'182 '{\n'183 ' ev_uint32_t tag;\n'184 ' while (EVBUFFER_LENGTH(evbuf) > 0) {\n'185 ' if (evtag_peek(evbuf, &tag) == -1)\n'186 ' return (-1);\n'187 ' switch (tag) {\n'188 ) % { 'name' : self._name }189 for entry in self._entries:190 print >>file, ' case %s:\n' % self.EntryTagName(entry)191 if not entry.Array():192 print >>file, (193 ' if (tmp->%s_set)\n'194 ' return (-1);'195 ) % (entry.Name())196 self.PrintIdented(197 file, ' ',198 entry.CodeUnmarshal('evbuf',199 self.EntryTagName(entry), 'tmp'))200 print >>file, ( ' tmp->%s_set = 1;\n' % entry.Name() +201 ' break;\n' )202 print >>file, ( ' default:\n'203 ' return -1;\n'204 ' }\n'205 ' }\n' )206 # Check if it was decoded completely207 print >>file, ( ' if (%(name)s_complete(tmp) == -1)\n'208 ' return (-1);'209 ) % { 'name' : self._name }210 # Successfully decoded211 print >>file, ( ' return (0);\n'212 '}\n')213 # Checking if a structure has all the required data214 print >>file, (215 'int\n'216 '%(name)s_complete(struct %(name)s *msg)\n'217 '{' ) % { 'name' : self._name }218 for entry in self._entries:219 self.PrintIdented(220 file, ' ',221 entry.CodeComplete('msg'))222 print >>file, (223 ' return (0);\n'224 '}\n' )225 # Complete message unmarshaling226 print >>file, (227 'int\n'228 'evtag_unmarshal_%(name)s(struct evbuffer *evbuf, '229 'ev_uint32_t need_tag, struct %(name)s *msg)\n'230 '{\n'231 ' ev_uint32_t tag;\n'232 ' int res = -1;\n'233 '\n'234 ' struct evbuffer *tmp = evbuffer_new();\n'235 '\n'236 ' if (evtag_unmarshal(evbuf, &tag, tmp) == -1'237 ' || tag != need_tag)\n'238 ' goto error;\n'239 '\n'240 ' if (%(name)s_unmarshal(msg, tmp) == -1)\n'241 ' goto error;\n'242 '\n'243 ' res = 0;\n'244 '\n'245 ' error:\n'246 ' evbuffer_free(tmp);\n'247 ' return (res);\n'248 '}\n' ) % { 'name' : self._name }249 # Complete message marshaling250 print >>file, (251 'void\n'252 'evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag, '253 'const struct %(name)s *msg)\n'254 '{\n'255 ' struct evbuffer *_buf = evbuffer_new();\n'256 ' assert(_buf != NULL);\n'257 ' evbuffer_drain(_buf, -1);\n'258 ' %(name)s_marshal(_buf, msg);\n'259 ' evtag_marshal(evbuf, tag, EVBUFFER_DATA(_buf), '260 'EVBUFFER_LENGTH(_buf));\n'261 ' evbuffer_free(_buf);\n'262 '}\n' ) % { 'name' : self._name }263class Entry:264 def __init__(self, type, name, tag):265 self._type = type266 self._name = name267 self._tag = int(tag)268 self._ctype = type269 self._optional = 0270 self._can_be_array = 0271 self._array = 0272 self._line_count = -1273 self._struct = None274 self._refname = None275 def GetTranslation(self):276 return { "parent_name" : self._struct.Name(),277 "name" : self._name,278 "ctype" : self._ctype,279 "refname" : self._refname280 }281 282 def SetStruct(self, struct):283 self._struct = struct284 def LineCount(self):285 assert self._line_count != -1286 return self._line_count287 def SetLineCount(self, number):288 self._line_count = number289 def Array(self):290 return self._array291 def Optional(self):292 return self._optional293 def Tag(self):294 return self._tag295 def Name(self):296 return self._name297 def Type(self):298 return self._type299 def MakeArray(self, yes=1):300 self._array = yes301 302 def MakeOptional(self):303 self._optional = 1304 def GetFuncName(self):305 return '%s_%s_get' % (self._struct.Name(), self._name)306 307 def GetDeclaration(self, funcname):308 code = [ 'int %s(struct %s *, %s *);' % (309 funcname, self._struct.Name(), self._ctype ) ]310 return code311 def CodeGet(self):312 code = (313 'int',314 '%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, '315 '%(ctype)s *value)',316 '{',317 ' if (msg->%(name)s_set != 1)',318 ' return (-1);',319 ' *value = msg->%(name)s_data;',320 ' return (0);',321 '}' )322 code = '\n'.join(code)323 code = code % self.GetTranslation()324 return code.split('\n')325 326 def AssignFuncName(self):327 return '%s_%s_assign' % (self._struct.Name(), self._name)328 329 def AddFuncName(self):330 return '%s_%s_add' % (self._struct.Name(), self._name)331 332 def AssignDeclaration(self, funcname):333 code = [ 'int %s(struct %s *, const %s);' % (334 funcname, self._struct.Name(), self._ctype ) ]335 return code336 def CodeAssign(self):337 code = [ 'int',338 '%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,'339 ' const %(ctype)s value)',340 '{',341 ' msg->%(name)s_set = 1;',342 ' msg->%(name)s_data = value;',343 ' return (0);',344 '}' ]345 code = '\n'.join(code)346 code = code % self.GetTranslation()347 return code.split('\n')348 def CodeClear(self, structname):349 code = [ '%s->%s_set = 0;' % (structname, self.Name()) ]350 return code351 352 def CodeComplete(self, structname):353 if self.Optional():354 return []355 356 code = [ 'if (!%s->%s_set)' % (structname, self.Name()),357 ' return (-1);' ]358 return code359 def CodeFree(self, name):360 return []361 def CodeBase(self):362 code = [363 '%(parent_name)s_%(name)s_assign,',364 '%(parent_name)s_%(name)s_get,'365 ]366 if self.Array():367 code.append('%(parent_name)s_%(name)s_add,')368 code = '\n'.join(code)369 code = code % self.GetTranslation()370 return code.split('\n')371 def Verify(self):372 if self.Array() and not self._can_be_array:373 print >>sys.stderr, (374 'Entry "%s" cannot be created as an array '375 'around line %d' ) % (self._name, self.LineCount())376 sys.exit(1)377 if not self._struct:378 print >>sys.stderr, (379 'Entry "%s" does not know which struct it belongs to '380 'around line %d' ) % (self._name, self.LineCount())381 sys.exit(1)382 if self._optional and self._array:383 print >>sys.stderr, ( 'Entry "%s" has illegal combination of '384 'optional and array around line %d' ) % (385 self._name, self.LineCount() )386 sys.exit(1)387class EntryBytes(Entry):388 def __init__(self, type, name, tag, length):389 # Init base class390 Entry.__init__(self, type, name, tag)391 self._length = length392 self._ctype = 'ev_uint8_t'393 def GetDeclaration(self, funcname):394 code = [ 'int %s(struct %s *, %s **);' % (395 funcname, self._struct.Name(), self._ctype ) ]396 return code397 398 def AssignDeclaration(self, funcname):399 code = [ 'int %s(struct %s *, const %s *);' % (400 funcname, self._struct.Name(), self._ctype ) ]401 return code402 403 def Declaration(self):404 dcl = ['ev_uint8_t %s_data[%s];' % (self._name, self._length)]405 406 return dcl407 def CodeGet(self):408 name = self._name409 code = [ 'int',410 '%s_%s_get(struct %s *msg, %s **value)' % (411 self._struct.Name(), name,412 self._struct.Name(), self._ctype),413 '{',414 ' if (msg->%s_set != 1)' % name,415 ' return (-1);',416 ' *value = msg->%s_data;' % name,417 ' return (0);',418 '}' ]419 return code420 421 def CodeAssign(self):422 name = self._name423 code = [ 'int',424 '%s_%s_assign(struct %s *msg, const %s *value)' % (425 self._struct.Name(), name,426 self._struct.Name(), self._ctype),427 '{',428 ' msg->%s_set = 1;' % name,429 ' memcpy(msg->%s_data, value, %s);' % (430 name, self._length),431 ' return (0);',432 '}' ]433 return code434 435 def CodeUnmarshal(self, buf, tag_name, var_name):436 code = [ 'if (evtag_unmarshal_fixed(%s, %s, ' % (buf, tag_name) +437 '%s->%s_data, ' % (var_name, self._name) +438 'sizeof(%s->%s_data)) == -1) {' % (439 var_name, self._name),440 ' event_warnx("%%s: failed to unmarshal %s", __func__);' % (441 self._name ),442 ' return (-1);',443 '}'444 ]445 return code446 def CodeMarshal(self, buf, tag_name, var_name):447 code = ['evtag_marshal(%s, %s, %s->%s_data, sizeof(%s->%s_data));' % (448 buf, tag_name, var_name, self._name, var_name, self._name )]449 return code450 def CodeClear(self, structname):451 code = [ '%s->%s_set = 0;' % (structname, self.Name()),452 'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (453 structname, self._name, structname, self._name)]454 return code455 456 def CodeNew(self, name):457 code = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (458 name, self._name, name, self._name)]459 return code460 def Verify(self):461 if not self._length:462 print >>sys.stderr, 'Entry "%s" needs a length around line %d' % (463 self._name, self.LineCount() )464 sys.exit(1)465 Entry.Verify(self)466class EntryInt(Entry):467 def __init__(self, type, name, tag):468 # Init base class469 Entry.__init__(self, type, name, tag)470 self._ctype = 'ev_uint32_t'471 def CodeUnmarshal(self, buf, tag_name, var_name):472 code = ['if (evtag_unmarshal_int(%s, %s, &%s->%s_data) == -1) {' % (473 buf, tag_name, var_name, self._name),474 ' event_warnx("%%s: failed to unmarshal %s", __func__);' % (475 self._name ),476 ' return (-1);',477 '}' ] 478 return code479 def CodeMarshal(self, buf, tag_name, var_name):480 code = ['evtag_marshal_int(%s, %s, %s->%s_data);' % (481 buf, tag_name, var_name, self._name)]482 return code483 def Declaration(self):484 dcl = ['ev_uint32_t %s_data;' % self._name]485 return dcl486 def CodeNew(self, name):487 code = ['%s->%s_data = 0;' % (name, self._name)]488 return code489class EntryString(Entry):490 def __init__(self, type, name, tag):491 # Init base class492 Entry.__init__(self, type, name, tag)493 self._ctype = 'char *'494 def CodeAssign(self):495 name = self._name496 code = """int497%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,498 const %(ctype)s value)499{500 if (msg->%(name)s_data != NULL)501 free(msg->%(name)s_data);502 if ((msg->%(name)s_data = strdup(value)) == NULL)503 return (-1);504 msg->%(name)s_set = 1;505 return (0);506}""" % self.GetTranslation()507 return code.split('\n')508 509 def CodeUnmarshal(self, buf, tag_name, var_name):510 code = ['if (evtag_unmarshal_string(%s, %s, &%s->%s_data) == -1) {' % (511 buf, tag_name, var_name, self._name),512 ' event_warnx("%%s: failed to unmarshal %s", __func__);' % (513 self._name ),514 ' return (-1);',515 '}'516 ]517 return code518 def CodeMarshal(self, buf, tag_name, var_name):519 code = ['evtag_marshal_string(%s, %s, %s->%s_data);' % (520 buf, tag_name, var_name, self._name)]521 return code522 def CodeClear(self, structname):523 code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),524 ' free (%s->%s_data);' % (structname, self.Name()),525 ' %s->%s_data = NULL;' % (structname, self.Name()),526 ' %s->%s_set = 0;' % (structname, self.Name()),527 '}'528 ]529 return code530 531 def CodeNew(self, name):532 code = ['%s->%s_data = NULL;' % (name, self._name)]533 return code534 def CodeFree(self, name):535 code = ['if (%s->%s_data != NULL)' % (name, self._name),536 ' free (%s->%s_data); ' % (name, self._name)]537 return code538 def Declaration(self):539 dcl = ['char *%s_data;' % self._name]540 return dcl541class EntryStruct(Entry):542 def __init__(self, type, name, tag, refname):543 # Init base class544 Entry.__init__(self, type, name, tag)545 self._can_be_array = 1546 self._refname = refname547 self._ctype = 'struct %s*' % refname548 def CodeGet(self):549 name = self._name550 code = [ 'int',551 '%s_%s_get(struct %s *msg, %s *value)' % (552 self._struct.Name(), name,553 self._struct.Name(), self._ctype),554 '{',555 ' if (msg->%s_set != 1) {' % name,556 ' msg->%s_data = %s_new();' % (name, self._refname),557 ' if (msg->%s_data == NULL)' % name,558 ' return (-1);',559 ' msg->%s_set = 1;' % name,560 ' }',561 ' *value = msg->%s_data;' % name,562 ' return (0);',563 '}' ]564 return code565 566 def CodeAssign(self):567 name = self._name568 code = """int569%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,570 const %(ctype)s value)571{572 struct evbuffer *tmp = NULL;573 if (msg->%(name)s_set) {574 %(refname)s_clear(msg->%(name)s_data);575 msg->%(name)s_set = 0;576 } else {577 msg->%(name)s_data = %(refname)s_new();578 if (msg->%(name)s_data == NULL) {579 event_warn("%%s: %(refname)s_new()", __func__);580 goto error;581 }582 }583 if ((tmp = evbuffer_new()) == NULL) {584 event_warn("%%s: evbuffer_new()", __func__);585 goto error;586 }587 %(refname)s_marshal(tmp, value);588 if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {589 event_warnx("%%s: %(refname)s_unmarshal", __func__);590 goto error;591 }592 msg->%(name)s_set = 1;593 evbuffer_free(tmp);594 return (0);595 error:596 if (tmp != NULL)597 evbuffer_free(tmp);598 if (msg->%(name)s_data != NULL) {599 %(refname)s_free(msg->%(name)s_data);600 msg->%(name)s_data = NULL;601 }602 return (-1);603}""" % self.GetTranslation()604 return code.split('\n')605 606 def CodeComplete(self, structname):607 if self.Optional():608 code = [ 'if (%s->%s_set && %s_complete(%s->%s_data) == -1)' % (609 structname, self.Name(),610 self._refname, structname, self.Name()),611 ' return (-1);' ]612 else:613 code = [ 'if (%s_complete(%s->%s_data) == -1)' % (614 self._refname, structname, self.Name()),615 ' return (-1);' ]616 return code617 618 def CodeUnmarshal(self, buf, tag_name, var_name):619 code = ['%s->%s_data = %s_new();' % (620 var_name, self._name, self._refname),621 'if (%s->%s_data == NULL)' % (var_name, self._name),622 ' return (-1);',623 'if (evtag_unmarshal_%s(%s, %s, %s->%s_data) == -1) {' % (624 self._refname, buf, tag_name, var_name, self._name),625 ' event_warnx("%%s: failed to unmarshal %s", __func__);' % (626 self._name ),627 ' return (-1);',628 '}'629 ]630 return code631 def CodeMarshal(self, buf, tag_name, var_name):632 code = ['evtag_marshal_%s(%s, %s, %s->%s_data);' % (633 self._refname, buf, tag_name, var_name, self._name)]634 return code635 def CodeClear(self, structname):636 code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),637 ' %s_free(%s->%s_data);' % (638 self._refname, structname, self.Name()),639 ' %s->%s_data = NULL;' % (structname, self.Name()),640 ' %s->%s_set = 0;' % (structname, self.Name()),641 '}'642 ]643 return code644 645 def CodeNew(self, name):646 code = ['%s->%s_data = NULL;' % (name, self._name)]647 return code648 def CodeFree(self, name):649 code = ['if (%s->%s_data != NULL)' % (name, self._name),650 ' %s_free(%s->%s_data); ' % (651 self._refname, name, self._name)]652 return code653 def Declaration(self):654 dcl = ['%s %s_data;' % (self._ctype, self._name)]655 return dcl656class EntryVarBytes(Entry):657 def __init__(self, type, name, tag):658 # Init base class659 Entry.__init__(self, type, name, tag)660 self._ctype = 'ev_uint8_t *'661 def GetDeclaration(self, funcname):662 code = [ 'int %s(struct %s *, %s *, ev_uint32_t *);' % (663 funcname, self._struct.Name(), self._ctype ) ]664 return code665 666 def AssignDeclaration(self, funcname):667 code = [ 'int %s(struct %s *, const %s, ev_uint32_t);' % (668 funcname, self._struct.Name(), self._ctype ) ]669 return code670 671 def CodeAssign(self):672 name = self._name673 code = [ 'int',674 '%s_%s_assign(struct %s *msg, '675 'const %s value, ev_uint32_t len)' % (676 self._struct.Name(), name,677 self._struct.Name(), self._ctype),678 '{',679 ' if (msg->%s_data != NULL)' % name,680 ' free (msg->%s_data);' % name,681 ' msg->%s_data = malloc(len);' % name,682 ' if (msg->%s_data == NULL)' % name,683 ' return (-1);',684 ' msg->%s_set = 1;' % name,685 ' msg->%s_length = len;' % name,686 ' memcpy(msg->%s_data, value, len);' % name,687 ' return (0);',688 '}' ]689 return code690 691 def CodeGet(self):692 name = self._name693 code = [ 'int',694 '%s_%s_get(struct %s *msg, %s *value, ev_uint32_t *plen)' % (695 self._struct.Name(), name,696 self._struct.Name(), self._ctype),697 '{',698 ' if (msg->%s_set != 1)' % name,699 ' return (-1);',700 ' *value = msg->%s_data;' % name,701 ' *plen = msg->%s_length;' % name,702 ' return (0);',703 '}' ]704 return code705 def CodeUnmarshal(self, buf, tag_name, var_name):706 code = ['if (evtag_payload_length(%s, &%s->%s_length) == -1)' % (707 buf, var_name, self._name),708 ' return (-1);',709 # We do not want DoS opportunities710 'if (%s->%s_length > EVBUFFER_LENGTH(%s))' % (711 var_name, self._name, buf),712 ' return (-1);',713 'if ((%s->%s_data = malloc(%s->%s_length)) == NULL)' % (714 var_name, self._name, var_name, self._name),715 ' return (-1);',716 'if (evtag_unmarshal_fixed(%s, %s, %s->%s_data, '717 '%s->%s_length) == -1) {' % (718 buf, tag_name, var_name, self._name, var_name, self._name),719 ' event_warnx("%%s: failed to unmarshal %s", __func__);' % (720 self._name ),721 ' return (-1);',722 '}'723 ]724 return code725 def CodeMarshal(self, buf, tag_name, var_name):726 code = ['evtag_marshal(%s, %s, %s->%s_data, %s->%s_length);' % (727 buf, tag_name, var_name, self._name, var_name, self._name)]728 return code729 def CodeClear(self, structname):730 code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),731 ' free (%s->%s_data);' % (structname, self.Name()),732 ' %s->%s_data = NULL;' % (structname, self.Name()),733 ' %s->%s_length = 0;' % (structname, self.Name()),734 ' %s->%s_set = 0;' % (structname, self.Name()),735 '}'736 ]737 return code738 739 def CodeNew(self, name):740 code = ['%s->%s_data = NULL;' % (name, self._name),741 '%s->%s_length = 0;' % (name, self._name) ]742 return code743 def CodeFree(self, name):744 code = ['if (%s->%s_data != NULL)' % (name, self._name),745 ' free (%s->%s_data); ' % (name, self._name)]746 return code747 def Declaration(self):748 dcl = ['ev_uint8_t *%s_data;' % self._name,749 'ev_uint32_t %s_length;' % self._name]750 return dcl751class EntryArray(Entry):752 def __init__(self, entry):753 # Init base class754 Entry.__init__(self, entry._type, entry._name, entry._tag)755 self._entry = entry756 self._refname = entry._refname757 self._ctype = 'struct %s *' % self._refname758 def GetDeclaration(self, funcname):759 """Allows direct access to elements of the array."""760 translate = self.GetTranslation()761 translate["funcname"] = funcname762 code = [763 'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %764 translate ]765 return code766 767 def AssignDeclaration(self, funcname):768 code = [ 'int %s(struct %s *, int, const %s);' % (769 funcname, self._struct.Name(), self._ctype ) ]770 return code771 772 def AddDeclaration(self, funcname):773 code = [ '%s %s(struct %s *);' % (774 self._ctype, funcname, self._struct.Name() ) ]775 return code776 777 def CodeGet(self):778 code = """int779%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,780 %(ctype)s *value)781{782 if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)783 return (-1);784 *value = msg->%(name)s_data[offset];785 return (0);786}""" % self.GetTranslation()787 return code.split('\n')788 789 def CodeAssign(self):790 code = """int791%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,792 const %(ctype)s value)793{794 struct evbuffer *tmp = NULL;795 if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)796 return (-1);797 %(refname)s_clear(msg->%(name)s_data[off]);798 if ((tmp = evbuffer_new()) == NULL) {799 event_warn("%%s: evbuffer_new()", __func__);800 goto error;801 }802 %(refname)s_marshal(tmp, value);803 if (%(refname)s_unmarshal(msg->%(name)s_data[off], tmp) == -1) {804 event_warnx("%%s: %(refname)s_unmarshal", __func__);805 goto error;806 }807 evbuffer_free(tmp);808 return (0);809error:810 if (tmp != NULL)811 evbuffer_free(tmp);812 %(refname)s_clear(msg->%(name)s_data[off]);813 return (-1);814}""" % self.GetTranslation()815 return code.split('\n')816 817 def CodeAdd(self):818 code = \819"""%(ctype)s820%(parent_name)s_%(name)s_add(struct %(parent_name)s *msg)821{822 if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {823 int tobe_allocated = msg->%(name)s_num_allocated;824 %(ctype)s* new_data = NULL;825 tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;826 new_data = (%(ctype)s*) realloc(msg->%(name)s_data,827 tobe_allocated * sizeof(%(ctype)s));828 if (new_data == NULL)829 goto error;830 msg->%(name)s_data = new_data;831 msg->%(name)s_num_allocated = tobe_allocated;832 }833 msg->%(name)s_data[msg->%(name)s_length - 1] = %(refname)s_new();834 if (msg->%(name)s_data[msg->%(name)s_length - 1] == NULL)835 goto error;836 msg->%(name)s_set = 1;837 return (msg->%(name)s_data[msg->%(name)s_length - 1]);838error:839 --msg->%(name)s_length;840 return (NULL);841}842 """ % self.GetTranslation()843 return code.split('\n')844 def CodeComplete(self, structname):845 code = []846 translate = self.GetTranslation()847 if self.Optional():848 code.append( 'if (%(structname)s->%(name)s_set)' % translate)849 translate["structname"] = structname850 tmp = """{851 int i;852 for (i = 0; i < %(structname)s->%(name)s_length; ++i) {853 if (%(refname)s_complete(%(structname)s->%(name)s_data[i]) == -1)854 return (-1);855 }856}""" % translate857 code.extend(tmp.split('\n'))858 return code859 860 def CodeUnmarshal(self, buf, tag_name, var_name):861 translate = self.GetTranslation()862 translate["var_name"] = var_name863 translate["buf"] = buf864 translate["tag_name"] = tag_name865 code = """if (%(parent_name)s_%(name)s_add(%(var_name)s) == NULL)866 return (-1);867if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag_name)s,868 %(var_name)s->%(name)s_data[%(var_name)s->%(name)s_length - 1]) == -1) {869 --%(var_name)s->%(name)s_length;870 event_warnx("%%s: failed to unmarshal %(name)s", __func__);871 return (-1);872}""" % translate873 return code.split('\n')874 def CodeMarshal(self, buf, tag_name, var_name):875 code = ['{',876 ' int i;',877 ' for (i = 0; i < %s->%s_length; ++i) {' % (878 var_name, self._name),879 ' evtag_marshal_%s(%s, %s, %s->%s_data[i]);' % (880 self._refname, buf, tag_name, var_name, self._name),881 ' }',882 '}'883 ]884 return code885 def CodeClear(self, structname):886 code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),887 ' int i;',888 ' for (i = 0; i < %s->%s_length; ++i) {' % (889 structname, self.Name()),890 ' %s_free(%s->%s_data[i]);' % (891 self._refname, structname, self.Name()),892 ' }',893 ' free(%s->%s_data);' % (structname, self.Name()),894 ' %s->%s_data = NULL;' % (structname, self.Name()),895 ' %s->%s_set = 0;' % (structname, self.Name()),896 ' %s->%s_length = 0;' % (structname, self.Name()),897 ' %s->%s_num_allocated = 0;' % (structname, self.Name()),898 '}'899 ]900 return code901 902 def CodeNew(self, name):903 code = ['%s->%s_data = NULL;' % (name, self._name),904 '%s->%s_length = 0;' % (name, self._name),905 '%s->%s_num_allocated = 0;' % (name, self._name)]906 return code907 def CodeFree(self, name):908 code = ['if (%s->%s_data != NULL) {' % (name, self._name),909 ' int i;',910 ' for (i = 0; i < %s->%s_length; ++i) {' % (911 name, self._name),912 ' %s_free(%s->%s_data[i]); ' % (913 self._refname, name, self._name),914 ' %s->%s_data[i] = NULL;' % (name, self._name),915 ' }',916 ' free(%s->%s_data);' % (name, self._name),917 ' %s->%s_data = NULL;' % (name, self._name),918 ' %s->%s_length = 0;' % (name, self._name),919 ' %s->%s_num_allocated = 0;' % (name, self._name),920 '}'921 ]922 return code923 def Declaration(self):924 dcl = ['struct %s **%s_data;' % (self._refname, self._name),925 'int %s_length;' % self._name,926 'int %s_num_allocated;' % self._name ]927 return dcl928def NormalizeLine(line):929 global white930 global cppcomment931 932 line = cppcomment.sub('', line)933 line = line.strip()934 line = white.sub(' ', line)935 return line936def ProcessOneEntry(newstruct, entry):937 optional = 0938 array = 0939 entry_type = ''940 name = ''941 tag = ''942 tag_set = None943 separator = ''944 fixed_length = ''945 tokens = entry.split(' ')946 while tokens:947 token = tokens[0]948 tokens = tokens[1:]949 if not entry_type:950 if not optional and token == 'optional':951 optional = 1952 continue953 if not array and token == 'array':954 array = 1955 continue956 if not entry_type:957 entry_type = token958 continue959 if not name:960 res = re.match(r'^([^\[\]]+)(\[.*\])?$', token)961 if not res:962 print >>sys.stderr, 'Cannot parse name: \"%s\" around %d' % (963 entry, line_count)964 sys.exit(1)965 name = res.group(1)966 fixed_length = res.group(2)967 if fixed_length:968 fixed_length = fixed_length[1:-1]969 continue970 if not separator:971 separator = token972 if separator != '=':973 print >>sys.stderr, 'Expected "=" after name \"%s\" got %s' % (974 name, token)975 sys.exit(1)976 continue977 if not tag_set:978 tag_set = 1979 if not re.match(r'^(0x)?[0-9]+$', token):980 print >>sys.stderr, 'Expected tag number: \"%s\"' % entry981 sys.exit(1)982 tag = int(token, 0)983 continue984 print >>sys.stderr, 'Cannot parse \"%s\"' % entry985 sys.exit(1)986 if not tag_set:987 print >>sys.stderr, 'Need tag number: \"%s\"' % entry988 sys.exit(1)989 # Create the right entry990 if entry_type == 'bytes':991 if fixed_length:992 newentry = EntryBytes(entry_type, name, tag, fixed_length)993 else:994 newentry = EntryVarBytes(entry_type, name, tag)995 elif entry_type == 'int' and not fixed_length:996 newentry = EntryInt(entry_type, name, tag)997 elif entry_type == 'string' and not fixed_length:998 newentry = EntryString(entry_type, name, tag)999 else:1000 res = re.match(r'^struct\[(%s)\]$' % _STRUCT_RE,1001 entry_type, re.IGNORECASE)1002 if res:1003 # References another struct defined in our file1004 newentry = EntryStruct(entry_type, name, tag, res.group(1))1005 else:1006 print >>sys.stderr, 'Bad type: "%s" in "%s"' % (entry_type, entry)1007 sys.exit(1)1008 structs = []1009 1010 if optional:1011 newentry.MakeOptional()1012 if array:1013 newentry.MakeArray()1014 newentry.SetStruct(newstruct)1015 newentry.SetLineCount(line_count)1016 newentry.Verify()1017 if array:1018 # We need to encapsulate this entry into a struct1019 newname = newentry.Name()+ '_array'1020 # Now borgify the new entry.1021 newentry = EntryArray(newentry)1022 newentry.SetStruct(newstruct)1023 newentry.SetLineCount(line_count)1024 newentry.MakeArray()1025 newstruct.AddEntry(newentry)1026 return structs1027def ProcessStruct(data):1028 tokens = data.split(' ')1029 # First three tokens are: 'struct' 'name' '{'1030 newstruct = Struct(tokens[1])1031 inside = ' '.join(tokens[3:-1])1032 tokens = inside.split(';')1033 structs = []1034 for entry in tokens:1035 entry = NormalizeLine(entry)1036 if not entry:1037 continue1038 # It's possible that new structs get defined in here1039 structs.extend(ProcessOneEntry(newstruct, entry))1040 structs.append(newstruct)1041 return structs1042def GetNextStruct(file):1043 global line_count1044 global cppdirect1045 got_struct = 01046 processed_lines = []1047 have_c_comment = 01048 data = ''1049 while 1:1050 line = file.readline()1051 if not line:1052 break1053 1054 line_count += 11055 line = line[:-1]1056 if not have_c_comment and re.search(r'/\*', line):1057 if re.search(r'/\*.*\*/', line):1058 line = re.sub(r'/\*.*\*/', '', line)1059 else:1060 line = re.sub(r'/\*.*$', '', line)1061 have_c_comment = 11062 if have_c_comment:1063 if not re.search(r'\*/', line):1064 continue1065 have_c_comment = 01066 line = re.sub(r'^.*\*/', '', line)1067 line = NormalizeLine(line)1068 if not line:1069 continue1070 if not got_struct:1071 if re.match(r'#include ["<].*[>"]', line):1072 cppdirect.append(line)1073 continue1074 1075 if re.match(r'^#(if( |def)|endif)', line):1076 cppdirect.append(line)1077 continue1078 if re.match(r'^#define', line):1079 headerdirect.append(line)1080 continue1081 if not re.match(r'^struct %s {$' % _STRUCT_RE,1082 line, re.IGNORECASE):1083 print >>sys.stderr, 'Missing struct on line %d: %s' % (1084 line_count, line)1085 sys.exit(1)1086 else:1087 got_struct = 11088 data += line1089 continue1090 # We are inside the struct1091 tokens = line.split('}')1092 if len(tokens) == 1:1093 data += ' ' + line1094 continue1095 if len(tokens[1]):1096 print >>sys.stderr, 'Trailing garbage after struct on line %d' % (1097 line_count )1098 sys.exit(1)1099 # We found the end of the struct1100 data += ' %s}' % tokens[0]1101 break1102 # Remove any comments, that might be in there1103 data = re.sub(r'/\*.*\*/', '', data)1104 1105 return data1106 1107def Parse(file):1108 """1109 Parses the input file and returns C code and corresponding header file.1110 """1111 entities = []1112 while 1:1113 # Just gets the whole struct nicely formatted1114 data = GetNextStruct(file)1115 if not data:1116 break1117 entities.extend(ProcessStruct(data))1118 return entities1119def GuardName(name):1120 name = '_'.join(name.split('.'))1121 name = '_'.join(name.split('/'))1122 guard = '_'+name.upper()+'_'1123 return guard1124def HeaderPreamble(name):1125 guard = GuardName(name)1126 pre = (1127 '/*\n'1128 ' * Automatically generated from %s\n'1129 ' */\n\n'1130 '#ifndef %s\n'1131 '#define %s\n\n' ) % (1132 name, guard, guard)1133 # insert stdint.h - let's hope everyone has it1134 pre += (1135 '#include <event-config.h>\n'1136 '#ifdef _EVENT_HAVE_STDINT_H\n'1137 '#include <stdint.h>\n'1138 '#endif\n' )1139 for statement in headerdirect:1140 pre += '%s\n' % statement1141 if headerdirect:1142 pre += '\n'1143 pre += (1144 '#define EVTAG_HAS(msg, member) ((msg)->member##_set == 1)\n'1145 '#ifdef __GNUC__\n'1146 '#define EVTAG_ASSIGN(msg, member, args...) '1147 '(*(msg)->base->member##_assign)(msg, ## args)\n'1148 '#define EVTAG_GET(msg, member, args...) '1149 '(*(msg)->base->member##_get)(msg, ## args)\n'1150 '#else\n'1151 '#define EVTAG_ASSIGN(msg, member, ...) '1152 '(*(msg)->base->member##_assign)(msg, ## __VA_ARGS__)\n'1153 '#define EVTAG_GET(msg, member, ...) '1154 '(*(msg)->base->member##_get)(msg, ## __VA_ARGS__)\n'1155 '#endif\n'1156 '#define EVTAG_ADD(msg, member) (*(msg)->base->member##_add)(msg)\n'1157 '#define EVTAG_LEN(msg, member) ((msg)->member##_length)\n'1158 )1159 return pre1160 1161def HeaderPostamble(name):1162 guard = GuardName(name)1163 return '#endif /* %s */' % guard1164def BodyPreamble(name):1165 global _NAME1166 global _VERSION1167 1168 header_file = '.'.join(name.split('.')[:-1]) + '.gen.h'1169 pre = ( '/*\n'1170 ' * Automatically generated from %s\n'1171 ' * by %s/%s. DO NOT EDIT THIS FILE.\n'1172 ' */\n\n' ) % (name, _NAME, _VERSION)1173 pre += ( '#include <sys/types.h>\n'1174 '#ifdef _EVENT_HAVE_SYS_TIME_H\n'1175 '#include <sys/time.h>\n'1176 '#endif\n'1177 '#include <stdlib.h>\n'1178 '#include <string.h>\n'1179 '#include <assert.h>\n'1180 '#define EVENT_NO_STRUCT\n'1181 '#include <event.h>\n\n'1182 '#ifdef _EVENT___func__\n'1183 '#define __func__ _EVENT___func__\n'1184 '#endif\n' )1185 for statement in cppdirect:1186 pre += '%s\n' % statement1187 1188 pre += '\n#include "%s"\n\n' % header_file1189 pre += 'void event_err(int eval, const char *fmt, ...);\n'1190 pre += 'void event_warn(const char *fmt, ...);\n'1191 pre += 'void event_errx(int eval, const char *fmt, ...);\n'1192 pre += 'void event_warnx(const char *fmt, ...);\n\n'1193 return pre1194def main(argv):1195 if len(argv) < 2 or not argv[1]:1196 print >>sys.stderr, 'Need RPC description file as first argument.'1197 sys.exit(1)1198 filename = argv[1]1199 ext = filename.split('.')[-1]1200 if ext != 'rpc':1201 print >>sys.stderr, 'Unrecognized file extension: %s' % ext1202 sys.exit(1)1203 print >>sys.stderr, 'Reading \"%s\"' % filename1204 fp = open(filename, 'r')1205 entities = Parse(fp)1206 fp.close()1207 header_file = '.'.join(filename.split('.')[:-1]) + '.gen.h'1208 impl_file = '.'.join(filename.split('.')[:-1]) + '.gen.c'1209 print >>sys.stderr, '... creating "%s"' % header_file1210 header_fp = open(header_file, 'w')1211 print >>header_fp, HeaderPreamble(filename)1212 # Create forward declarations: allows other structs to reference1213 # each other1214 for entry in entities:1215 entry.PrintForwardDeclaration(header_fp)1216 print >>header_fp, ''1217 for entry in entities:1218 entry.PrintTags(header_fp)1219 entry.PrintDeclaration(header_fp)1220 print >>header_fp, HeaderPostamble(filename)1221 header_fp.close()1222 print >>sys.stderr, '... creating "%s"' % impl_file1223 impl_fp = open(impl_file, 'w')1224 print >>impl_fp, BodyPreamble(filename)1225 for entry in entities:1226 entry.PrintCode(impl_fp)1227 impl_fp.close()1228if __name__ == '__main__':...

Full Screen

Full Screen

hr.py

Source:hr.py Github

copy

Full Screen

1# Copyright (c) 2013-2019 Philip Hane2# All rights reserved.3#4# Redistribution and use in source and binary forms, with or without5# modification, are permitted provided that the following conditions are met:6#7# 1. Redistributions of source code must retain the above copyright notice,8# this list of conditions and the following disclaimer.9# 2. Redistributions in binary form must reproduce the above copyright notice,10# this list of conditions and the following disclaimer in the documentation11# and/or other materials provided with the distribution.12#13# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"14# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE17# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR18# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF19# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS20# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN21# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)22# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE23# POSSIBILITY OF SUCH DAMAGE.24# TODO: Add '_links' for RFC/other references25HR_ASN = {26 'asn': {27 '_short': 'ASN',28 '_name': 'Autonomous System Number',29 '_description': 'Globally unique identifier used for routing '30 'information exchange with Autonomous Systems.'31 },32 'asn_cidr': {33 '_short': 'ASN CIDR Block',34 '_name': 'ASN Classless Inter-Domain Routing Block',35 '_description': 'Network routing block assigned to an ASN.'36 },37 'asn_country_code': {38 '_short': 'ASN Country Code',39 '_name': 'ASN Assigned Country Code',40 '_description': 'ASN assigned country code in ISO 3166-1 format.'41 },42 'asn_date': {43 '_short': 'ASN Date',44 '_name': 'ASN Allocation Date',45 '_description': 'ASN allocation date in ISO 8601 format.'46 },47 'asn_registry': {48 '_short': 'ASN Registry',49 '_name': 'ASN Assigned Registry',50 '_description': 'ASN assigned regional internet registry.'51 },52 'asn_description': {53 '_short': 'ASN Description',54 '_name': 'ASN Description',55 '_description': 'A brief description for the assigned ASN.'56 }57}58HR_ASN_ORIGIN = {59 'nets': {60 '_short': 'Network',61 '_name': 'ASN Network',62 '_description': 'A network associated with an Autonomous System Number'63 ' (ASN)',64 'cidr': {65 '_short': 'CIDR',66 '_name': 'Classless Inter-Domain Routing Block',67 '_description': 'The network routing block.'68 },69 'description': {70 '_short': 'Description',71 '_name': 'Description',72 '_description': 'Description for the registered network.'73 },74 'maintainer': {75 '_short': 'Maintainer',76 '_name': 'Maintainer',77 '_description': 'The entity that maintains the network.'78 },79 'updated': {80 '_short': 'Updated',81 '_name': 'Updated Timestamp',82 '_description': 'Network registration updated information.'83 },84 'source': {85 '_short': 'Source',86 '_name': 'ASN Network Information Source',87 '_description': 'The source of the network information.'88 }89 }90}91HR_RDAP_COMMON = {92 'entities': {93 '_short': 'Entities',94 '_name': 'RIR Object Entities',95 '_description': 'List of object names referenced by an RIR object.'96 },97 'events': {98 '_short': 'Events',99 '_name': 'Events',100 '_description': 'Events for an RIR object.',101 'action': {102 '_short': 'Action',103 '_name': 'Event Action (Reason)',104 '_description': 'The reason for an event.'105 },106 'timestamp': {107 '_short': 'Timestamp',108 '_name': 'Event Timestamp',109 '_description': 'The date an event occured in ISO 8601 '110 'format.'111 },112 'actor': {113 '_short': 'Actor',114 '_name': 'Event Actor',115 '_description': 'The identifier for an event initiator.'116 }117 },118 'handle': {119 '_short': 'Handle',120 '_name': 'RIR Handle',121 '_description': 'Unique identifier for a registered object.'122 },123 'links': {124 '_short': 'Links',125 '_name': 'Links',126 '_description': 'HTTP/HTTPS links provided for an RIR object.'127 },128 'notices': {129 '_short': 'Notices',130 '_name': 'Notices',131 '_description': 'Notices for an RIR object.',132 'description': {133 '_short': 'Description',134 '_name': 'Notice Description',135 '_description': 'The description/body of a notice.'136 },137 'title': {138 '_short': 'Title',139 '_name': 'Notice Title',140 '_description': 'The title/header for a notice.'141 },142 'links': {143 '_short': 'Links',144 '_name': 'Notice Links',145 '_description': 'HTTP/HTTPS links provided for a notice.'146 }147 },148 'remarks': {149 '_short': 'Remarks',150 '_name': 'Remarks',151 '_description': 'Remarks for an RIR object.',152 'description': {153 '_short': 'Description',154 '_name': 'Remark Description',155 '_description': 'The description/body of a remark.'156 },157 'title': {158 '_short': 'Title',159 '_name': 'Remark Title',160 '_description': 'The title/header for a remark.'161 },162 'links': {163 '_short': 'Links',164 '_name': 'Remark Links',165 '_description': 'HTTP/HTTPS links provided for a remark.'166 }167 },168 'status': {169 '_short': 'Status',170 '_name': 'Object Status',171 '_description': 'List indicating the state of a registered object.'172 }173}174HR_RDAP = {175 'network': {176 '_short': 'Network',177 '_name': 'RIR Network',178 '_description': 'The assigned network for an IP address.',179 'cidr': {180 '_short': 'CIDR Block',181 '_name': 'Classless Inter-Domain Routing Block',182 '_description': 'Network routing block an IP address belongs to.'183 },184 'country': {185 '_short': 'Country Code',186 '_name': 'Country Code',187 '_description': 'Country code registered with the RIR in '188 'ISO 3166-1 format.'189 },190 'end_address': {191 '_short': 'End Address',192 '_name': 'Ending IP Address',193 '_description': 'The last IP address in a network block.'194 },195 'events': HR_RDAP_COMMON['events'],196 'handle': HR_RDAP_COMMON['handle'],197 'ip_version': {198 '_short': 'IP Version',199 '_name': 'IP Protocol Version',200 '_description': 'The IP protocol version (v4 or v6) of an IP '201 'address.'202 },203 'links': HR_RDAP_COMMON['links'],204 'name': {205 '_short': 'Name',206 '_name': 'RIR Network Name',207 '_description': 'The identifier assigned to the network '208 'registration for an IP address.'209 },210 'notices': HR_RDAP_COMMON['notices'],211 'parent_handle': {212 '_short': 'Parent Handle',213 '_name': 'RIR Parent Handle',214 '_description': 'Unique identifier for the parent network of '215 'a registered network.'216 },217 'remarks': HR_RDAP_COMMON['remarks'],218 'start_address': {219 '_short': 'Start Address',220 '_name': 'Starting IP Address',221 '_description': 'The first IP address in a network block.'222 },223 'status': HR_RDAP_COMMON['status'],224 'type': {225 '_short': 'Type',226 '_name': 'RIR Network Type',227 '_description': 'The RIR classification of a registered network.'228 }229 },230 'entities': HR_RDAP_COMMON['entities'],231 'objects': {232 '_short': 'Objects',233 '_name': 'RIR Objects',234 '_description': 'The objects (entities) referenced by an RIR network.',235 'contact': {236 '_short': 'Contact',237 '_name': 'Contact Information',238 '_description': 'Contact information registered with an RIR '239 'object.',240 'address': {241 '_short': 'Address',242 '_name': 'Postal Address',243 '_description': 'The contact postal address.'244 },245 'email': {246 '_short': 'Email',247 '_name': 'Email Address',248 '_description': 'The contact email address.'249 },250 'kind': {251 '_short': 'Kind',252 '_name': 'Kind',253 '_description': 'The contact information kind (individual, '254 'group, org, etc).'255 },256 'name': {257 '_short': 'Name',258 '_name': 'Name',259 '_description': 'The contact name.'260 },261 'phone': {262 '_short': 'Phone',263 '_name': 'Phone Number',264 '_description': 'The contact phone number.'265 },266 'role': {267 '_short': 'Role',268 '_name': 'Role',269 '_description': 'The contact\'s role.'270 },271 'title': {272 '_short': 'Title',273 '_name': 'Title',274 '_description': 'The contact\'s position or job title.'275 }276 },277 'entities': HR_RDAP_COMMON['entities'],278 'events': HR_RDAP_COMMON['events'],279 'events_actor': {280 '_short': 'Events Misc',281 '_name': 'Events w/o Actor',282 '_description': 'An event for an RIR object with no event actor.',283 'action': {284 '_short': 'Action',285 '_name': 'Event Action (Reason)',286 '_description': 'The reason for an event.'287 },288 'timestamp': {289 '_short': 'Timestamp',290 '_name': 'Event Timestamp',291 '_description': 'The date an event occured in ISO 8601 '292 'format.'293 }294 },295 'handle': HR_RDAP_COMMON['handle'],296 'links': HR_RDAP_COMMON['links'],297 'notices': HR_RDAP_COMMON['notices'],298 'remarks': HR_RDAP_COMMON['remarks'],299 'roles': {300 '_short': 'Roles',301 '_name': 'Roles',302 '_description': 'List of roles assigned to a registered object.'303 },304 'status': HR_RDAP_COMMON['status'],305 }306}307HR_WHOIS = {308 'nets': {309 '_short': 'Network',310 '_name': 'RIR Network',311 '_description': 'The assigned network for an IP address. May be a '312 'parent or child network.',313 'address': {314 '_short': 'Address',315 '_name': 'Postal Address',316 '_description': 'The contact postal address.'317 },318 'cidr': {319 '_short': 'CIDR Blocks',320 '_name': 'Classless Inter-Domain Routing Blocks',321 '_description': 'Network routing blocks an IP address belongs to.'322 },323 'city': {324 '_short': 'City',325 '_name': 'City',326 '_description': 'The city registered with a whois network.'327 },328 'country': {329 '_short': 'Country Code',330 '_name': 'Country Code',331 '_description': 'Country code registered for the network in '332 'ISO 3166-1 format.'333 },334 'created': {335 '_short': 'Created',336 '_name': 'Created Timestamp',337 '_description': 'The date the network was created in ISO 8601 '338 'format.'339 },340 'description': {341 '_short': 'Description',342 '_name': 'Description',343 '_description': 'The description for the network.'344 },345 'emails': {346 '_short': 'Emails',347 '_name': 'Email Addresses',348 '_description': 'The contact email addresses.'349 },350 'handle': {351 '_short': 'Handle',352 '_name': 'RIR Network Handle',353 '_description': 'Unique identifier for a registered network.'354 },355 'name': {356 '_short': 'Name',357 '_name': 'RIR Network Name',358 '_description': 'The identifier assigned to the network '359 'registration for an IP address.'360 },361 'postal_code': {362 '_short': 'Postal',363 '_name': 'Postal Code',364 '_description': 'The postal code registered with a whois network.'365 },366 'range': {367 '_short': 'Ranges',368 '_name': 'CIDR Block Ranges',369 '_description': 'Network routing blocks an IP address belongs to.'370 },371 'state': {372 '_short': 'State',373 '_name': 'State',374 '_description': 'The state registered with a whois network.'375 },376 'updated': {377 '_short': 'Updated',378 '_name': 'Updated Timestamp',379 '_description': 'The date the network was updated in ISO 8601 '380 'format.'381 }382 },383 'referral': {384 '_short': 'Referral',385 '_name': 'Referral Whois',386 '_description': 'The referral whois data if referenced and enabled.',387 }388}389HR_WHOIS_NIR = {390 'nets': {391 '_short': 'NIR Network',392 '_name': 'National Internet Registry Network',393 '_description': 'The assigned NIR (JPNIC, KRNIC) network for an IP '394 'address. May be a parent or child network.',395 'address': {396 '_short': 'Address',397 '_name': 'Postal Address',398 '_description': 'The network contact postal address.'399 },400 'cidr': {401 '_short': 'CIDR Blocks',402 '_name': 'Classless Inter-Domain Routing Blocks',403 '_description': 'Network routing blocks an IP address belongs to.'404 },405 'country': {406 '_short': 'Country Code',407 '_name': 'Country Code',408 '_description': 'Country code registered for the network in '409 'ISO 3166-1 format.'410 },411 'handle': {412 '_short': 'Handle',413 '_name': 'NIR Network Handle',414 '_description': 'Unique identifier for a registered NIR network.'415 },416 'name': {417 '_short': 'Name',418 '_name': 'NIR Network Name',419 '_description': 'The identifier assigned to the network '420 'registration for an IP address.'421 },422 'postal_code': {423 '_short': 'Postal',424 '_name': 'Postal Code',425 '_description': 'The postal code registered with a NIR network.'426 },427 'range': {428 '_short': 'Ranges',429 '_name': 'CIDR Block Ranges',430 '_description': 'Network routing blocks an IP address belongs to.'431 },432 'nameservers': {433 '_short': 'NS',434 '_name': 'Nameservers',435 '_description': 'Nameservers associated with a NIR network.'436 },437 'created': {438 '_short': 'Created',439 '_name': 'Created Timestamp',440 '_description': 'The date the network was created in ISO 8601 '441 'format.'442 },443 'updated': {444 '_short': 'Updated',445 '_name': 'Updated Timestamp',446 '_description': 'The date the network was updated in ISO 8601 '447 'format.'448 },449 'contacts': {450 '_short': 'Contacts',451 '_name': 'NIR Contacts',452 '_description': 'The contacts (admin, tech) registered with a NIR '453 'network.',454 'organization': {455 '_short': 'Org',456 '_name': 'Organization',457 '_description': 'The contact organization.'458 },459 'division': {460 '_short': 'Div',461 '_name': 'Division',462 '_description': 'The contact division of the organization.'463 },464 'name': {465 '_short': 'Name',466 '_name': 'Name',467 '_description': 'The contact name.'468 },469 'title': {470 '_short': 'Title',471 '_name': 'Title',472 '_description': 'The contact position or job title.'473 },474 'phone': {475 '_short': 'Phone',476 '_name': 'Phone Number',477 '_description': 'The contact phone number.'478 },479 'fax': {480 '_short': 'Fax',481 '_name': 'Fax Number',482 '_description': 'The contact fax number.'483 },484 'email': {485 '_short': 'Email',486 '_name': 'Email Address',487 '_description': 'The contact email address.'488 },489 'reply_email': {490 '_short': 'Reply Email',491 '_name': 'Reply Email Address',492 '_description': 'The contact reply email address.'493 },494 'updated': {495 '_short': 'Updated',496 '_name': 'Updated Timestamp',497 '_description': 'The date the contact was updated in ISO 8601 '498 'format.'499 }500 }501 }...

Full Screen

Full Screen

test_models.py

Source:test_models.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2from odoo import fields, models3def name(suffix_name):4 return 'base_import.tests.models.%s' % suffix_name5class Char(models.Model):6 _name = name('char')7 value = fields.Char()8class CharRequired(models.Model):9 _name = name('char.required')10 value = fields.Char(required=True)11class CharReadonly(models.Model):12 _name = name('char.readonly')13 value = fields.Char(readonly=True)14class CharStates(models.Model):15 _name = name('char.states')16 value = fields.Char(readonly=True, states={'draft': [('readonly', False)]})17class CharNoreadonly(models.Model):18 _name = name('char.noreadonly')19 value = fields.Char(readonly=True, states={'draft': [('invisible', True)]})20class CharStillreadonly(models.Model):21 _name = name('char.stillreadonly')22 value = fields.Char(readonly=True, states={'draft': [('readonly', True)]})23# TODO: complex field (m2m, o2m, m2o)24class M2o(models.Model):25 _name = name('m2o')26 value = fields.Many2one(name('m2o.related'))27class M2oRelated(models.Model):28 _name = name('m2o.related')29 value = fields.Integer(default=42)30class M2oRequired(models.Model):31 _name = name('m2o.required')32 value = fields.Many2one(name('m2o.required.related'), required=True)33class M2oRequiredRelated(models.Model):34 _name = name('m2o.required.related')35 value = fields.Integer(default=42)36class O2m(models.Model):37 _name = name('o2m')38 value = fields.One2many(name('o2m.child'), 'parent_id')39class O2mChild(models.Model):40 _name = name('o2m.child')41 parent_id = fields.Many2one(name('o2m'))42 value = fields.Integer()43class PreviewModel(models.Model):44 _name = name('preview')45 name = fields.Char('Name')46 somevalue = fields.Integer(string='Some Value', required=True)...

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 assertpy 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