How to use _command_args method in molecule

Best Python code snippet using molecule_python

volatile.py

Source:volatile.py Github

copy

Full Screen

...68 __next__ = next69class VolatileValue(object):70 def __repr__(self):71 return "<%s>" % self.__class__.__name__72 def _command_args(self):73 return ''74 def command(self):75 return "%s(%s)" % (self.__class__.__name__, self._command_args())76 def __eq__(self, other):77 x = self._fix()78 y = other._fix() if isinstance(other, VolatileValue) else other79 if not isinstance(x, type(y)):80 return False81 return x == y82 def __ne__(self, other):83 # Python 2.7 compat84 return not self == other85 __hash__ = None86 def __getattr__(self, attr):87 if attr in ["__setstate__", "__getstate__"]:88 raise AttributeError(attr)89 return getattr(self._fix(), attr)90 def __str__(self):91 return str(self._fix())92 def __bytes__(self):93 return bytes_encode(self._fix())94 def __len__(self):95 return len(self._fix())96 def copy(self):97 return copy.copy(self)98 def _fix(self):99 return None100class RandField(VolatileValue):101 pass102class _RandNumeral(RandField):103 """Implements integer management in RandField"""104 def __int__(self):105 return int(self._fix())106 def __index__(self):107 return int(self)108 def __nonzero__(self):109 return bool(self._fix())110 __bool__ = __nonzero__111 def __add__(self, other):112 return self._fix() + other113 def __radd__(self, other):114 return other + self._fix()115 def __sub__(self, other):116 return self._fix() - other117 def __rsub__(self, other):118 return other - self._fix()119 def __mul__(self, other):120 return self._fix() * other121 def __rmul__(self, other):122 return other * self._fix()123 def __floordiv__(self, other):124 return self._fix() / other125 __div__ = __floordiv__126 def __lt__(self, other):127 return self._fix() < other128 def __le__(self, other):129 return self._fix() <= other130 def __ge__(self, other):131 return self._fix() >= other132 def __gt__(self, other):133 return self._fix() > other134 def __lshift__(self, other):135 return self._fix() << other136 def __rshift__(self, other):137 return self._fix() >> other138 def __and__(self, other):139 return self._fix() & other140 def __rand__(self, other):141 return other & self._fix()142 def __or__(self, other):143 return self._fix() | other144 def __ror__(self, other):145 return other | self._fix()146class RandNum(_RandNumeral):147 """Instances evaluate to random integers in selected range"""148 min = 0149 max = 0150 def __init__(self, min, max):151 self.min = min152 self.max = max153 def _command_args(self):154 if self.__class__.__name__ == 'RandNum':155 return "min=%r, max=%r" % (self.min, self.max)156 return super(RandNum, self)._command_args()157 def _fix(self):158 return random.randrange(self.min, self.max + 1)159class RandFloat(RandNum):160 def _fix(self):161 return random.uniform(self.min, self.max)162class RandBinFloat(RandNum):163 def _fix(self):164 return struct.unpack("!f", bytes(RandBin(4)))[0]165class RandNumGamma(_RandNumeral):166 def __init__(self, alpha, beta):167 self.alpha = alpha168 self.beta = beta169 def _command_args(self):170 return "alpha=%r, beta=%r" % (self.alpha, self.beta)171 def _fix(self):172 return int(round(random.gammavariate(self.alpha, self.beta)))173class RandNumGauss(_RandNumeral):174 def __init__(self, mu, sigma):175 self.mu = mu176 self.sigma = sigma177 def _command_args(self):178 return "mu=%r, sigma=%r" % (self.mu, self.sigma)179 def _fix(self):180 return int(round(random.gauss(self.mu, self.sigma)))181class RandNumExpo(_RandNumeral):182 def __init__(self, lambd, base=0):183 self.lambd = lambd184 self.base = base185 def _command_args(self):186 ret = "lambd=%r" % self.lambd187 if self.base != 0:188 ret += ", base=%r" % self.base189 return ret190 def _fix(self):191 return self.base + int(round(random.expovariate(self.lambd)))192class RandEnum(RandNum):193 """Instances evaluate to integer sampling without replacement from the given interval""" # noqa: E501194 def __init__(self, min, max, seed=None):195 self._seed = seed196 self.seq = RandomEnumeration(min, max, seed)197 super(RandEnum, self).__init__(min, max)198 def _command_args(self):199 ret = "min=%r, max=%r" % (self.min, self.max)200 if self._seed:201 ret += ", seed=%r" % self._seed202 return ret203 def _fix(self):204 return next(self.seq)205class RandByte(RandNum):206 def __init__(self):207 RandNum.__init__(self, 0, 2**8 - 1)208class RandSByte(RandNum):209 def __init__(self):210 RandNum.__init__(self, -2**7, 2**7 - 1)211class RandShort(RandNum):212 def __init__(self):213 RandNum.__init__(self, 0, 2**16 - 1)214class RandSShort(RandNum):215 def __init__(self):216 RandNum.__init__(self, -2**15, 2**15 - 1)217class RandInt(RandNum):218 def __init__(self):219 RandNum.__init__(self, 0, 2**32 - 1)220class RandSInt(RandNum):221 def __init__(self):222 RandNum.__init__(self, -2**31, 2**31 - 1)223class RandLong(RandNum):224 def __init__(self):225 RandNum.__init__(self, 0, 2**64 - 1)226class RandSLong(RandNum):227 def __init__(self):228 RandNum.__init__(self, -2**63, 2**63 - 1)229class RandEnumByte(RandEnum):230 def __init__(self):231 RandEnum.__init__(self, 0, 2**8 - 1)232class RandEnumSByte(RandEnum):233 def __init__(self):234 RandEnum.__init__(self, -2**7, 2**7 - 1)235class RandEnumShort(RandEnum):236 def __init__(self):237 RandEnum.__init__(self, 0, 2**16 - 1)238class RandEnumSShort(RandEnum):239 def __init__(self):240 RandEnum.__init__(self, -2**15, 2**15 - 1)241class RandEnumInt(RandEnum):242 def __init__(self):243 RandEnum.__init__(self, 0, 2**32 - 1)244class RandEnumSInt(RandEnum):245 def __init__(self):246 RandEnum.__init__(self, -2**31, 2**31 - 1)247class RandEnumLong(RandEnum):248 def __init__(self):249 RandEnum.__init__(self, 0, 2**64 - 1)250class RandEnumSLong(RandEnum):251 def __init__(self):252 RandEnum.__init__(self, -2**63, 2**63 - 1)253class RandEnumKeys(RandEnum):254 """Picks a random value from dict keys list. """255 def __init__(self, enum, seed=None):256 self.enum = list(enum)257 RandEnum.__init__(self, 0, len(self.enum) - 1, seed)258 def _command_args(self):259 # Note: only outputs the list of keys, but values are irrelevant anyway260 ret = "enum=%r" % self.enum261 if self._seed:262 ret += ", seed=%r" % self._seed263 return ret264 def _fix(self):265 return self.enum[next(self.seq)]266class RandChoice(RandField):267 def __init__(self, *args):268 if not args:269 raise TypeError("RandChoice needs at least one choice")270 self._choice = list(args)271 def _command_args(self):272 return ", ".join(self._choice)273 def _fix(self):274 return random.choice(self._choice)275class RandString(RandField):276 _DEFAULT_CHARS = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" # noqa: E501277 def __init__(self, size=None, chars=_DEFAULT_CHARS):278 if size is None:279 size = RandNumExpo(0.01)280 self.size = size281 self.chars = chars282 def _command_args(self):283 ret = ""284 if isinstance(self.size, VolatileValue):285 if self.size.lambd != 0.01 or self.size.base != 0:286 ret += "size=%r" % self.size.command()287 else:288 ret += "size=%r" % self.size289 if self.chars != self._DEFAULT_CHARS:290 ret += ", chars=%r" % self.chars291 return ret292 def _fix(self):293 s = b""294 for _ in range(self.size):295 rdm_chr = random.choice(self.chars)296 s += rdm_chr if isinstance(rdm_chr, str) else chb(rdm_chr)297 return s298 def __str__(self):299 return plain_str(self._fix())300 def __bytes__(self):301 return bytes_encode(self._fix())302 def __mul__(self, n):303 return self._fix() * n304class RandBin(RandString):305 def __init__(self, size=None):306 super(RandBin, self).__init__(size=size, chars=b"".join(chb(c) for c in range(256))) # noqa: E501307 def _command_args(self):308 if not isinstance(self.size, VolatileValue):309 return "size=%r" % self.size310 if isinstance(self.size, RandNumExpo) and \311 self.size.lambd == 0.01 and self.size.base == 0:312 # Default size for RandString, skip313 return ""314 return "size=%r" % self.size.command()315class RandTermString(RandBin):316 def __init__(self, size, term):317 self.term = bytes_encode(term)318 super(RandTermString, self).__init__(size=size)319 def _command_args(self):320 return ", ".join((super(RandTermString, self)._command_args(),321 "term=%r" % self.term))322 def _fix(self):323 return RandBin._fix(self) + self.term324class RandIP(RandString):325 _DEFAULT_IPTEMPLATE = "0.0.0.0/0"326 def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):327 RandString.__init__(self)328 self.ip = Net(iptemplate)329 def _command_args(self):330 if self.ip.repr == self._DEFAULT_IPTEMPLATE:331 return ""332 return "iptemplate=%r" % self.ip.repr333 def _fix(self):334 return self.ip.choice()335class RandMAC(RandString):336 def __init__(self, template="*"):337 RandString.__init__(self)338 self._template = template339 template += ":*:*:*:*:*"340 template = template.split(":")341 self.mac = ()342 for i in range(6):343 if template[i] == "*":344 v = RandByte()345 elif "-" in template[i]:346 x, y = template[i].split("-")347 v = RandNum(int(x, 16), int(y, 16))348 else:349 v = int(template[i], 16)350 self.mac += (v,)351 def _command_args(self):352 if self._template == "*":353 return ""354 return "template=%r" % self._template355 def _fix(self):356 return "%02x:%02x:%02x:%02x:%02x:%02x" % self.mac357class RandIP6(RandString):358 def __init__(self, ip6template="**"):359 RandString.__init__(self)360 self.tmpl = ip6template361 self.sp = self.tmpl.split(":")362 for i, v in enumerate(self.sp):363 if not v or v == "**":364 continue365 if "-" in v:366 a, b = v.split("-")367 elif v == "*":368 a = b = ""369 else:370 a = b = v371 if not a:372 a = "0"373 if not b:374 b = "ffff"375 if a == b:376 self.sp[i] = int(a, 16)377 else:378 self.sp[i] = RandNum(int(a, 16), int(b, 16))379 self.variable = "" in self.sp380 self.multi = self.sp.count("**")381 def _command_args(self):382 if self.tmpl == "**":383 return ""384 return "ip6template=%r" % self.tmpl385 def _fix(self):386 nbm = self.multi387 ip = []388 for i, n in enumerate(self.sp):389 if n == "**":390 nbm -= 1391 remain = 8 - (len(self.sp) - i - 1) - len(ip) + nbm392 if "" in self.sp:393 remain += 1394 if nbm or self.variable:395 remain = random.randint(0, remain)396 for j in range(remain):397 ip.append("%04x" % random.randint(0, 65535))398 elif isinstance(n, RandNum):399 ip.append("%04x" % n)400 elif n == 0:401 ip.append("0")402 elif not n:403 ip.append("")404 else:405 ip.append("%04x" % n)406 if len(ip) == 9:407 ip.remove("")408 if ip[-1] == "":409 ip[-1] = "0"410 return ":".join(ip)411class RandOID(RandString):412 def __init__(self, fmt=None, depth=RandNumExpo(0.1), idnum=RandNumExpo(0.01)): # noqa: E501413 RandString.__init__(self)414 self.ori_fmt = fmt415 if fmt is not None:416 fmt = fmt.split(".")417 for i in range(len(fmt)):418 if "-" in fmt[i]:419 fmt[i] = tuple(map(int, fmt[i].split("-")))420 self.fmt = fmt421 self.depth = depth422 self.idnum = idnum423 def _command_args(self):424 ret = []425 if self.fmt:426 ret.append("fmt=%r" % self.ori_fmt)427 if not isinstance(self.depth, VolatileValue):428 ret.append("depth=%r" % self.depth)429 elif not isinstance(self.depth, RandNumExpo) or \430 self.depth.lambd != 0.1 or self.depth.base != 0:431 ret.append("depth=%s" % self.depth.command())432 if not isinstance(self.idnum, VolatileValue):433 ret.append("idnum=%r" % self.idnum)434 elif not isinstance(self.idnum, RandNumExpo) or \435 self.idnum.lambd != 0.01 or self.idnum.base != 0:436 ret.append("idnum=%s" % self.idnum.command())437 return ", ".join(ret)438 def __repr__(self):439 if self.ori_fmt is None:440 return "<%s>" % self.__class__.__name__441 else:442 return "<%s [%s]>" % (self.__class__.__name__, self.ori_fmt)443 def _fix(self):444 if self.fmt is None:445 return ".".join(str(self.idnum) for _ in range(1 + self.depth))446 else:447 oid = []448 for i in self.fmt:449 if i == "*":450 oid.append(str(self.idnum))451 elif i == "**":452 oid += [str(self.idnum) for i in range(1 + self.depth)]453 elif isinstance(i, tuple):454 oid.append(str(random.randrange(*i)))455 else:456 oid.append(i)457 return ".".join(oid)458class RandRegExp(RandField):459 def __init__(self, regexp, lambda_=0.3,):460 self._regexp = regexp461 self._lambda = lambda_462 def _command_args(self):463 ret = "regexp=%r" % self._regexp464 if self._lambda != 0.3:465 ret += ", lambda_=%r" % self._lambda466 return ret467 special_sets = {468 "[:alnum:]": "[a-zA-Z0-9]",469 "[:alpha:]": "[a-zA-Z]",470 "[:ascii:]": "[\x00-\x7F]",471 "[:blank:]": "[ \t]",472 "[:cntrl:]": "[\x00-\x1F\x7F]",473 "[:digit:]": "[0-9]",474 "[:graph:]": "[\x21-\x7E]",475 "[:lower:]": "[a-z]",476 "[:print:]": "[\x20-\x7E]",477 "[:punct:]": "[!\"\\#$%&'()*+,\\-./:;<=>?@\\[\\\\\\]^_{|}~]",478 "[:space:]": "[ \t\r\n\v\f]",479 "[:upper:]": "[A-Z]",480 "[:word:]": "[A-Za-z0-9_]",481 "[:xdigit:]": "[A-Fa-f0-9]",482 }483 @staticmethod484 def choice_expand(s):485 m = ""486 invert = s and s[0] == "^"487 while True:488 p = s.find("-")489 if p < 0:490 break491 if p == 0 or p == len(s) - 1:492 m = "-"493 if p:494 s = s[:-1]495 else:496 s = s[1:]497 else:498 c1 = s[p - 1]499 c2 = s[p + 1]500 rng = "".join(map(chr, range(ord(c1), ord(c2) + 1)))501 s = s[:p - 1] + rng + s[p + 1:]502 res = m + s503 if invert:504 res = "".join(chr(x) for x in range(256) if chr(x) not in res)505 return res506 @staticmethod507 def stack_fix(lst, index):508 r = ""509 mul = 1510 for e in lst:511 if isinstance(e, list):512 if mul != 1:513 mul = mul - 1514 r += RandRegExp.stack_fix(e[1:] * mul, index)515 # only the last iteration should be kept for back reference516 f = RandRegExp.stack_fix(e[1:], index)517 for i, idx in enumerate(index):518 if e is idx:519 index[i] = f520 r += f521 mul = 1522 elif isinstance(e, tuple):523 kind, val = e524 if kind == "cite":525 r += index[val - 1]526 elif kind == "repeat":527 mul = val528 elif kind == "choice":529 if mul == 1:530 c = random.choice(val)531 r += RandRegExp.stack_fix(c[1:], index)532 else:533 r += RandRegExp.stack_fix([e] * mul, index)534 mul = 1535 else:536 if mul != 1:537 r += RandRegExp.stack_fix([e] * mul, index)538 mul = 1539 else:540 r += str(e)541 return r542 def _fix(self):543 stack = [None]544 index = []545 current = stack546 i = 0547 regexp = self._regexp548 for k, v in self.special_sets.items():549 regexp = regexp.replace(k, v)550 ln = len(regexp)551 interp = True552 while i < ln:553 c = regexp[i]554 i += 1555 if c == '(':556 current = [current]557 current[0].append(current)558 elif c == '|':559 p = current[0]560 ch = p[-1]561 if not isinstance(ch, tuple):562 ch = ("choice", [current])563 p[-1] = ch564 else:565 ch[1].append(current)566 current = [p]567 elif c == ')':568 ch = current[0][-1]569 if isinstance(ch, tuple):570 ch[1].append(current)571 index.append(current)572 current = current[0]573 elif c == '[' or c == '{':574 current = [current]575 current[0].append(current)576 interp = False577 elif c == ']':578 current = current[0]579 choice = RandRegExp.choice_expand("".join(current.pop()[1:]))580 current.append(RandChoice(*list(choice)))581 interp = True582 elif c == '}':583 current = current[0]584 num = "".join(current.pop()[1:])585 e = current.pop()586 if "," not in num:587 n = int(num)588 current.append([current] + [e] * n)589 else:590 num_min, num_max = num.split(",")591 if not num_min:592 num_min = "0"593 if num_max:594 n = RandNum(int(num_min), int(num_max))595 else:596 n = RandNumExpo(self._lambda, base=int(num_min))597 current.append(("repeat", n))598 current.append(e)599 interp = True600 elif c == '\\':601 c = regexp[i]602 if c == "s":603 c = RandChoice(" ", "\t")604 elif c in "0123456789":605 c = ("cite", ord(c) - 0x30)606 current.append(c)607 i += 1608 elif not interp:609 current.append(c)610 elif c == '+':611 e = current.pop()612 current.append([current] + [e] * (int(random.expovariate(self._lambda)) + 1)) # noqa: E501613 elif c == '*':614 e = current.pop()615 current.append([current] + [e] * int(random.expovariate(self._lambda))) # noqa: E501616 elif c == '?':617 if random.randint(0, 1):618 current.pop()619 elif c == '.':620 current.append(RandChoice(*[chr(x) for x in range(256)]))621 elif c == '$' or c == '^':622 pass623 else:624 current.append(c)625 return RandRegExp.stack_fix(stack[1:], index)626 def __repr__(self):627 return "<%s [%r]>" % (self.__class__.__name__, self._regexp)628class RandSingularity(RandChoice):629 pass630class RandSingNum(RandSingularity):631 @staticmethod632 def make_power_of_two(end):633 sign = 1634 if end == 0:635 end = 1636 if end < 0:637 end = -end638 sign = -1639 end_n = int(math.log(end) / math.log(2)) + 1640 return {sign * 2**i for i in range(end_n)}641 def __init__(self, mn, mx):642 self._mn = mn643 self._mx = mx644 sing = {0, mn, mx, int((mn + mx) / 2)}645 sing |= self.make_power_of_two(mn)646 sing |= self.make_power_of_two(mx)647 for i in sing.copy():648 sing.add(i + 1)649 sing.add(i - 1)650 for i in sing.copy():651 if not mn <= i <= mx:652 sing.remove(i)653 super(RandSingNum, self).__init__(*sing)654 self._choice.sort()655 def _command_args(self):656 if self.__class__.__name__ == 'RandSingNum':657 return "mn=%r, mx=%r" % (self._mn, self._mx)658 return super(RandSingNum, self)._command_args()659class RandSingByte(RandSingNum):660 def __init__(self):661 RandSingNum.__init__(self, 0, 2**8 - 1)662class RandSingSByte(RandSingNum):663 def __init__(self):664 RandSingNum.__init__(self, -2**7, 2**7 - 1)665class RandSingShort(RandSingNum):666 def __init__(self):667 RandSingNum.__init__(self, 0, 2**16 - 1)668class RandSingSShort(RandSingNum):669 def __init__(self):670 RandSingNum.__init__(self, -2**15, 2**15 - 1)671class RandSingInt(RandSingNum):672 def __init__(self):673 RandSingNum.__init__(self, 0, 2**32 - 1)674class RandSingSInt(RandSingNum):675 def __init__(self):676 RandSingNum.__init__(self, -2**31, 2**31 - 1)677class RandSingLong(RandSingNum):678 def __init__(self):679 RandSingNum.__init__(self, 0, 2**64 - 1)680class RandSingSLong(RandSingNum):681 def __init__(self):682 RandSingNum.__init__(self, -2**63, 2**63 - 1)683class RandSingString(RandSingularity):684 def __init__(self):685 choices_list = ["",686 "%x",687 "%%",688 "%s",689 "%i",690 "%n",691 "%x%x%x%x%x%x%x%x%x",692 "%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s",693 "%",694 "%%%",695 "A" * 4096,696 b"\x00" * 4096,697 b"\xff" * 4096,698 b"\x7f" * 4096,699 b"\x80" * 4096,700 " " * 4096,701 "\\" * 4096,702 "(" * 4096,703 "../" * 1024,704 "/" * 1024,705 "${HOME}" * 512,706 " or 1=1 --",707 "' or 1=1 --",708 '" or 1=1 --',709 " or 1=1; #",710 "' or 1=1; #",711 '" or 1=1; #',712 ";reboot;",713 "$(reboot)",714 "`reboot`",715 "index.php%00",716 b"\x00",717 "%00",718 "\\",719 "../../../../../../../../../../../../../../../../../etc/passwd", # noqa: E501720 "%2e%2e%2f" * 20 + "etc/passwd",721 "%252e%252e%252f" * 20 + "boot.ini",722 "..%c0%af" * 20 + "etc/passwd",723 "..%c0%af" * 20 + "boot.ini",724 "//etc/passwd",725 r"..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\..\boot.ini", # noqa: E501726 "AUX:",727 "CLOCK$",728 "COM:",729 "CON:",730 "LPT:",731 "LST:",732 "NUL:",733 "CON:",734 r"C:\CON\CON",735 r"C:\boot.ini",736 r"\\myserver\share",737 "foo.exe:",738 "foo.exe\\", ]739 super(RandSingString, self).__init__(*choices_list)740 def _command_args(self):741 return ""742 def __str__(self):743 return str(self._fix())744 def __bytes__(self):745 return bytes_encode(self._fix())746class RandPool(RandField):747 def __init__(self, *args):748 """Each parameter is a volatile object or a couple (volatile object, weight)""" # noqa: E501749 self._args = args750 pool = []751 for p in args:752 w = 1753 if isinstance(p, tuple):754 p, w = p755 pool += [p] * w756 self._pool = pool757 def _command_args(self):758 ret = []759 for p in self._args:760 if isinstance(p, tuple):761 ret.append("(%s, %r)" % (p[0].command(), p[1]))762 else:763 ret.append(p.command())764 return ", ".join(ret)765 def _fix(self):766 r = random.choice(self._pool)767 return r._fix()768class RandUUID(RandField):769 """Generates a random UUID.770 By default, this generates a RFC 4122 version 4 UUID (totally random).771 See Python's ``uuid`` module documentation for more information.772 Args:773 template (optional): A template to build the UUID from. Not valid with774 any other option.775 node (optional): A 48-bit Host ID. Only valid for version 1 (where it776 is optional).777 clock_seq (optional): An integer of up to 14-bits for the sequence778 number. Only valid for version 1 (where it is779 optional).780 namespace: A namespace identifier, which is also a UUID. Required for781 versions 3 and 5, must be omitted otherwise.782 name: string, required for versions 3 and 5, must be omitted otherwise.783 version: Version of UUID to use (1, 3, 4 or 5). If omitted, attempts to784 guess which version to generate, defaulting to version 4785 (totally random).786 Raises:787 ValueError: on invalid constructor arguments788 """789 # This was originally scapy.contrib.dce_rpc.RandUUID.790 _BASE = "([0-9a-f]{{{0}}}|\\*|[0-9a-f]{{{0}}}:[0-9a-f]{{{0}}})"791 _REG = re.compile(792 r"^{0}-?{1}-?{1}-?{2}{2}-?{2}{2}{2}{2}{2}{2}$".format(793 _BASE.format(8), _BASE.format(4), _BASE.format(2)794 ),795 re.I796 )797 VERSIONS = [1, 3, 4, 5]798 def __init__(self, template=None, node=None, clock_seq=None,799 namespace=None, name=None, version=None):800 self._template = template801 self._ori_version = version802 self.uuid_template = None803 self.node = None804 self.clock_seq = None805 self.namespace = None806 self.name = None807 self.node = None808 self.version = None809 if template:810 if node or clock_seq or namespace or name or version:811 raise ValueError("UUID template must be the only parameter, "812 "if specified")813 tmp = RandUUID._REG.match(template)814 if tmp:815 template = tmp.groups()816 else:817 # Invalid template818 raise ValueError("UUID template is invalid")819 rnd_f = [RandInt] + [RandShort] * 2 + [RandByte] * 8820 uuid_template = []821 for i, t in enumerate(template):822 if t == "*":823 val = rnd_f[i]()824 elif ":" in t:825 mini, maxi = t.split(":")826 val = RandNum(int(mini, 16), int(maxi, 16))827 else:828 val = int(t, 16)829 uuid_template.append(val)830 self.uuid_template = tuple(uuid_template)831 else:832 if version:833 if version not in RandUUID.VERSIONS:834 raise ValueError("version is not supported")835 else:836 self.version = version837 else:838 # No version specified, try to guess...839 # This could be wrong, and cause an error later!840 if node or clock_seq:841 self.version = 1842 elif namespace and name:843 self.version = 5844 else:845 # Don't know, random!846 self.version = 4847 # We have a version, now do things...848 if self.version == 1:849 if namespace or name:850 raise ValueError("namespace and name may not be used with "851 "version 1")852 self.node = node853 self.clock_seq = clock_seq854 elif self.version in (3, 5):855 if node or clock_seq:856 raise ValueError("node and clock_seq may not be used with "857 "version {}".format(self.version))858 self.namespace = namespace859 self.name = name860 elif self.version == 4:861 if namespace or name or node or clock_seq:862 raise ValueError("node, clock_seq, node and clock_seq may "863 "not be used with version 4. If you "864 "did not specify version, you need to "865 "specify it explicitly.")866 def _command_args(self):867 ret = []868 if self._template:869 ret.append("template=%r" % self._template)870 if self.node:871 ret.append("node=%r" % self.node)872 if self.clock_seq:873 ret.append("clock_seq=%r" % self.clock_seq)874 if self.namespace:875 ret.append("namespace=%r" % self.namespace)876 if self.name:877 ret.append("name=%r" % self.name)878 if self._ori_version:879 ret.append("version=%r" % self._ori_version)880 return ", ".join(ret)881 def _fix(self):882 if self.uuid_template:883 return uuid.UUID(("%08x%04x%04x" + ("%02x" * 8))884 % self.uuid_template)885 elif self.version == 1:886 return uuid.uuid1(self.node, self.clock_seq)887 elif self.version == 3:888 return uuid.uuid3(self.namespace, self.name)889 elif self.version == 4:890 return uuid.uuid4()891 elif self.version == 5:892 return uuid.uuid5(self.namespace, self.name)893 else:894 raise ValueError("Unhandled version")895# Automatic timestamp896class AutoTime(_RandNumeral):897 def __init__(self, base=None, diff=None):898 self._base = base899 self._ori_diff = diff900 if diff is not None:901 self.diff = diff902 elif base is None:903 self.diff = 0904 else:905 self.diff = time.time() - base906 def _command_args(self):907 ret = []908 if self._base:909 ret.append("base=%r" % self._base)910 if self._ori_diff:911 ret.append("diff=%r" % self._ori_diff)912 return ", ".join(ret)913 def _fix(self):914 return time.time() - self.diff915class IntAutoTime(AutoTime):916 def _fix(self):917 return int(time.time() - self.diff)918class ZuluTime(AutoTime):919 def __init__(self, diff=0):920 super(ZuluTime, self).__init__(diff=diff)921 def _fix(self):922 return time.strftime("%y%m%d%H%M%SZ",923 time.gmtime(time.time() + self.diff))924class GeneralizedTime(AutoTime):925 def __init__(self, diff=0):926 super(GeneralizedTime, self).__init__(diff=diff)927 def _fix(self):928 return time.strftime("%Y%m%d%H%M%SZ",929 time.gmtime(time.time() + self.diff))930class DelayedEval(VolatileValue):931 """ Example of usage: DelayedEval("time.time()") """932 def __init__(self, expr):933 self.expr = expr934 def _command_args(self):935 return "expr=%r" % self.expr936 def _fix(self):937 return eval(self.expr)938class IncrementalValue(VolatileValue):939 def __init__(self, start=0, step=1, restart=-1):940 self.start = self.val = start941 self.step = step942 self.restart = restart943 def _command_args(self):944 ret = []945 if self.start:946 ret.append("start=%r" % self.start)947 if self.step != 1:948 ret.append("step=%r" % self.step)949 if self.restart != -1:950 ret.append("restart=%r" % self.restart)951 return ", ".join(ret)952 def _fix(self):953 v = self.val954 if self.val == self.restart:955 self.val = self.start956 else:957 self.val += self.step958 return v959class CorruptedBytes(VolatileValue):960 def __init__(self, s, p=0.01, n=None):961 self.s = s962 self.p = p963 self.n = n964 def _command_args(self):965 ret = []966 ret.append("s=%r" % self.s)967 if self.p != 0.01:968 ret.append("p=%r" % self.p)969 if self.n:970 ret.append("n=%r" % self.n)971 return ", ".join(ret)972 def _fix(self):973 return corrupt_bytes(self.s, self.p, self.n)974class CorruptedBits(CorruptedBytes):975 def _fix(self):...

Full Screen

Full Screen

role.py

Source:role.py Github

copy

Full Screen

1# Copyright (c) 2015-2018 Cisco Systems, Inc.2#3# Permission is hereby granted, free of charge, to any person obtaining a copy4# of this software and associated documentation files (the "Software"), to5# deal in the Software without restriction, including without limitation the6# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or7# sell copies of the Software, and to permit persons to whom the Software is8# furnished to do so, subject to the following conditions:9#10# The above copyright notice and this permission notice shall be included in11# all copies or substantial portions of the Software.12#13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING18# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER19# DEALINGS IN THE SOFTWARE.20import os21import click22from molecule import config23from molecule import logger24from molecule import util25from molecule.command import base as command_base26from molecule.command.init import base27LOG = logger.get_logger(__name__)28class Role(base.Base):29 """30 .. program:: molecule init role --role-name foo31 .. option:: molecule init role --role-name foo32 Initialize a new role.33 """34 def __init__(self, command_args):35 self._command_args = command_args36 def execute(self):37 """38 Execute the actions necessary to perform a `molecule init role` and39 returns None.40 :return: None41 """42 role_name = self._command_args['role_name']43 role_directory = os.getcwd()44 msg = 'Initializing new role {}...'.format(role_name)45 LOG.info(msg)46 if os.path.isdir(role_name):47 msg = ('The directory {} exists. '48 'Cannot create new role.').format(role_name)49 util.sysexit_with_message(msg)50 self._process_templates('role', self._command_args, role_directory)51 scenario_base_directory = os.path.join(role_directory, role_name)52 templates = [53 'scenario/driver/{driver_name}'.format(**self._command_args),54 'scenario/verifier/{verifier_name}'.format(**self._command_args),55 ]56 for template in templates:57 self._process_templates(template, self._command_args,58 scenario_base_directory)59 self._process_templates('molecule', self._command_args, role_directory)60 role_directory = os.path.join(role_directory, role_name)61 msg = 'Initialized role in {} successfully.'.format(role_directory)62 LOG.success(msg)63@click.command()64@click.pass_context65@click.option(66 '--dependency-name',67 type=click.Choice(['galaxy']),68 default='galaxy',69 help='Name of dependency to initialize. (galaxy)')70@click.option(71 '--driver-name',72 '-d',73 type=click.Choice(config.molecule_drivers()),74 default='docker',75 help='Name of driver to initialize. (docker)')76@click.option(77 '--lint-name',78 type=click.Choice(['yamllint']),79 default='yamllint',80 help='Name of lint to initialize. (yamllint)')81@click.option(82 '--provisioner-name',83 type=click.Choice(['ansible']),84 default='ansible',85 help='Name of provisioner to initialize. (ansible)')86@click.option(87 '--role-name', '-r', required=True, help='Name of the role to create.')88@click.option(89 '--verifier-name',90 type=click.Choice(config.molecule_verifiers()),91 default='testinfra',92 help='Name of verifier to initialize. (testinfra)')93def role(ctx, dependency_name, driver_name, lint_name, provisioner_name,94 role_name, verifier_name): # pragma: no cover95 """ Initialize a new role for use with Molecule. """96 command_args = {97 'dependency_name': dependency_name,98 'driver_name': driver_name,99 'lint_name': lint_name,100 'provisioner_name': provisioner_name,101 'role_name': role_name,102 'scenario_name': command_base.MOLECULE_DEFAULT_SCENARIO_NAME,103 'subcommand': __name__,104 'verifier_name': verifier_name,105 }106 if verifier_name == 'inspec':107 command_args['verifier_lint_name'] = 'rubocop'108 if verifier_name == 'goss':109 command_args['verifier_lint_name'] = 'yamllint'110 r = Role(command_args)...

Full Screen

Full Screen

test_molecule.py

Source:test_molecule.py Github

copy

Full Screen

...31@pytest.fixture32def _instance(_base_class):33 return _base_class()34@pytest.fixture35def _command_args():36 return {37 "dependency_name": "galaxy",38 "driver_name": "docker",39 "lint_name": "yamllint",40 "provisioner_name": "ansible",41 "scenario_name": "default",42 "role_name": "test-role",43 "verifier_name": "testinfra",44 }45@pytest.fixture46def _role_directory():47 return '.'48@pytest.fixture49def _molecule_file(_role_directory):...

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