How to use put method in mountebank

Best JavaScript code snippet using mountebank

gdbmacros.py

Source:gdbmacros.py Github

copy

Full Screen

...455 if False:456 # Take four bytes at a time, this is critical for performance.457 # In fact, even four at a time is too slow beyond 100x100 or so.458 d.putField("editformat", 1) # Magic marker for direct "QImage" data.459 d.put('%s="' % name)460 d.put("%08x" % int(d_ptr["width"]))461 d.put("%08x" % int(d_ptr["height"]))462 d.put("%08x" % int(d_ptr["format"]))463 p = bits.cast(lookupType("unsigned int").pointer())464 for i in xrange(nbytes / 4):465 d.put("%08x" % int(p.dereference()))466 p += 1467 d.put('",')468 else:469 # Write to an external file. Much faster ;-(470 file = tempfile.mkstemp(prefix="gdbpy_")471 filename = file[1].replace("\\", "\\\\")472 p = bits.cast(lookupType("unsigned char").pointer())473 gdb.execute("dump binary memory %s %s %s" %474 (filename, cleanAddress(p), cleanAddress(p + nbytes)))475 d.putDisplay(DisplayImage, " %d %d %d %s"476 % (d_ptr["width"], d_ptr["height"], d_ptr["format"], filename))477def qdump__QLinkedList(d, item):478 d_ptr = item.value["d"]479 e_ptr = item.value["e"]480 n = d_ptr["size"]481 check(0 <= n and n <= 100*1000*1000)482 checkRef(d_ptr["ref"])483 d.putItemCount(n)484 d.putNumChild(n)485 if d.isExpanded(item):486 innerType = templateArgument(item.value.type, 0)487 with Children(d, [n, 1000], innerType):488 p = e_ptr["n"]489 for i in d.childRange():490 d.putSubItem(Item(p["t"], item.iname, i))491 p = p["n"]492def qdump__QLocale(d, item):493 d.putStringValue(call(item.value, "name"))494 d.putNumChild(0)495 return496 # FIXME: Poke back for variants.497 if d.isExpanded(item):498 with Children(d, 1, lookupType(d.ns + "QChar"), 0):499 d.putCallItem("country", item, "country")500 d.putCallItem("language", item, "language")501 d.putCallItem("measurementSystem", item, "measurementSystem")502 d.putCallItem("numberOptions", item, "numberOptions")503 d.putCallItem("timeFormat_(short)", item,504 "timeFormat", d.ns + "QLocale::ShortFormat")505 d.putCallItem("timeFormat_(long)", item,506 "timeFormat", d.ns + "QLocale::LongFormat")507 d.putCallItem("decimalPoint", item, "decimalPoint")508 d.putCallItem("exponential", item, "exponential")509 d.putCallItem("percent", item, "percent")510 d.putCallItem("zeroDigit", item, "zeroDigit")511 d.putCallItem("groupSeparator", item, "groupSeparator")512 d.putCallItem("negativeSign", item, "negativeSign")513def qdump__QMapNode(d, item):514 d.putValue(" ")515 d.putNumChild(2)516 if d.isExpanded(item):517 with Children(d, 2):518 with SubItem(d):519 d.putName("key")520 d.putItem(Item(item.value["key"], item.iname, "name"))521 with SubItem(d):522 d.putName("value")523 d.putItem(Item(item.value["value"], item.iname, "value"))524def qdumpHelper__QMap(d, item, forceLong):525 d_ptr = item.value["d"].dereference()526 e_ptr = item.value["e"].dereference()527 n = d_ptr["size"]528 check(0 <= n and n <= 100*1000*1000)529 checkRef(d_ptr["ref"])530 d.putItemCount(n)531 d.putNumChild(n)532 if d.isExpanded(item):533 if n > 1000:534 n = 1000535 keyType = templateArgument(item.value.type, 0)536 valueType = templateArgument(item.value.type, 1)537 isSimpleKey = isSimpleType(keyType)538 isSimpleValue = isSimpleType(valueType)539 it = e_ptr["forward"].dereference()540 # QMapPayloadNode is QMapNode except for the 'forward' member, so541 # its size is most likely the offset of the 'forward' member therein.542 # Or possibly 2 * sizeof(void *)543 nodeType = lookupType(d.ns + "QMapNode<%s, %s>" % (keyType, valueType))544 payloadSize = nodeType.sizeof - 2 * lookupType("void").pointer().sizeof545 charPtr = lookupType("char").pointer()546 innerType = select(isSimpleKey and isSimpleValue, valueType, nodeType)547 with Children(d, n, innerType):548 for i in xrange(n):549 itd = it.dereference()550 base = it.cast(charPtr) - payloadSize551 node = base.cast(nodeType.pointer()).dereference()552 with SubItem(d):553 key = node["key"]554 value = node["value"]555 #if isSimpleType(item.value.type): # or isStringType(d, item.value.type):556 if isSimpleKey and isSimpleValue:557 #d.putType(valueType)558 if forceLong:559 d.putName("[%s] %s" % (i, key))560 else:561 d.putName(key)562 d.putItem(Item(value, item.iname, i))563 else:564 d.putItem(Item(node, item.iname, i))565 it = it.dereference()["forward"].dereference()566def qdump__QMap(d, item):567 qdumpHelper__QMap(d, item, False)568def qdump__QMultiMap(d, item):569 qdumpHelper__QMap(d, item, True)570def extractCString(table, offset):571 result = ""572 while True:573 d = table[offset]574 if d == 0:575 break576 result += "%c" % d577 offset += 1578 return result579def qdump__QObject(d, item):580 #warn("OBJECT: %s " % item.value)581 try:582 privateType = lookupType(d.ns + "QObjectPrivate")583 staticMetaObject = item.value["staticMetaObject"]584 d_ptr = item.value["d_ptr"]["d"].cast(privateType.pointer()).dereference()585 #warn("D_PTR: %s " % d_ptr)586 objectName = d_ptr["objectName"]587 except:588 d.putPlainChildren(item)589 return590 #warn("SMO: %s " % staticMetaObject)591 #warn("SMO DATA: %s " % staticMetaObject["d"]["stringdata"])592 superData = staticMetaObject["d"]["superdata"]593 #warn("SUPERDATA: %s" % superData)594 #while not isNull(superData):595 # superData = superData.dereference()["d"]["superdata"]596 # warn("SUPERDATA: %s" % superData)597 if privateType is None:598 d.putNumChild(4)599 #d.putValue(cleanAddress(item.value.address))600 if d.isExpanded(item):601 with Children(d):602 d.putFields(item)603 return604 #warn("OBJECTNAME: %s " % objectName)605 #warn("D_PTR: %s " % d_ptr)606 mo = d_ptr["metaObject"]607 if isNull(mo):608 mo = staticMetaObject609 #warn("MO: %s " % mo)610 #warn("MO.D: %s " % mo["d"])611 metaData = mo["d"]["data"]612 metaStringData = mo["d"]["stringdata"]613 #extradata = mo["d"]["extradata"] # Capitalization!614 #warn("METADATA: %s " % metaData)615 #warn("STRINGDATA: %s " % metaStringData)616 #warn("TYPE: %s " % item.value.type)617 #warn("INAME: %s " % item.iname)618 #d.putValue("")619 d.putStringValue(objectName)620 #QSignalMapper::staticMetaObject621 #checkRef(d_ptr["ref"])622 d.putNumChild(4)623 if d.isExpanded(item):624 with Children(d):625 d.putFields(item)626 # Parent and children.627 if stripClassTag(str(item.value.type)) == d.ns + "QObject":628 d.putSubItem(Item(d_ptr["parent"], item.iname, "parent", "parent"))629 d.putSubItem(Item(d_ptr["children"], item.iname, "children", "children"))630 # Properties.631 with SubItem(d):632 # Prolog633 extraData = d_ptr["extraData"] # Capitalization!634 if isNull(extraData):635 dynamicPropertyCount = 0636 else:637 extraDataType = lookupType(638 d.ns + "QObjectPrivate::ExtraData").pointer()639 extraData = extraData.cast(extraDataType)640 ed = extraData.dereference()641 names = ed["propertyNames"]642 values = ed["propertyValues"]643 #userData = ed["userData"]644 namesBegin = names["d"]["begin"]645 namesEnd = names["d"]["end"]646 namesArray = names["d"]["array"]647 dynamicPropertyCount = namesEnd - namesBegin648 #staticPropertyCount = call(mo, "propertyCount")649 staticPropertyCount = metaData[6]650 #warn("PROPERTY COUNT: %s" % staticPropertyCount)651 propertyCount = staticPropertyCount + dynamicPropertyCount652 d.putName("properties")653 d.putType(" ")654 d.putItemCount(propertyCount)655 d.putNumChild(propertyCount)656 if d.isExpandedIName(item.iname + ".properties"):657 # FIXME: Make this global. Don't leak.658 variant = "'%sQVariant'" % d.ns659 # Avoid malloc symbol clash with QVector660 gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (variant, variant))661 gdb.execute("set $d.d.is_shared = 0")662 with Children(d, [propertyCount, 500]):663 # Dynamic properties.664 if dynamicPropertyCount != 0:665 dummyType = lookupType("void").pointer().pointer()666 namesType = lookupType(d.ns + "QByteArray")667 valuesBegin = values["d"]["begin"]668 valuesEnd = values["d"]["end"]669 valuesArray = values["d"]["array"]670 valuesType = lookupType(d.ns + "QVariant")671 p = namesArray.cast(dummyType) + namesBegin672 q = valuesArray.cast(dummyType) + valuesBegin673 for i in xrange(dynamicPropertyCount):674 with SubItem(d):675 pp = p.cast(namesType.pointer()).dereference();676 d.putField("key", encodeByteArray(pp))677 d.putField("keyencoded", Hex2EncodedLatin1)678 qq = q.cast(valuesType.pointer().pointer())679 qq = qq.dereference();680 d.putField("addr", cleanAddress(qq))681 d.putField("exp", "*(%s*)%s"682 % (variant, cleanAddress(qq)))683 name = "%s.properties.%d" % (item.iname, i)684 t = qdump__QVariant(d, Item(qq, name))685 # Override the "QVariant (foo)" output686 d.putType(t, d.currentTypePriority + 1)687 p += 1688 q += 1689 # Static properties.690 propertyData = metaData[7]691 for i in xrange(staticPropertyCount):692 with SubItem(d):693 offset = propertyData + 3 * i694 propertyName = extractCString(metaStringData, metaData[offset])695 propertyType = extractCString(metaStringData, metaData[offset + 1])696 d.putName(propertyName)697 #flags = metaData[offset + 2]698 #warn("FLAGS: %s " % flags)699 #warn("PROPERTY: %s %s " % (propertyType, propertyName))700 # #exp = '((\'%sQObject\'*)%s)->property("%s")' \701 # % (d.ns, item.value.address, propertyName)702 #exp = '"((\'%sQObject\'*)%s)"' % (d.ns, item.value.address,)703 #warn("EXPRESSION: %s" % exp)704 value = call(item.value, "property",705 str(cleanAddress(metaStringData + metaData[offset])))706 value1 = value["d"]707 #warn(" CODE: %s" % value1["type"])708 # Type 1 and 2 are bool and int. Try to save a few cycles in this case:709 if int(value1["type"]) > 2:710 # Poke back value711 gdb.execute("set $d.d.data.ull = %s" % value1["data"]["ull"])712 gdb.execute("set $d.d.type = %s" % value1["type"])713 gdb.execute("set $d.d.is_null = %s" % value1["is_null"])714 value = parseAndEvaluate("$d").dereference()715 val, inner, innert = qdumpHelper__QVariant(d, value)716 if len(inner):717 # Build-in types.718 d.putType(inner)719 name = "%s.properties.%d" % (item.iname, i + dynamicPropertyCount)720 d.putItem(Item(val, item.iname + ".properties",721 propertyName, propertyName))722 else:723 # User types.724 # func = "typeToName(('%sQVariant::Type')%d)" % (d.ns, variantType)725 # type = str(call(item.value, func))726 # type = type[type.find('"') + 1 : type.rfind('"')]727 # type = type.replace("Q", d.ns + "Q") # HACK!728 # data = call(item.value, "constData")729 # tdata = data.cast(lookupType(type).pointer()).dereference()730 # d.putValue("(%s)" % tdata.type)731 # d.putType(tdata.type)732 # d.putNumChild(1)733 # if d.isExpanded(item):734 # with Children(d):735 # d.putSubItem(Item(tdata, item.iname, "data", "data"))736 warn("FIXME: CUSTOM QOBJECT PROPERTIES NOT IMPLEMENTED: %s %s"737 % (propertyType, innert))738 d.putType(propertyType)739 d.putValue("...")740 d.putNumChild(0)741 # Connections.742 with SubItem(d):743 d.putName("connections")744 d.putType(" ")745 connections = d_ptr["connectionLists"]746 connectionListCount = 0747 if not isNull(connections):748 connectionListCount = connections["d"]["size"]749 d.putItemCount(connectionListCount, 0)750 d.putNumChild(connectionListCount)751 if d.isExpandedIName(item.iname + ".connections"):752 with Children(d):753 vectorType = connections.type.target().fields()[0].type754 innerType = templateArgument(vectorType, 0)755 # Should check: innerType == ns::QObjectPrivate::ConnectionList756 p = gdb.Value(connections["p"]["array"]).cast(innerType.pointer())757 pp = 0758 for i in xrange(connectionListCount):759 first = p.dereference()["first"]760 while not isNull(first):761 d.putSubItem(Item(first.dereference(), item.iname + ".connections", pp))762 first = first["next"]763 # We need to enforce some upper limit.764 pp += 1765 if pp > 1000:766 break767 p += 1768 # Signals769 signalCount = metaData[13]770 with SubItem(d):771 d.putName("signals")772 d.putItemCount(signalCount)773 d.putType(" ")774 d.putNumChild(signalCount)775 if signalCount:776 # FIXME: empty type does not work for childtype777 #d.putField("childtype", ".")778 d.putField("childnumchild", "0")779 if d.isExpandedIName(item.iname + ".signals"):780 with Children(d):781 for signal in xrange(signalCount):782 with SubItem(d):783 offset = metaData[14 + 5 * signal]784 d.putField("iname", "%s.signals.%d" % (item.iname, signal))785 d.putName("signal %d" % signal)786 d.putType(" ")787 d.putValue(extractCString(metaStringData, offset))788 d.putNumChild(0) # FIXME: List the connections here.789 # Slots790 with SubItem(d):791 slotCount = metaData[4] - signalCount792 d.putName("slots")793 d.putItemCount(slotCount)794 d.putType(" ")795 d.putNumChild(slotCount)796 if slotCount:797 #d.putField("childtype", ".")798 d.putField("childnumchild", "0")799 if d.isExpandedIName(item.iname + ".slots"):800 with Children(d):801 for slot in xrange(slotCount):802 with SubItem(d):803 offset = metaData[14 + 5 * (signalCount + slot)]804 d.putField("iname", "%s.slots.%d" % (item.iname, slot))805 d.putName("slot %d" % slot)806 d.putType(" ")807 d.putValue(extractCString(metaStringData, offset))808 d.putNumChild(0) # FIXME: List the connections here.809 # Active connection810 with SubItem(d):811 d.putName("currentSender")812 d.putType(" ")813 sender = d_ptr["currentSender"]814 d.putValue(cleanAddress(sender))815 if isNull(sender):816 d.putNumChild(0)817 else:818 d.putNumChild(1)819 iname = item.iname + ".currentSender"820 if d.isExpandedIName(iname):821 with Children(d):822 # Sending object823 d.putSubItem(Item(sender["sender"], iname, "object", "object"))824 # Signal in sending object825 with SubItem(d):826 d.putName("signal")827 d.putValue(sender["signal"])828 d.putType(" ");829 d.putNumChild(0)830# QObject831# static const uint qt_meta_data_QObject[] = {832# int revision;833# int className;834# int classInfoCount, classInfoData;835# int methodCount, methodData;836# int propertyCount, propertyData;837# int enumeratorCount, enumeratorData;838# int constructorCount, constructorData; //since revision 2839# int flags; //since revision 3840# int signalCount; //since revision 4841# // content:842# 4, // revision843# 0, // classname844# 0, 0, // classinfo845# 4, 14, // methods846# 1, 34, // properties847# 0, 0, // enums/sets848# 2, 37, // constructors849# 0, // flags850# 2, // signalCount851# /* 14 */852# // signals: signature, parameters, type, tag, flags853# 9, 8, 8, 8, 0x05,854# 29, 8, 8, 8, 0x25,855# /* 24 */856# // slots: signature, parameters, type, tag, flags857# 41, 8, 8, 8, 0x0a,858# 55, 8, 8, 8, 0x08,859# /* 34 */860# // properties: name, type, flags861# 90, 82, 0x0a095103,862# /* 37 */863# // constructors: signature, parameters, type, tag, flags864# 108, 101, 8, 8, 0x0e,865# 126, 8, 8, 8, 0x2e,866# 0 // eod867# };868# static const char qt_meta_stringdata_QObject[] = {869# "QObject\0\0destroyed(QObject*)\0destroyed()\0"870# "deleteLater()\0_q_reregisterTimers(void*)\0"871# "QString\0objectName\0parent\0QObject(QObject*)\0"872# "QObject()\0"873# };874# QSignalMapper875# static const uint qt_meta_data_QSignalMapper[] = {876# // content:877# 4, // revision878# 0, // classname879# 0, 0, // classinfo880# 7, 14, // methods881# 0, 0, // properties882# 0, 0, // enums/sets883# 0, 0, // constructors884# 0, // flags885# 4, // signalCount886# // signals: signature, parameters, type, tag, flags887# 15, 14, 14, 14, 0x05,888# 27, 14, 14, 14, 0x05,889# 43, 14, 14, 14, 0x05,890# 60, 14, 14, 14, 0x05,891# // slots: signature, parameters, type, tag, flags892# 77, 14, 14, 14, 0x0a,893# 90, 83, 14, 14, 0x0a,894# 104, 14, 14, 14, 0x08,895# 0 // eod896# };897# static const char qt_meta_stringdata_QSignalMapper[] = {898# "QSignalMapper\0\0mapped(int)\0mapped(QString)\0"899# "mapped(QWidget*)\0mapped(QObject*)\0"900# "map()\0sender\0map(QObject*)\0"901# "_q_senderDestroyed()\0"902# };903# const QMetaObject QSignalMapper::staticMetaObject = {904# { &QObject::staticMetaObject, qt_meta_stringdata_QSignalMapper,905# qt_meta_data_QSignalMapper, 0 }906# };907# checkAccess(deref(d.data)); // is the d-ptr de-referenceable and valid908# const QObject *ob = reinterpret_cast<const QObject *>(d.data)909# const QMetaObject *mo = ob->metaObject()910# d.putValue(ob->objectName(), 2)911# d.putField("type", d.ns + "QObject")912# d.putField("displayedtype", mo->className())913# d.putField("numchild", 4)914# if d.isExpanded(item):915# int slotCount = 0916# int signalCount = 0917# for (int i = mo->methodCount(); --i >= 0; ) {918# QMetaMethod::MethodType mt = mo->method(i).methodType()919# signalCount += (mt == QMetaMethod::Signal)920# slotCount += (mt == QMetaMethod::Slot)921# }922# with Children(d):923# with SubItem(d):924# d.putName("properties")925# // using 'addr' does not work in gdb as 'exp' is recreated as926# // (type *)addr, and here we have different 'types':927# // QObject vs QObjectPropertyList!928# d.putField("addr", d.data)929# d.putField("type", d.ns + "QObjectPropertyList")930# d.putItemCount(mo->propertyCount())931# d.putField("numchild", mo->propertyCount())932# with SubItem(d):933# d.putName("signals")934# d.putField("addr", d.data)935# d.putField("type", d.ns + "QObjectSignalList")936# d.putItemCount(signalCount)937# d.putField("numchild", signalCount)938# with SubItem(d):939# d.putName("slots")940# d.putField("addr", d.data)941# d.putField("type", d.ns + "QObjectSlotList")942# d.putItemCount(slotCount)943# d.putField("numchild", slotCount)944# const QObjectList objectChildren = ob->children()945# if !objectChildren.empty()) {946# with SubItem(d):947# d.putName("children")948# d.putField("addr", d.data)949# d.putField("type", ns + "QObjectChildList")950# d.putItemCount(objectChildren.size())951# d.putField("numchild", objectChildren.size())952# with SubItem(d):953# d.putName("parent")954# if isSimpleType(item.value.type):955# d.putItem(d, ns + "QObject *", ob->parent())956# #if 1957# with SubItem(d):958# d.putName("className")959# d.putValue(ob->metaObject()->className())960# d.putField("type", "")961# d.putField("numchild", "0")962# #endif963# static const char *sizePolicyEnumValue(QSizePolicy::Policy p)964# {965# switch (p) {966# case QSizePolicy::Fixed:967# return "Fixed"968# case QSizePolicy::Minimum:969# return "Minimum"970# case QSizePolicy::Maximum:971# return "Maximum"972# case QSizePolicy::Preferred:973# return "Preferred"974# case QSizePolicy::Expanding:975# return "Expanding"976# case QSizePolicy::MinimumExpanding:977# return "MinimumExpanding"978# case QSizePolicy::Ignored:979# break980# }981# return "Ignored"982# }983#984# static QString sizePolicyValue(const QSizePolicy &sp)985# {986# QString rc987# QTextStream str(&rc)988# // Display as in Designer989# str << '[' << sizePolicyEnumValue(sp.horizontalPolicy())990# << ", " << sizePolicyEnumValue(sp.verticalPolicy())991# << ", " << sp.horizontalStretch() << ", " << sp.verticalStretch() << ']'992# return rc993# }994# #endif995#996# // Meta enumeration helpers997# static inline void dumpMetaEnumType(QDumper &d, const QMetaEnum &me)998# {999# QByteArray type = me.scope()1000# if !type.isEmpty())1001# type += "::"1002# type += me.name()1003# d.putField("type", type.constData())1004# }1005#1006# static inline void dumpMetaEnumValue(QDumper &d, const QMetaProperty &mop,1007# int value)1008# {1009#1010# const QMetaEnum me = mop.enumerator()1011# dumpMetaEnumType(d, me)1012# if const char *enumValue = me.valueToKey(value)) {1013# d.putValue(enumValue)1014# } else {1015# d.putValue(value)1016# }1017# d.putField("numchild", 0)1018# }1019#1020# static inline void dumpMetaFlagValue(QDumper &d, const QMetaProperty &mop,1021# int value)1022# {1023# const QMetaEnum me = mop.enumerator()1024# dumpMetaEnumType(d, me)1025# const QByteArray flagsValue = me.valueToKeys(value)1026# if flagsValue.isEmpty():1027# d.putValue(value)1028# else:1029# d.putValue(flagsValue.constData())1030# d.putNumChild(0)1031# }1032#1033# #ifndef QT_BOOTSTRAPPED1034# static void dumpQObjectProperty(QDumper &d)1035# {1036# const QObject *ob = (const QObject *)d.data1037# const QMetaObject *mob = ob->metaObject()1038# // extract "local.Object.property"1039# QString iname = d.iname1040# const int dotPos = iname.lastIndexOf(QLatin1Char('.'))1041# if dotPos == -1)1042# return1043# iname.remove(0, dotPos + 1)1044# const int index = mob->indexOfProperty(iname.toAscii())1045# if index == -1)1046# return1047# const QMetaProperty mop = mob->property(index)1048# const QVariant value = mop.read(ob)1049# const bool isInteger = value.type() == QVariant::Int1050# if isInteger and mop.isEnumType()) {1051# dumpMetaEnumValue(d, mop, value.toInt())1052# } elif isInteger and mop.isFlagType()) {1053# dumpMetaFlagValue(d, mop, value.toInt())1054# } else {1055# dumpQVariant(d, &value)1056# }1057# d.disarm()1058# }1059#1060# static void dumpQObjectMethodList(QDumper &d)1061# {1062# const QObject *ob = (const QObject *)d.data1063# const QMetaObject *mo = ob->metaObject()1064# d.putField("addr", "<synthetic>")1065# d.putField("type", ns + "QObjectMethodList")1066# d.putField("numchild", mo->methodCount())1067# if d.isExpanded(item):1068# d.putField("childtype", ns + "QMetaMethod::Method")1069# d.putField("childnumchild", "0")1070# with Children(d):1071# for (int i = 0; i != mo->methodCount(); ++i) {1072# const QMetaMethod & method = mo->method(i)1073# int mt = method.methodType()1074# with SubItem(d):1075# d.beginItem("name")1076# d.put(i).put(" ").put(mo->indexOfMethod(method.signature()))1077# d.put(" ").put(method.signature())1078# d.endItem()1079# d.beginItem("value")1080# d.put((mt == QMetaMethod::Signal ? "<Signal>" : "<Slot>"))1081# d.put(" (").put(mt).put(")")1082# d.endItem()1083#1084# def qConnectionType(type):1085# Qt::ConnectionType connType = static_cast<Qt::ConnectionType>(type)1086# const char *output = "unknown"1087# switch (connType) {1088# case Qt::AutoConnection: output = "auto"; break1089# case Qt::DirectConnection: output = "direct"; break1090# case Qt::QueuedConnection: output = "queued"; break1091# case Qt::BlockingQueuedConnection: output = "blockingqueued"; break1092# case 3: output = "autocompat"; break1093# #if QT_VERSION >= 0x0406001094# case Qt::UniqueConnection: break; // Can't happen.1095# #endif1096# return output1097#1098# #if QT_VERSION >= 0x0404001099# static const ConnectionList &qConnectionList(const QObject *ob, int signalNumber)1100# {1101# static const ConnectionList emptyList1102# const ObjectPrivate *p = reinterpret_cast<const ObjectPrivate *>(dfunc(ob))1103# if !p->connectionLists)1104# return emptyList1105# typedef QVector<ConnectionList> ConnLists1106# const ConnLists *lists = reinterpret_cast<const ConnLists *>(p->connectionLists)1107# // there's an optimization making the lists only large enough to hold the1108# // last non-empty item1109# if signalNumber >= lists->size())1110# return emptyList1111# return lists->at(signalNumber)1112# }1113# #endif1114#1115# // Write party involved in a slot/signal element,1116# // avoid to recursion to self.1117# static inline void dumpQObjectConnectionPart(QDumper &d,1118# const QObject *owner,1119# const QObject *partner,1120# int number, const char *namePostfix)1121# {1122# with SubItem(d):1123# d.beginItem("name")1124# d.put(number).put(namePostfix)1125# d.endItem()1126# if partner == owner) {1127# d.putValue("<this>")1128# d.putField("type", owner->metaObject()->className())1129# d.putField("numchild", 0)1130# d.putField("addr", owner)1131# } else {1132# if isSimpleType(item.value.type):1133# d.putItem(ns + "QObject *", partner)1134#1135# static void dumpQObjectSignal(QDumper &d)1136# {1137# unsigned signalNumber = d.extraInt[0]1138#1139# d.putField("addr", "<synthetic>")1140# d.putField("numchild", "1")1141# d.putField("type", ns + "QObjectSignal")1142#1143# #if QT_VERSION >= 0x0404001144# if d.isExpanded(item):1145# const QObject *ob = reinterpret_cast<const QObject *>(d.data)1146# with Children(d):1147# const ConnectionList &connList = qConnectionList(ob, signalNumber)1148# for (int i = 0; i != connList.size(); ++i) {1149# const Connection &conn = connectionAt(connList, i)1150# dumpQObjectConnectionPart(d, ob, conn.receiver, i, " receiver")1151# with SubItem(d):1152# d.beginItem("name")1153# d.put(i).put(" slot")1154# d.endItem()1155# d.putField("type", "")1156# if conn.receiver)1157# d.putValue(conn.receiver->metaObject()->method(conn.method).signature())1158# else1159# d.putValue("<invalid receiver>")1160# d.putField("numchild", "0")1161# with SubItem(d):1162# d.beginItem("name")1163# d.put(i).put(" type")1164# d.endItem()1165# d.putField("type", "")1166# d.beginItem("value")1167# d.put("<").put(qConnectionType(conn.connectionType)).put(" connection>")1168# d.endItem()1169# d.putField("numchild", "0")1170# d.putField("numchild", connList.size())1171# #endif1172#1173# static void dumpQObjectSignalList(QDumper &d)1174# {1175# const QObject *ob = reinterpret_cast<const QObject *>(d.data)1176# const QMetaObject *mo = ob->metaObject()1177# int count = 01178# const int methodCount = mo->methodCount()1179# for (int i = methodCount; --i >= 0; )1180# count += (mo->method(i).methodType() == QMetaMethod::Signal)1181# d.putField("type", ns + "QObjectSignalList")1182# d.putItemCount(count)1183# d.putField("addr", d.data)1184# d.putField("numchild", count)1185# #if QT_VERSION >= 0x0404001186# if d.isExpanded(item):1187# with Children(d):1188# for (int i = 0; i != methodCount; ++i) {1189# const QMetaMethod & method = mo->method(i)1190# if method.methodType() == QMetaMethod::Signal) {1191# int k = mo->indexOfSignal(method.signature())1192# const ConnectionList &connList = qConnectionList(ob, k)1193# with SubItem(d):1194# d.putName(k)1195# d.putValue(method.signature())1196# d.putField("numchild", connList.size())1197# d.putField("addr", d.data)1198# d.putField("type", ns + "QObjectSignal")1199# #endif1200#1201# static void dumpQObjectSlot(QDumper &d)1202# {1203# int slotNumber = d.extraInt[0]1204#1205# d.putField("addr", d.data)1206# d.putField("numchild", "1")1207# d.putField("type", ns + "QObjectSlot")1208#1209# #if QT_VERSION >= 0x0404001210# if d.isExpanded(item):1211# with Children(d):1212# int numchild = 01213# const QObject *ob = reinterpret_cast<const QObject *>(d.data)1214# const ObjectPrivate *p = reinterpret_cast<const ObjectPrivate *>(dfunc(ob))1215# #####if QT_VERSION >= 0x0406001216# int s = 01217# for (SenderList senderList = p->senders; senderList != 01218# senderList = senderList->next, ++s) {1219# const QObject *sender = senderList->sender1220# int signal = senderList->method; // FIXME: 'method' is wrong.1221# #####else1222# for (int s = 0; s != p->senders.size(); ++s) {1223# const QObject *sender = senderAt(p->senders, s)1224# int signal = signalAt(p->senders, s)1225# #####endif1226# const ConnectionList &connList = qConnectionList(sender, signal)1227# for (int i = 0; i != connList.size(); ++i) {1228# const Connection &conn = connectionAt(connList, i)1229# if conn.receiver == ob and conn.method == slotNumber) {1230# ++numchild1231# const QMetaMethod &method = sender->metaObject()->method(signal)1232# dumpQObjectConnectionPart(d, ob, sender, s, " sender")1233# with SubItem(d):1234# d.beginItem("name")1235# d.put(s).put(" signal")1236# d.endItem()1237# d.putField("type", "")1238# d.putValue(method.signature())1239# d.putField("numchild", "0")1240# with SubItem(d):1241# d.beginItem("name")1242# d.put(s).put(" type")1243# d.endItem()1244# d.putField("type", "")1245# d.beginItem("value")1246# d.put("<").put(qConnectionType(conn.method))1247# d.put(" connection>")1248# d.endItem()1249# d.putField("numchild", "0")1250# }1251# }1252# }1253# d.putField("numchild", numchild)1254# }1255# #endif1256# d.disarm()1257# }1258#1259# static void dumpQObjectSlotList(QDumper &d)1260# {1261# const QObject *ob = reinterpret_cast<const QObject *>(d.data)...

Full Screen

Full Screen

test_attvars.py

Source:test_attvars.py Github

copy

Full Screen

1import py2from prolog.interpreter.test.tool import prolog_raises, \3assert_true, assert_false4from prolog.interpreter.parsing import get_engine5from prolog.interpreter.continuation import Engine6from prolog.interpreter.term import AttMap, Callable, AttVar7def test_not_attvar():8 assert_false("attvar(1).")9 assert_false("attvar(X).")10 assert_false("attvar(a).")11 assert_false("attvar((a --> b)).")12def test_put_attr_and_get_attr():13 assert_true("put_attr(X, m, 1).")14 assert_true("put_attr(X, m, abc).")15 assert_true("put_attr(X, m, Y).")16 prolog_raises("type_error(A, B)", "put_attr(X, 1, 1)")17 assert_true("put_attr(X, m1, 1), put_attr(X, m2, 1), put_attr(X, m1, 2), get_attr(X, m1, 2), get_attr(X, m2, 1).")18 assert_true("put_attr(X, b, 1), (put_attr(X, b, 1), fail; get_attr(X, b, 1)).")19 assert_true("put_attr(X, a, 1), Y = X, attvar(Y), attvar(X).")20 assert_true("put_attr(X, a, 1), X = Y, attvar(Y), attvar(X).")21 e = get_engine("g(X) :- !, put_attr(X, m, 1), fail.")22 assert_true("\+ g(X), \+ attvar(X).", e)23 prolog_raises("representation_error(_, _)", "put_attr(a, a, a)")24def test_attvar_and_put_attr():25 assert_true("put_attr(X, m, 1), attvar(X).")26 assert_false("attvar(X), put_attr(X, m, 1).")27def test_get_attr():28 assert_true("put_attr(X, m, 1), get_attr(X, m, 1).")29 assert_false("get_attr(X, m, 1).")30 prolog_raises("type_error(A, B)", "get_attr(X, 2, 2)")31 prolog_raises("instantiation_error", "get_attr(X, Y, 2)")32 assert_true("put_attr(X, m, 1), put_attr(X, m, 2), get_attr(X, m, 2).")33def test_backtracking():34 assert_false("(put_attr(X, m, 1), fail); attvar(X).")35 assert_false("put_attr(X, m, 2), (put_attr(X, m, 1), fail); get_attr(X, m, 2).")36 assert_true("(put_attr(X, b, 1), fail); \+ get_attr(X, b, 1).")37 assert_true("put_attr(X, a, 2), ((put_attr(X, b, 1), fail); get_attr(X, a, 2)), \+ get_attr(X, b, 1).")38 assert_true("put_attr(X, a, 2), ((put_attr(X, a, 1), put_attr(X, a, 3), fail); get_attr(X, a, 2)).")39 assert_true("put_attr(X, a, 2), ((put_attr(X, b, 1), put_attr(X, c, 3), fail); get_attr(X, a, 2)), \+ get_attr(X, b, 1), \+ get_attr(X, c, 3).")40def test_del_attributes():41 assert_true("del_attr(X, m).")42 assert_true("del_attr(a, m).")43 prolog_raises("instantiation_error", "del_attr(X, Y)")44 prolog_raises("type_error(A, B)", "del_attr(X, 1)")45 assert_false("put_attr(X, m, 1), del_attr(X, m), attvar(X).")46 assert_true("""put_attr(X, m, 1), put_attr(X, m2, 2), 47 del_attr(X, m), attvar(X).""")48 assert_true("put_attr(X, m, 1), (del_attr(X, m), fail; true), get_attr(X, m, 1).")49 assert_true("put_attr(X, m, 1), (del_attr(X, m), fail; attvar(X)).")50def test_attr_unify_hook():51 e = get_engine("",52 m = """53 :- module(m, []).54 55 attr_unify_hook(Attr, Value) :-56 10 is Attr + Value.57 """)58 assert_false("put_attr(X, m, 1), X = 10.", e)59 assert_false("put_attr(X, m, 0), X = 11.", e)60 assert_true("put_attr(X, m, 1), X = 9.", e)61 assert_true("put_attr(X, m, 2), X = 8.", e)62 63 assert_true("X = 11, put_attr(Y, m, -1), Y = X.", e)64 assert_false("X = 11, put_attr(Y, m, 0), Y = X.", e)65 assert_false("put_attr(X, m, 11), (X = -1, fail; X = 0).", e)66 assert_true("put_attr(X, m, 11), (X = -1, fail; X = -1).", e)67def test_attr_unify_hook_complex_term():68 e = get_engine("",69 m = """70 :- module(m, []).71 attr_unify_hook(Attr, Value) :-72 assert(user:f(Value)).73 """)74 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), g(X, Y) = g(a, b).", e)75 assert_true("findall(X, f(X), [a, b]).", e)76 assert_true("abolish(f/1).", e)77 assert_true("""78 put_attr(X, m, 1), put_attr(Y, m, 2), put_attr(Z, m, 3), 79 f(Z, g(a, X, X, h(Z), Y)) = f(q, g(a, j, j, U, x)), U = h(q).80 """, e)81 assert_true("findall(X, f(X), [q, j, x]).", e)82def test_hook_not_defined():83 e = get_engine("",84 m = """85 :- module(m2, []).86 """)87 prolog_raises("existence_error(A, B)", "put_attr(X, bla, blub), X = 1")88 prolog_raises("existence_error(A, B)", "put_attr(X, m, blub), X = 1", e)89def test_multiple_hooks_one_not_defined():90 e = get_engine("", 91 m = """92 :- module(m, []).93 attr_unify_hook(_, _).94 """)95 prolog_raises("existence_error(_, _)", "put_attr(X, m, 1), put_attr(X, n, 2), X = a", e)96 prolog_raises("existence_error(_, _)", "put_attr(X, m, 1), put_attr(Y, n, 2), X = a, Y = X", e)97 prolog_raises("existence_error(_, _)", "put_attr(X, m, 1), put_attr(Y, n, 2), X = a, X = Y", e)98def test_attr_unify_hook_choice():99 e = get_engine("",100 m = """101 :- module(m, []).102 103 attr_unify_hook(Attr, f(Value)) :-104 Value = a; Value = b.105 """)106 assert_false("put_attr(X, m, 1), X = c.", e)107 assert_false("put_attr(X, m, 1), X = f(c).", e)108 assert_true("put_attr(X, m, 1), X = f(Y), Y = a.", e)109 assert_true("put_attr(X, m, 1), X = f(Y), Y = b.", e)110def test_run_hook_once():111 e = get_engine("",112 m = """113 :- module(m, []).114 attr_unify_hook(Attr, Value) :-115 assert(user:f(Value)).116 """)117 assert_true("put_attr(X, m, 1), X = a, X = a.", e)118 assert_true("findall(Y, f(Y), [a]).", e)119 assert_true("abolish(f/1).", e) # clear the database120 assert_true("""121 put_attr(X, m, 1), put_attr(Y, m, 2),122 X = a, (X = a, fail; Y = b),123 findall(A, f(A), [a, b]).124 """, e)125 assert_true("abolish(f/1).", e)126 assert_true("""127 put_attr(X, m, 1), put_attr(Y, m, 2),128 (f(X, b) = f(a, a); Y = b),129 findall(A, f(A), [b]).130 """, e)131 assert_true("abolish(f/1).", e)132 assert_true("""133 put_attr(X, m, 1), (X = a, fail; true),134 findall(Z, f(Z), [a]).135 """, e)136def test_symmetric():137 e = get_engine("",138 m = """139 :- module(m, []).140 attr_unify_hook(A, V) :-141 assert(user:f(A)).142 """)143 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), X = Y.", e)144 assert_true("f(1).", e)145 assert_true("abolish(f/1).", e)146 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), Y = X.", e)147 assert_true("f(2).", e)148def test_attvar_unification():149 e = get_engine("",150 m = """151 :- module(m, []).152 attr_unify_hook(Attr, Value) :-153 assert(user:f(Value)).154 """)155 assert_true("""156 put_attr(X, m, 1), put_attr(Y, m, 2),157 X = Y, X = a,158 findall(Z, f(Z), [W, a]).159 """, e)160 assert_true("abolish(f/1).", e)161 assert_true("""162 put_attr(X, m, 1), put_attr(Y, m, 2),163 X = Y, X = a, X = a, Y = a,164 findall(Z, f(Z), [W, a]).165 """, e)166def test_term_variables():167 assert_true("put_attr(X, m, 1), term_variables(X, [H]), attvar(H).")168def test_term_attvars():169 e = get_engine("",170 m = """171 :- module(m, []).172 attr_unify_hook(_, _).173 """)174 assert_true("term_attvars(a, []).")175 assert_true("term_attvars([], []).")176 assert_false("term_attvars([], 1).")177 assert_true("put_attr(X, m, 1), term_attvars(X, [X]).")178 assert_true("term_attvars(X,Y), Y == [].")179 assert_true("put_attr(X, m, 1), term_attvars(f(g(h(X)), X), [X]).")180 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), term_attvars(f(X, Y), [X, Y]).")181 assert_false("put_attr(X, m, 1), put_attr(Y, m, 2), X = Y, term_attvars(f(X, Y), [X, Y]).", e)182 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), X = Y, term_attvars(f(X, Y), [X]).", e)183 assert_true("put_attr(X, m, 1), put_attr(Y, m, 2), X = Y, term_attvars(f(X, Y), [Y]).", e)184 assert_true("put_attr(X, m, 1), term_attvars(f(A, X, B, X), [X]).")185 assert_true("put_attr(X, m, 1), Y = X, term_attvars(f(X, Y), [Y]).")186 assert_true("put_attr(X, m, 1), Y = X, term_attvars(f(X, Y), [X]).")187 assert_true("term_attvars(X, []), put_attr(X, m, 1).")188 assert_true("put_attr(X, m , 1), term_attvars(X, [X]), del_attr(X, m), term_attvars(X, []).")189 assert_true("put_attr(X, m, Y), term_variables(X, L), L == [X].")190def test_term_attvars_fail_fast():191 py.test.skip("")192 e = get_engine("""193 f(1, [X]) :-194 put_attr(X, m, 1).195 f(N, [X|R]) :-196 N >= 1,197 put_attr(X, m, 1),198 N1 is N - 1,199 f(N1, R).200 """)201 assert_false("f(10000, L), term_attvars(L, []).", e)202def test_copy_term_2():203 assert_true("put_attr(X, m, 1), copy_term(X, Y), attvar(Y).")204 assert_true("put_attr(X, m, 1), copy_term(X, Y), get_attr(Y, m, 1).")205 assert_false("put_attr(X, m, A), copy_term(X, Y), get_attr(Y, m, B), A == B.")206def test_copy_term_3():207 assert_true("copy_term(a, a, []).")208 assert_true("copy_term(X, Y, []), X \== Y.")209 assert_false("put_attr(X, foor, bar), copy_term(X, Y, _), X == Y.")210 assert_false("put_attr(X, foo, bar), copy_term(X, Y, Z), attvar(Y).")211 assert_true("put_attr(X, foo, bar), copy_term(X, Y, Z), \+ attvar(Y).")212 assert_true("put_attr(X, foo, bar), copy_term(X, Y, Z), Z == [put_attr(Y, foo, bar)], X \== Y.")213 assert_true("put_attr(X, foo, bar), put_attr(X, blar, blupp), copy_term(X, Y, Z), Z == [put_attr(Y, foo, bar), put_attr(Y, blar, blupp)], X \== Y.")214 215 e = get_engine("",216 m = """217 :- module(m, []).218 attr_unify_hook(_, _).219 """)220 assert_true("put_attr(X, m, 1), X = a, copy_term(X, a, Z), Z == [].", e)221 assert_true("put_attr(X, a, 1), put_attr(Y, b, 2), copy_term(f(X,Y), f(A, B), [put_attr(A, a, 1), put_attr(B, b, 2)]), Z \== f(X, Y).")222 assert_true("put_attr(X, a, Y), copy_term(X, A, [put_attr(A, a, Y)]).")223 assert_true("(put_attr(X, m, 1), fail; true), copy_term(X, A, []).")224 assert_true("copy_term(X, A, []), put_attr(X, m, 1), copy_term(X, A, [put_attr(A, m, 1)]).")225def xtest_get_attrs():226 assert_false("get_attrs(X, Y).")227 assert_false("get_attrs(a, Y).")228 assert_false("get_attrs(1, Y).")229 assert_true("put_attr(X, m, 1), get_attrs(X, att(m, 1, [])).")230 assert_false("put_attr(X, m, 1), get_attrs(f(X), att(m, 1, [])).")231 assert_true("put_attr(X, m, 1), put_attr(X, a, 2), get_attrs(X, att(m, 1, att(a, 2, []))).")232 assert_false("(put_attr(X, m, 1), fail; true), get_attrs(X, L).")233 assert_true("put_attr(X, m, 1), put_attr(Y, m, X), get_attrs(Y, att(m, X, [])), get_attrs(X, att(m, 1, [])).")234def test_del_attrs():235 assert_true("del_attrs(1).")236 assert_true("del_attrs(a).")237 assert_true("\+ attvar(X), del_attrs(X).")238 assert_false("put_attr(X, m, 1), del_attrs(X), get_attr(X, m, 1).")239 assert_true("put_attr(X, m, 1), del_attrs(X), \+ attvar(X).")240 assert_true("put_attr(X, m, 1), del_attrs(X), del_attrs(X).")241 assert_true("put_attr(X, m, 1), (del_attrs(X), fail; true), get_attr(X, m, 1).")242 assert_true("put_attr(X, m, 1), put_attr(X, m, 2), del_attrs(X), \+ attvar(X).")243def test_put_attrs():244 e = Engine(load_system=True)245 assert_false("put_attrs(X, []), attvar(X).", e)246 prolog_raises("representation_error(A, B)", "put_attrs(a, [])", e)247 prolog_raises("representation_error(A, B)", "put_attrs(a, att(m, 1, []))", e)248 assert_true("put_attrs(X, att(m, 1, [])), get_attr(X, m, 1).", e)249 assert_true("put_attrs(X, att(m, 1, att(n, W, []))), get_attr(X, m, 1), get_attr(X, n, W).", e)250 assert_false("put_attrs(X, att(m, 1, [])), fail; attvar(X).", e)251 assert_true("put_attr(X, m, 1), (put_attrs(X, att(m, 2, [])), fail; true), get_attr(X, m, 1).", e)252 assert_true("put_attr(X, m, 1), put_attrs(X, att(m, 2, [])), get_attr(X, m, 2).", e)253def test_more_than_one_attr_unify_hook():254 e = get_engine("",255 m = """256 :- module(m, []).257 attr_unify_hook(Attribute, f(X)) :-258 X = 1.259 attr_unify_hook(Attribute, f(X)) :-260 X = 2.261 """)262 assert_true("put_attr(X, m, a), X = f(1).", e)263 assert_true("put_attr(X, m, a), X = f(2).", e)264 assert_true("put_attr(X, m, a), X = f(Y), Y = 1.", e)265 assert_true("put_attr(X, m, a), X = f(Y), Y = 2.", e)266 assert_true("put_attr(X, m, a), X = f(Y), ((Y = 1, fail); Y = 2).", e)267"""268* tests regarding map support269"""270def test_basic_maps():271 m = AttMap()272 assert m.indexes == {}273 assert m.other_maps == {}274 assert m.get_index("not available") == -1275 map1 = m.with_extra_attribute("x")276 assert m.indexes == {}277 assert m.other_maps == {"x": map1}278 assert map1.indexes == {"x": 0}279 map2 = m.with_extra_attribute("x")280 assert m.indexes == {}281 assert map2.indexes == {"x": 0}282 assert map2 is map1 283 assert m.other_maps == {"x": map1}284 map3 = m.with_extra_attribute("y")285 assert m.indexes == {}286 assert m.other_maps == {"x": map1, "y": map3}287 assert m.other_maps["x"].indexes == {"x": 0}288 assert m.other_maps["y"].indexes == {"y": 0}289 map4 = map3.with_extra_attribute("z")290 assert map3.indexes == {"y": 0}291 assert map3.other_maps == {"z": map4}292 assert map4.indexes == {"z": 1, "y": 0}293 assert map4.other_maps == {}294def test_attvars_with_maps():295 a = AttVar()296 assert a.attmap is AttVar.attmap297 assert a.attmap.indexes == {}298 assert a.value_list == []299 val1 = Callable.build("1")300 a.add_attribute("x", val1)301 assert a.attmap is not AttVar.attmap302 assert a.attmap.indexes == {"x": 0}303 assert a.value_list == [val1]304 m1 = a.attmap305 a.del_attribute("x")306 assert m1 is a.attmap307 assert a.value_list == [None]308 a.add_attribute("x", val1)309 assert a.attmap is m1310 assert a.value_list == [val1]311 val2 = Callable.build("2")312 a.add_attribute("y", val2)313 m2 = a.attmap314 assert m2.indexes == {"x": 0, "y": 1}315 assert a.value_list == [val1, val2]316 a.del_attribute("x")317 assert a.attmap is m2318 assert a.value_list == [None, val2]319 a.del_attribute("y")320 assert a.attmap is m2321 assert a.value_list == [None, None]322 val3 = Callable.build("3")323 a.add_attribute("z", val3)324 m3 = a.attmap325 assert m3.indexes == {"x": 0, "y": 1, "z": 2}326 assert a.value_list == [None, None, val3]327 a.add_attribute("x", val1)328 assert a.attmap is m3329 assert a.value_list == [val1, None, val3]330def test_attvars_get():331 a = AttVar()332 t1 = a.get_attribute("x")333 assert t1[0] is None334 assert t1[1] == -1335 val1 = Callable.build("1")336 a.add_attribute("x", val1)337 t2 = a.get_attribute("x")338 assert t2[0] is val1339 assert t2[1] == 0340def test_several_attvars_same_map():341 a = AttVar()342 b = AttVar()343 assert a.attmap is b.attmap344 val1 = Callable.build("1")345 val2 = Callable.build("2")346 a.add_attribute("x", val1)347 assert a.attmap is not b.attmap348 b.add_attribute("x", val2)349 assert a.attmap is b.attmap350 a.add_attribute("y", val1)351 a.add_attribute("z", val2)352 assert a.attmap is not b.attmap353"""354* end tests regarding map support355"""356def test_integration_efficient_bools():357 e = get_engine("",358 swi_bool_pred = """359 :- module(swi_bool_pred, [negate/2]).360 negate(X, Y) :-361 ( nonvar(X) -> negate3(X, Y)362 ; nonvar(Y) -> negate3(Y, X)363 ; get_attr(X, swi_bool_pred, OtherX) -> Y = OtherX, X \== Y, put_attr(Y, swi_bool_pred, X)364 ; get_attr(Y, swi_bool_pred, OtherY) -> X = OtherY, X \== Y, put_attr(X, swi_bool_pred, Y)365 ; X \== Y, put_attr(Y, swi_bool_pred, X), put_attr(X, swi_bool_pred, Y)366 ).367 negate3(pred_true, pred_false).368 negate3(pred_false, pred_true).369 attr_unify_hook(Other, Value) :-370 (var(Value) -> (get_attr(Value, swi_bool_pred, Other2)371 -> Other = Other2, Value \== Other372 ; put_attr(Value, swi_bool_pred, Other)373 )374 ; negate3(Value, Other)).375 """)376 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(Y,Z), X==Z, Z=pred_true, X==pred_true, Y==pred_false.", e)377 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(Y,Z), X==Z, Z=pred_true, X==pred_true, Y==pred_false.", e)378 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(X2,Y2), X=X2, Y==Y2, Y=pred_false, X2==pred_true.", e)379 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(X,Z), Y==Z, Z=pred_true, X==pred_false.", e)380 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(Y,Z), \+ swi_bool_pred:negate(Z,X).", e)381 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(Y,Z), swi_bool_pred:negate(Z,X2), \+ X2=X.", e)382 assert_true("swi_bool_pred:negate(X,Y), swi_bool_pred:negate(Y,Z), X2=X, \+ swi_bool_pred:negate(Z,X2).", e)...

Full Screen

Full Screen

remote_api_put_stub_test.py

Source:remote_api_put_stub_test.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright 2007 Google Inc.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17"""Unit test for the App Engine RPC-over-HTTP 'put only' stub."""18import pickle19import google20import mox21from google.testing.pybase import googletest22from google.appengine.api import api_base_pb23from google.appengine.api import apiproxy_stub24from google.appengine.api import urlfetch25from google.appengine.datastore import datastore_pb26from google.appengine.ext import db27from google.appengine.ext.datastore_admin import remote_api_put_stub28from google.appengine.ext.remote_api import remote_api_pb29class MyModel(db.Model):30 prop = db.StringProperty()31class MockUrlfetchResult(object):32 """A mock Urlfetch result object."""33 def __init__(self, status_code, content):34 self.status_code = status_code35 self.content = content36class PutStubTest(googletest.TestCase):37 """Tests the App Engine RPC-over-HTTP interface."""38 def setUp(self):39 self.mox = mox.Mox()40 self.mock_stub = self.mox.CreateMock(apiproxy_stub.APIProxyStub)41 self.mox.StubOutWithMock(remote_api_put_stub.urlfetch, 'fetch')42 self.remote_url = 'http://remoteapp.appspot.com/remote_api'43 self.stub = remote_api_put_stub.DatastorePutStub(44 self.remote_url, 'remoteapp', {'auth': 'good'}, self.mock_stub)45 def tearDown(self):46 try:47 self.mox.VerifyAll()48 finally:49 self.mox.UnsetStubs()50 def CreatePutRequest(self, appid):51 """Create a commonly used datastore Put request."""52 model_instance = MyModel(prop='cat', _app=appid)53 put_request = datastore_pb.PutRequest()54 put_request.add_entity().CopyFrom(db.model_to_protobuf(model_instance))55 return put_request56 def CreateAllocateIdsRequest(self, appid):57 """Create a commonly used datastore AllocateIds request."""58 key = db.Key.from_path('TestEntity', 1, _app=appid)59 request = datastore_pb.AllocateIdsRequest()60 request.mutable_model_key().CopyFrom(key._ToPb())61 return request62 def RemoteApiRequest(self, call, request):63 """Return a filled in remote_api request proto."""64 remote_request_pb = remote_api_pb.Request()65 remote_request_pb.set_service_name('datastore_v3')66 remote_request_pb.set_method(call)67 remote_request_pb.mutable_request().set_contents(request.Encode())68 return remote_request_pb69 def RemoteApiResponse(self, response):70 """Return a filled in remote_api response proto."""71 remote_response = remote_api_pb.Response()72 remote_response.mutable_response().set_contents(response.Encode())73 return remote_response74 def testNonsenseRequest(self):75 """Test that a request for a service other than the datastore fails."""76 request = api_base_pb.Integer32Proto()77 request.set_value(20)78 response = api_base_pb.Integer32Proto()79 self.assertRaises(AssertionError, self.stub.MakeSyncCall,80 'testservice', 'timestwo', request, response)81 def testLocalGetRequest(self):82 """A request for Get should always pass through."""83 local_key = db.Key.from_path('MyModel', 'Name1', _app='localapp')84 get_request = datastore_pb.GetRequest()85 get_request.add_key().CopyFrom(local_key._ToPb())86 get_response = datastore_pb.GetResponse()87 self.mock_stub.MakeSyncCall('datastore_v3', 'Get', get_request,88 get_response)89 self.mox.ReplayAll()90 self.stub.MakeSyncCall('datastore_v3', 'Get', get_request, get_response)91 def testRemoteGetRequest(self):92 """A request for Get should always pass through."""93 remote_key = db.Key.from_path('MyModel', 'Name1', _app='remoteapp')94 get_request = datastore_pb.GetRequest()95 get_request.add_key().CopyFrom(remote_key._ToPb())96 get_response = datastore_pb.GetResponse()97 self.mock_stub.MakeSyncCall('datastore_v3', 'Get', get_request,98 get_response)99 self.mox.ReplayAll()100 self.stub.MakeSyncCall('datastore_v3', 'Get', get_request, get_response)101 def testLocalPutRequest(self):102 """A request for Put should go local or remote depending on the key."""103 put_request = self.CreatePutRequest('localapp')104 put_response = datastore_pb.PutResponse()105 self.mock_stub.MakeSyncCall('datastore_v3', 'Put', put_request,106 put_response)107 self.mox.ReplayAll()108 self.stub.MakeSyncCall('datastore_v3', 'Put', put_request, put_response)109 def testRemotePutRequest(self):110 """A request for Put should go local or remote depending on the key."""111 put_request = self.CreatePutRequest('remoteapp')112 put_response = datastore_pb.PutResponse()113 key = db.Key.from_path('MyModel', 1, _app='remoteapp')114 expected_put_response = datastore_pb.PutResponse()115 expected_put_response.add_key().CopyFrom(key._ToPb())116 expected_post = self.RemoteApiRequest('Put', put_request).Encode()117 expected_response = self.RemoteApiResponse(118 expected_put_response).Encode()119 remote_api_put_stub.urlfetch.fetch(120 self.remote_url, expected_post, urlfetch.POST,121 {'X-appcfg-api-version': '1', 'auth': 'good'}, follow_redirects=False122 ).AndReturn(MockUrlfetchResult(200, expected_response))123 self.mox.ReplayAll()124 self.stub.MakeSyncCall('datastore_v3', 'Put', put_request, put_response)125 self.assertEqual(put_response, expected_put_response)126 def testRemotePutTransactionRequest(self):127 """A remote transactional PUT should fail."""128 put_request = self.CreatePutRequest('remoteapp')129 put_request.mutable_transaction().set_app('remoteapp')130 put_request.mutable_transaction().set_handle(123)131 put_response = datastore_pb.PutResponse()132 self.assertRaises(remote_api_put_stub.RemoteTransactionsUnimplemented,133 self.stub.MakeSyncCall, 'datastore_v3', 'Put',134 put_request, put_response)135 def testRemoteMultiPutRequest(self):136 """A request for Put should go local or remote depending on the key."""137 put_request = self.CreatePutRequest('remoteapp')138 put_request.add_entity().CopyFrom(put_request.entity(0))139 put_response = datastore_pb.PutResponse()140 key1 = db.Key.from_path('MyModel', 1, _app='localapp')141 key2 = db.Key.from_path('MyModel', 2, _app='localapp')142 expected_put_response = datastore_pb.PutResponse()143 expected_put_response.add_key().CopyFrom(key1._ToPb())144 expected_put_response.add_key().CopyFrom(key2._ToPb())145 expected_post = self.RemoteApiRequest('Put', put_request).Encode()146 expected_response = self.RemoteApiResponse(expected_put_response).Encode()147 remote_api_put_stub.urlfetch.fetch(148 self.remote_url, expected_post, urlfetch.POST,149 {'X-appcfg-api-version': '1', 'auth': 'good'}, follow_redirects=False150 ).AndReturn(MockUrlfetchResult(200, expected_response))151 self.mox.ReplayAll()152 self.stub.MakeSyncCall('datastore_v3', 'Put', put_request, put_response)153 self.assertEqual(put_response, expected_put_response)154 def testRemotePutRequestUnauthorized(self):155 """A remote put with a 'bad' urlfetch response."""156 put_request = self.CreatePutRequest('remoteapp')157 put_response = datastore_pb.PutResponse()158 expected_post = self.RemoteApiRequest('Put', put_request).Encode()159 remote_api_put_stub.urlfetch.fetch(160 self.remote_url, expected_post, urlfetch.POST,161 {'X-appcfg-api-version': '1', 'auth': 'good'}, follow_redirects=False162 ).AndReturn(MockUrlfetchResult(403, 'not authorized'))163 self.mox.ReplayAll()164 self.assertRaises(remote_api_put_stub.FetchFailed, self.stub.MakeSyncCall,165 'datastore_v3', 'Put', put_request, put_response)166 def testRemotePutRemoteException(self):167 """Test that a remote exception is bubbled back up."""168 put_request = self.CreatePutRequest('remoteapp')169 put_response = datastore_pb.PutResponse()170 expected_post = self.RemoteApiRequest('Put', put_request).Encode()171 expected_exception = db.Timeout('too slow')172 remote_response = remote_api_pb.Response()173 remote_response.mutable_exception().set_contents(174 pickle.dumps(expected_exception))175 expected_response = remote_response.Encode()176 remote_api_put_stub.urlfetch.fetch(177 self.remote_url, expected_post, urlfetch.POST,178 {'X-appcfg-api-version': '1', 'auth': 'good'}, follow_redirects=False179 ).AndReturn(MockUrlfetchResult(200, expected_response))180 self.mox.ReplayAll()181 self.assertRaises(db.Timeout, self.stub.MakeSyncCall,182 'datastore_v3', 'Put', put_request, put_response)183 def testLocalAllocateIds(self):184 """AllocateIds request should go local or remote depending on the key."""185 request = self.CreateAllocateIdsRequest('localapp')186 response = datastore_pb.AllocateIdsResponse()187 response.set_start(1)188 response.set_end(2)189 self.mock_stub.MakeSyncCall('datastore_v3', 'AllocateIds', request,190 response)191 self.mox.ReplayAll()192 self.stub.MakeSyncCall('datastore_v3', 'AllocateIds', request, response)193 def testRemoteAllocateIds(self):194 """AllocateIds request should go local or remote depending on the key."""195 request = self.CreateAllocateIdsRequest('remoteapp')196 response = datastore_pb.AllocateIdsResponse()197 response.set_start(1)198 response.set_end(2)199 expected_post = self.RemoteApiRequest('AllocateIds', request).Encode()200 expected_response = self.RemoteApiResponse(response).Encode()201 remote_api_put_stub.urlfetch.fetch(202 self.remote_url, expected_post, urlfetch.POST,203 {'X-appcfg-api-version': '1', 'auth': 'good'}, follow_redirects=False204 ).AndReturn(MockUrlfetchResult(200, expected_response))205 self.mox.ReplayAll()206 self.stub.MakeSyncCall('datastore_v3', 'AllocateIds', request, response)207class ConfigurationTest(googletest.TestCase):208 """Tests the configuration methods."""209 def setUp(self):210 self.mox = mox.Mox()211 self.mox.StubOutWithMock(remote_api_put_stub.urlfetch, 'fetch')212 self.mox.StubOutWithMock(remote_api_put_stub.random, 'random')213 self.remote_url = 'http://remoteapp.appspot.com/remote_api'214 self.app_id = 'remoteapp'215 self.rtok = '12345'216 def tearDown(self):217 try:218 self.mox.VerifyAll()219 finally:220 self.mox.UnsetStubs()221 def testGetAppid(self):222 """Sueccessfully get an appid."""223 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))224 response = "{app_id: %s, rtok: !!python/unicode '%s'}" % (225 self.app_id, self.rtok)226 remote_api_put_stub.urlfetch.fetch(227 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,228 {'X-appcfg-api-version': '1'}, follow_redirects=False229 ).AndReturn(MockUrlfetchResult(200, response))230 self.mox.ReplayAll()231 self.assertEqual(self.app_id,232 remote_api_put_stub.get_remote_appid(self.remote_url, {}))233 def testGetAppidAuthDenied(self):234 """Remote server returns denied."""235 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))236 remote_api_put_stub.urlfetch.fetch(237 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,238 {'X-appcfg-api-version': '1'}, follow_redirects=False239 ).AndReturn(MockUrlfetchResult(403, 'not authorized'))240 self.mox.ReplayAll()241 self.assertRaises(remote_api_put_stub.FetchFailed,242 remote_api_put_stub.get_remote_appid,243 self.remote_url, {})244 def testGetAppidUrlfetchFail(self):245 """Urlfetch fails."""246 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))247 remote_api_put_stub.urlfetch.fetch(248 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,249 {'X-appcfg-api-version': '1'}, follow_redirects=False250 ).AndRaise(urlfetch.Error)251 self.mox.ReplayAll()252 self.assertRaises(remote_api_put_stub.FetchFailed,253 remote_api_put_stub.get_remote_appid,254 self.remote_url, {})255 def testGetAppidBogusResult(self):256 """Remote server returns nonsense."""257 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))258 remote_api_put_stub.urlfetch.fetch(259 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,260 {'X-appcfg-api-version': '1'}, follow_redirects=False261 ).AndReturn(MockUrlfetchResult(200, "Hello World"))262 self.mox.ReplayAll()263 self.assertRaises(remote_api_put_stub.ConfigurationError,264 remote_api_put_stub.get_remote_appid,265 self.remote_url, {})266 def testGetAppidBogusBadRtok(self):267 """Remote server returns bad token."""268 response = "{app_id: %s, rtok: !!python/unicode '%s'}" % (269 self.app_id, 'badtoken')270 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))271 remote_api_put_stub.urlfetch.fetch(272 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,273 {'X-appcfg-api-version': '1'}, follow_redirects=False274 ).AndReturn(MockUrlfetchResult(200, response))275 self.mox.ReplayAll()276 self.assertRaises(remote_api_put_stub.ConfigurationError,277 remote_api_put_stub.get_remote_appid,278 self.remote_url, {})279 def testGetAppidNotQuiteYaml(self):280 """Remote server returns other nonsense."""281 response = "{curly braces are curly}"282 remote_api_put_stub.random.random().AndReturn(float('0.%s' % self.rtok))283 remote_api_put_stub.urlfetch.fetch(284 self.remote_url + '?rtok=%s' % self.rtok, None, urlfetch.GET,285 {'X-appcfg-api-version': '1'}, follow_redirects=False286 ).AndReturn(MockUrlfetchResult(200, response))287 self.mox.ReplayAll()288 self.assertRaises(remote_api_put_stub.ConfigurationError,289 remote_api_put_stub.get_remote_appid,290 self.remote_url, {})291if __name__ == '__main__':...

Full Screen

Full Screen

snippets_test.py

Source:snippets_test.py Github

copy

Full Screen

...16import snippets17from snippets_models import (Account, Address, Article,18 Bar, Contact, FlexEmployee, Message)19def test_query_account_equality(testbed):20 Account(userid=42).put()21 Account(userid=43).put()22 query = snippets.query_account_equality()23 accounts = query.fetch()24 assert len(accounts) == 125 assert accounts[0].userid == 4226def test_query_account_inequality(testbed):27 Account(userid=32).put()28 Account(userid=42).put()29 Account(userid=43).put()30 query = snippets.query_account_inequality()31 accounts = query.fetch()32 assert len(accounts) == 233 assert all(a.userid > 40 for a in accounts)34def test_query_account_multiple_filters(testbed):35 Account(userid=40).put()36 Account(userid=49).put()37 Account(userid=50).put()38 Account(userid=6).put()39 Account(userid=62).put()40 query = snippets.query_account_multiple_filters()41 accounts = query.fetch()42 assert len(accounts) == 243 assert all(40 <= a.userid < 50 for a in accounts)44def test_query_account_in_steps(testbed):45 Account(userid=40).put()46 Account(userid=49).put()47 Account(userid=50).put()48 Account(userid=6).put()49 Account(userid=62).put()50 _, _, query = snippets.query_account_in_steps()51 accounts = query.fetch()52 assert len(accounts) == 253 assert all(40 <= a.userid < 50 for a in accounts)54def test_query_article_inequality(testbed):55 Article(tags=['perl']).put()56 Article(tags=['perl', 'python']).put()57 query = snippets.query_article_inequality()58 articles = query.fetch()59 assert len(articles) == 160def test_query_article_inequality_explicit(testbed):61 Article(tags=['perl']).put()62 Article(tags=['perl', 'python']).put()63 query = snippets.query_article_inequality_explicit()64 articles = query.fetch()65 assert len(articles) == 166def test_articles_with_tags_example(testbed):67 snippets.articles_with_tags_example()68def test_query_article_in(testbed):69 Article(tags=['perl']).put()70 Article(tags=['perl', 'python']).put()71 Article(tags=['ruby']).put()72 Article(tags=['php']).put()73 query = snippets.query_article_in()74 articles = query.fetch()75 assert len(articles) == 376def test_query_article_in_equivalent(testbed):77 Article(tags=['perl']).put()78 Article(tags=['perl', 'python']).put()79 Article(tags=['ruby']).put()80 Article(tags=['php']).put()81 query = snippets.query_article_in_equivalent()82 articles = query.fetch()83 assert len(articles) == 384def test_query_article_nested(testbed):85 Article(tags=['python']).put() # excluded - no non-python86 Article(tags=['ruby']).put() # excluded - no python87 Article(tags=['python', 'ruby']).put() # included88 Article(tags=['python', 'jruby']).put() # included89 Article(tags=['python', 'ruby', 'jruby']).put() # included90 Article(tags=['python', 'php']).put() # included91 Article(tags=['python', 'perl']).put() # excluded92 query = snippets.query_article_nested()93 articles = query.fetch()94 assert len(articles) == 495def test_query_greeting_order(testbed):96 Greeting(content='3').put()97 Greeting(content='2').put()98 Greeting(content='1').put()99 Greeting(content='2').put()100 query = snippets.query_greeting_order()101 greetings = query.fetch()102 assert (greetings[0].content < greetings[1].content < greetings[3].content)103 assert greetings[1].content == greetings[2].content104 assert greetings[1].date > greetings[2].date105def test_query_greeting_multiple_orders(testbed):106 Greeting(content='3').put()107 Greeting(content='2').put()108 Greeting(content='1').put()109 Greeting(content='2').put()110 query = snippets.query_greeting_multiple_orders()111 greetings = query.fetch()112 assert (greetings[0].content < greetings[1].content < greetings[3].content)113 assert greetings[1].content == greetings[2].content114 assert greetings[1].date > greetings[2].date115def test_query_purchase_with_customer_key(testbed):116 Customer, Purchase, do_query = snippets.query_purchase_with_customer_key()117 charles = Customer(name='Charles')118 charles.put()119 snoop_key = Customer(name='Snoop').put()120 Purchase(price=123, customer=charles.key).put()121 Purchase(price=234, customer=snoop_key).put()122 purchases = do_query(charles)123 assert len(purchases) == 1124 assert purchases[0].price == 123125def test_query_purchase_with_ancestor_key(testbed):126 Customer, Purchase, create_purchase, do_query = (127 snippets.query_purchase_with_ancestor_key())128 charles = Customer(name='Charles')129 charles.put()130 snoop = Customer(name='Snoop')131 snoop.put()132 charles_purchase = create_purchase(charles)133 charles_purchase.price = 123134 charles_purchase.put()135 snoop_purchase = create_purchase(snoop)136 snoop_purchase.price = 234137 snoop_purchase.put()138 purchases = do_query(snoop)139 assert len(purchases) == 1140 assert purchases[0].price == 234141def test_print_query(testbed, capsys):142 snippets.print_query()143 stdout, _ = capsys.readouterr()144 assert '' in stdout145def test_query_contact_with_city(testbed):146 address = Address(type='home', street='Spear St', city='Amsterdam')147 address.put()148 Contact(name='Bertus Aafjes', addresses=[address]).put()149 address1 = Address(type='home', street='Damrak St', city='Amsterdam')150 address1.put()151 address2 = Address(type='work', street='Spear St', city='San Francisco')152 address2.put()153 Contact(name='Willem Jan Aalders', addresses=[address1, address2]).put()154 address = Address(type='home', street='29th St', city='San Francisco')155 address.put()156 Contact(name='Hans Aarsman', addresses=[address]).put()157 query = snippets.query_contact_with_city()158 contacts = query.fetch()159 assert len(contacts) == 2160def test_query_contact_sub_entities_beware(testbed):161 address = Address(type='home', street='Spear St', city='Amsterdam')162 address.put()163 Contact(name='Bertus Aafjes', addresses=[address]).put()164 address1 = Address(type='home', street='Damrak St', city='Amsterdam')165 address1.put()166 address2 = Address(type='work', street='Spear St', city='San Francisco')167 address2.put()168 Contact(name='Willem Jan Aalders', addresses=[address1, address2]).put()169 address = Address(type='home', street='29th St', city='San Francisco')170 address.put()171 Contact(name='Hans Aarsman', addresses=[address]).put()172 query = snippets.query_contact_sub_entities_beware()173 contacts = query.fetch()174 assert len(contacts) == 2175 for contact in contacts:176 assert ('Spear St' in [a.street for a in contact.addresses] or177 'Amsterdam' in [a.city for a in contact.addresses])178def test_query_contact_multiple_values_in_single_sub_entity(testbed):179 address = Address(type='home', street='Spear St', city='Amsterdam')180 address.put()181 Contact(name='Bertus Aafjes', addresses=[address]).put()182 address1 = Address(type='home', street='Damrak St', city='Amsterdam')183 address1.put()184 address2 = Address(type='work', street='Spear St', city='San Francisco')185 address2.put()186 Contact(name='Willem Jan Aalders', addresses=[address1, address2]).put()187 address = Address(type='home', street='29th St', city='San Francisco')188 address.put()189 Contact(name='Hans Aarsman', addresses=[address]).put()190 query = snippets.query_contact_multiple_values_in_single_sub_entity()191 contacts = query.fetch()192 assert len(contacts) == 1193 assert any(a.city == 'San Francisco' and a.street == 'Spear St'194 for a in contacts[0].addresses)195def test_query_properties_named_by_string_on_expando(testbed):196 FlexEmployee(location='SF').put()197 FlexEmployee(location='Amsterdam').put()198 query = snippets.query_properties_named_by_string_on_expando()199 employees = query.fetch()200 assert len(employees) == 1201def test_query_properties_named_by_string_for_defined_properties(testbed):202 Article(title='from').put()203 Article(title='to').put()204 query = snippets.query_properties_named_by_string_for_defined_properties(205 'title', 'from')206 articles = query.fetch()207 assert len(articles) == 1208def test_query_properties_named_by_string_using_getattr(testbed):209 Article(title='from').put()210 Article(title='to').put()211 query = snippets.query_properties_named_by_string_using_getattr(212 'title', 'from')213 articles = query.fetch()214 assert len(articles) == 1215def test_order_query_results_by_property(testbed):216 Article(title='2').put()217 Article(title='1').put()218 FlexEmployee(location=2).put()219 FlexEmployee(location=1).put()220 expando_query, property_query = snippets.order_query_results_by_property(221 'title')222 assert expando_query.fetch()[0].location == 1223 assert property_query.fetch()[0].title == '1'224def test_print_query_keys(testbed, capsys):225 for i in range(3):226 Article(title='title {}'.format(i)).put()227 snippets.print_query_keys(Article.query())228 stdout, _ = capsys.readouterr()229 assert "Key('Article'" in stdout230def test_reverse_queries(testbed):231 for i in range(11):232 Bar().put()233 (bars, cursor, more), (r_bars, r_cursor, r_more) = (234 snippets.reverse_queries())235 assert len(bars) == 10236 assert len(r_bars) == 10237 for prev_bar, bar in zip(bars, bars[1:]):238 assert prev_bar.key < bar.key239 for prev_bar, bar in zip(r_bars, r_bars[1:]):240 assert prev_bar.key > bar.key241def test_fetch_message_accounts_inefficient(testbed):242 for i in range(1, 6):243 Account(username='Account %s' % i, id=i).put()244 Message(content='Message %s' % i, userid=i).put()245 message_account_pairs = snippets.fetch_message_accounts_inefficient(246 Message.query().order(Message.userid))247 assert len(message_account_pairs) == 5248 print(repr(message_account_pairs))249 for i in range(1, 6):250 message, account = message_account_pairs[i - 1]251 assert message.content == 'Message %s' % i252 assert account.username == 'Account %s' % i253def test_fetch_message_accounts_efficient(testbed):254 for i in range(1, 6):255 Account(username='Account %s' % i, id=i).put()256 Message(content='Message %s' % i, userid=i).put()257 message_account_pairs = snippets.fetch_message_accounts_efficient(258 Message.query().order(Message.userid))259 assert len(message_account_pairs) == 5260 for i in range(1, 6):261 message, account = message_account_pairs[i - 1]262 assert message.content == 'Message %s' % i263 assert account.username == 'Account %s' % i264def test_fetch_good_articles_using_gql_with_explicit_bind(testbed):265 for i in range(1, 6):266 Article(stars=i).put()267 query, query2 = snippets.fetch_good_articles_using_gql_with_explicit_bind()268 articles = query2.fetch()269 assert len(articles) == 2270 assert all(a.stars > 3 for a in articles)271def test_fetch_good_articles_using_gql_with_inlined_bind(testbed):272 for i in range(1, 6):273 Article(stars=i).put()274 query = snippets.fetch_good_articles_using_gql_with_inlined_bind()275 articles = query.fetch()276 assert len(articles) == 2...

Full Screen

Full Screen

test_rest_api_put.py

Source:test_rest_api_put.py Github

copy

Full Screen

...13 resp_post = client.post(url_post, data=data, headers={'Authorization': f'JWT {auth}'})14 challenge_id = resp_post.json['challenge']['id']15 16 url_put = 'cSharp/c-sharp-challenges/' + str(challenge_id) 17 resp_put = client.put(url_put, data=data_put, headers={'Authorization': f'JWT {auth}'})18 #Assert19 assert resp_put.status_code == 40920 assert resp_put.json == {'Complexity': 'Must be between 1 and 5'}21 cleanup()22def test_update_code_w_sintax_error(client,create_test_data, auth):23 #Arrange24 url_post = 'cSharp/c-sharp-challenges'25 data = create_test_data['data']26 data_put = {'source_code_file': open('tests/cSharp/test-files/ExampleSintaxErrors.cs', 'rb')}27 28 #Act29 resp_post = client.post(url_post, data=data, headers={'Authorization': f'JWT {auth}'})30 challenge_id = resp_post.json['challenge']['id'] 31 url_put = 'cSharp/c-sharp-challenges/' + str(challenge_id) 32 resp_put = client.put(url_put, data=data_put, headers={'Authorization': f'JWT {auth}'})33 34 #Assert35 assert resp_put.status_code == 40936 assert resp_put.json == {'Source code': 'Sintax errors'}37 cleanup()38def test_update_complexity_and_repair_objective(client, create_test_data, auth):39 url_post = 'cSharp/c-sharp-challenges'40 data = create_test_data['data']41 data_put = create_challenge(repair_objective='Test this method', complexity='4')42 expected_response = {"challenge": { "code": create_test_data['content_code'],43 "tests_code": create_test_data['content_tests_code'],44 "repair_objective": "Test this method",45 "complexity": 4,46 "best_score": 047 }48 }49 resp_post = client.post(url_post, data=data, headers={'Authorization': f'JWT {auth}'})50 challenge_id = resp_post.json['challenge']['id']51 52 url_put = 'cSharp/c-sharp-challenges/' + str(challenge_id) 53 resp_put = client.put(url_put, data=data_put, headers={'Authorization': f'JWT {auth}'})54 resp_put_json = resp_put.json55 del resp_put_json['challenge']['id']56 print(resp_put.json)57 58 #Assert59 assert resp_put.status_code == 20060 assert resp_put_json == expected_response61 cleanup()62def test_update_code_passes_all_tests(client, create_test_data, auth):63 # Arrange64 url = 'cSharp/c-sharp-challenges'65 data_put = create_challenge(code_name='Example1', code='ExampleNoFails')66 expected_response = {'Challenge': 'Must fail at least one test'}67 # Act68 resp_post = client.post(url, data=create_test_data['data'], headers={'Authorization': f'JWT {auth}'})69 ch_id = resp_post.json['challenge']['id']70 url += '/' + str(ch_id)71 resp_put = client.put(url, data=data_put, headers={'Authorization': f'JWT {auth}'})72 resp_json = resp_put.json73 resp_code = resp_put.status_code74 # Assert75 assert resp_code == 40976 assert resp_json == expected_response77 # Cleanup78 cleanup()79def test_put_non_existent_challenge(client, auth):80 # Arrange81 url = 'cSharp/c-sharp-challenges/1'82 expected_response = {"challenge": "There is no challenge for this id"}83 data_put={}84 # Act85 resp = client.put(url, data=data_put, headers={'Authorization': f'JWT {auth}'})86 resp_json = resp.json87 # Assert88 assert resp_json == expected_response89 assert resp.status_code == 40490 # Cleanup91 cleanup()92def test_put_with_code_and_test_and_without_challenge(client, create_test_data, auth):93 # Arrange94 url = 'cSharp/c-sharp-challenges'95 data_post = create_test_data['data']96 data_put = create_challenge(code="BaseExample3", tests_code="BaseTest3")97 with open('tests/cSharp/test-files/BaseExample3.cs') as f:98 new_content_code = f.read()99 with open('tests/cSharp/test-files/BaseTest3.cs') as f:100 new_content_tests_code = f.read()101 # Act102 resp_post = client.post(url, data=data_post, headers={'Authorization': f'JWT {auth}'})103 challenge_id = resp_post.json["challenge"]["id"]104 url_put = 'cSharp/c-sharp-challenges/' + str(challenge_id)105 resp_put = client.put(url_put, data=data_put, headers={'Authorization': f'JWT {auth}'})106 # Assert107 resp_put_json = resp_put.json108 del resp_put_json ['challenge']['id']109 110 assert resp_put.status_code == 200111 assert resp_put_json == {"challenge": { "best_score": 0,112 "code": new_content_code,113 "complexity": 5,114 "repair_objective": "Testing",115 "tests_code":new_content_tests_code 116 }117 }118 119 # Cleanup120 cleanup()121def test_put_with_only_test(client, create_test_data, auth):122 # Arrange123 url = 'cSharp/c-sharp-challenges'124 data_post = create_test_data['data']125 data_put = create_challenge(tests_name='Example1Test', tests_code="BaseTest")126 with open('tests/cSharp/test-files/BaseTest.cs') as f:127 new_content_tests_code = f.read()128 expected_response = {"challenge": { "best_score": 0,129 "code":create_test_data['content_code'],130 "complexity": 5,131 "repair_objective": "Testing",132 "tests_code":new_content_tests_code 133 }134 }135 # Act136 resp_post = client.post(url, data=data_post, headers={'Authorization': f'JWT {auth}'})137 challenge_id = resp_post.json["challenge"]["id"]138 url_put = 'cSharp/c-sharp-challenges/' + str(challenge_id)139 resp_put = client.put(url_put, data=data_put, headers={'Authorization': f'JWT {auth}'})140 # Assert141 resp_put_json = resp_put.json142 del resp_put_json ['challenge']['id']143 144 assert resp_put.status_code == 200145 assert resp_put_json == expected_response146 147 # Cleanup148 cleanup()149def test_update_test_with_sintax_error(client, create_test_data, auth):150 # Arrange151 url = 'cSharp/c-sharp-challenges'152 data_put = create_challenge(tests_name='Example1Test', tests_code='TestSintaxErrors')153 expected_response = {'Test': 'Sintax errors'}154 # Act155 resp_post = client.post(url, data=create_test_data['data'], headers={'Authorization': f'JWT {auth}'})156 ch_id = resp_post.json['challenge']['id']157 url += '/' + str(ch_id)158 resp_put = client.put(url, data=data_put, headers={'Authorization': f'JWT {auth}'})159 resp_json = resp_put.json160 resp_code = resp_put.status_code161 # Assert162 assert resp_code == 409163 assert resp_json == expected_response164 # Cleanup165 cleanup()166def test_update_code_and_test_not_valid(client, create_test_data, auth):167 # Arrange168 url = 'cSharp/c-sharp-challenges'169 data_put_1 = create_challenge(code="ExampleSintaxErrors", tests_code="BaseTest")170 data_put_2 = create_challenge(code="ExampleNoFails", tests_code="BaseTest")171 data_put_3 = create_challenge(code="BaseExample", tests_code="TestSintaxErrors")172 expected_response_1 = {'Source code': 'Sintax errors'}173 expected_response_2 = {'Challenge': 'Must fail at least one test'}174 expected_response_3 = {'Test': 'Sintax errors'}175 resp_post = client.post(url, data=create_test_data['data'], headers={'Authorization': f'JWT {auth}'})176 ch_id = resp_post.json['challenge']['id']177 url += '/' + str(ch_id)178 # Act179 resp_put_1 = client.put(url, data=data_put_1, headers={'Authorization': f'JWT {auth}'})180 resp_put_2 = client.put(url, data=data_put_2, headers={'Authorization': f'JWT {auth}'})181 resp_put_3 = client.put(url, data=data_put_3, headers={'Authorization': f'JWT {auth}'})182 resp_json_1 = resp_put_1.json183 resp_json_2 = resp_put_2.json184 resp_json_3 = resp_put_3.json185 response_codes = (resp_put_1.status_code,186 resp_put_2.status_code,187 resp_put_3.status_code)188 # Assert189 assert all(response == 409 for response in response_codes)190 assert resp_json_1 == expected_response_1191 assert resp_json_2 == expected_response_2192 assert resp_json_3 == expected_response_3193 # Cleanup194 cleanup()195def test_update_valid_code(client, create_test_data, auth):196 # Arrange197 url = 'cSharp/c-sharp-challenges'198 data_put = create_challenge(code='BaseExample')199 200 expected_response = {"challenge": { "best_score": 0,201 "code":create_test_data['content_code'],202 "complexity": 5,203 "repair_objective": "Testing",204 "tests_code":create_test_data['content_tests_code'] 205 }206 }207 208 # Act209 resp_post = client.post(url, data=create_test_data['data'], headers={'Authorization': f'JWT {auth}'})210 ch_id = resp_post.json['challenge']['id']211 url += '/' + str(ch_id)212 resp_put = client.put(url, data=data_put, headers={'Authorization': f'JWT {auth}'})213 resp_put_json = resp_put.json214 del resp_put_json ['challenge']['id']215 216 #Assert217 assert resp_put.status_code == 200218 assert resp_put_json == expected_response219 # Cleanup220 cleanup()221def test_update_nothing(client, create_test_data, auth):222 #Arrange223 url = 'cSharp/c-sharp-challenges'224 data_put = {}225 226 expected_response = {"challenge": { "best_score": 0,227 "code":create_test_data['content_code'],228 "complexity": 5,229 "repair_objective": "Testing",230 "tests_code":create_test_data['content_tests_code'] 231 }232 }233 #Act234 resp_post = client.post(url, data=create_test_data['data'], headers={'Authorization': f'JWT {auth}'})235 ch_id = resp_post.json['challenge']['id']236 url += '/' + str(ch_id)237 resp_put = client.put(url, data=data_put, headers={'Authorization': f'JWT {auth}'})238 resp_put_json = resp_put.json239 del resp_put_json ['challenge']['id']240 #Assert241 assert resp_put.status_code == 200242 assert resp_put_json == expected_response243 #Cleanup...

Full Screen

Full Screen

Task1_test.py

Source:Task1_test.py Github

copy

Full Screen

...6 self.assertRaises(ValueError, LRU, -1)7 def test_put_1(self): 8 """ Test Case: To check for put functionality for one value """9 lru = LRU(5)10 lru.put("1", 1)11 lru.put("2", 2)12 lru.put("3", 3)13 lru.put("4", 4)14 lru.put("5", 5)15 self.assertEqual(lru.get("5"), 5, "should be 5")16 def test_put_2(self): 17 """ Test Case: To check for multiple put functionality after LRU maximum size is achieved """18 lru = LRU(5)19 lru.put("1", 1)20 lru.put("2", 2)21 lru.put("3", 3)22 lru.put("4", 4)23 lru.put("5", 5)24 self.assertEqual(lru.get("5"), 5, "should be 5")25 lru.put("6", 6)26 lru.put("7", 7)27 self.assertEqual(lru.get("6"), 6, "should be 6")28 self.assertEqual(lru.get("7"), 7, "should be 7")29 def test_put_3(self): 30 """ Test Case: To check for put functionality for the value which is not the most recent in the size of LRU """31 lru = LRU(5)32 lru.put("1", 1)33 lru.put("2", 2)34 lru.put("3", 3)35 lru.put("4", 4)36 lru.put("5", 5)37 self.assertEqual(lru.get("5"), 5, "should be 5")38 lru.put("6", 6)39 lru.put("7", 7)40 self.assertEqual(lru.get("6"), 6, "should be 6")41 self.assertEqual(lru.get("7"), 7, "should be 7")42 self.assertRaises(KeyError, lru.get, "1")43 44 45 def test_get_1(self): 46 """ Test Case: To check for get functionality for all the values which was put using put function """47 lru = LRU(5)48 lru.put("1", 1)49 lru.put("2", 2)50 lru.put("3", 3)51 lru.put("4", 4)52 lru.put("5", 5)53 self.assertEqual(lru.get("1"), 1, "should be 1")54 self.assertEqual(lru.get("2"), 2, "should be 2")55 self.assertEqual(lru.get("3"), 3, "should be 3")56 self.assertEqual(lru.get("4"), 4, "should be 4")57 self.assertEqual(lru.get("5"), 5, "should be 5")58 def test_get_2(self): 59 """ Test Case: To check for get functionality for a value that doesn't exist in the LRU cache """60 lru = LRU(5)61 lru.put("1", 1)62 lru.put("2", 2)63 lru.put("3", 3)64 lru.put("4", 4)65 lru.put("5", 5)66 self.assertEqual(lru.get("1"), 1, "should be 1")67 self.assertEqual(lru.get("2"), 2, "should be 2")68 self.assertEqual(lru.get("3"), 3, "should be 3")69 self.assertEqual(lru.get("4"), 4, "should be 4")70 self.assertEqual(lru.get("5"), 5, "should be 5")71 self.assertRaises(KeyError, lru.get, "10")72 def test_get_3(self): 73 """ Test Case: To check for get functionality after multiple put """74 lru = LRU(15)75 lru.put("1", 1)76 lru.put("2", 2)77 lru.put("3", 3)78 lru.put("4", 4)79 lru.put("5", 5)80 self.assertEqual(lru.get("1"), 1, "should be 1")81 self.assertEqual(lru.get("2"), 2, "should be 2")82 self.assertEqual(lru.get("3"), 3, "should be 3")83 self.assertEqual(lru.get("4"), 4, "should be 4")84 self.assertEqual(lru.get("5"), 5, "should be 5")85 self.assertRaises(KeyError, lru.get, "10")86 lru.put("6", 6)87 lru.put("7", 7)88 lru.put("8", 8)89 lru.put("9", 9)90 lru.put("10", 10)91 self.assertEqual(lru.get("10"), 10, "should be 10")92 self.assertEqual(lru.get("9"), 9, "should be 10")93 self.assertEqual(lru.get("8"), 8, "should be 10")94 self.assertEqual(lru.get("7"), 7, "should be 10")95 self.assertEqual(lru.get("6"), 6, "should be 10")96 def test_delete_1(self): 97 """ Test Case: To check for delete functionality for different scnearios """98 lru = LRU(5)99 lru.put("1", 1)100 lru.put("2", 2)101 lru.put("3", 3)102 lru.put("4", 4)103 lru.put("5", 5)104 lru.delete("5")105 self.assertRaises(KeyError, lru.get, "5")106 self.assertEqual(lru.get("4"), 4, "should be 4")107 self.assertEqual(lru.get("3"), 3, "should be 3")108 lru.delete("3")109 self.assertRaises(KeyError, lru.get, "3")110 lru.delete("1")111 self.assertRaises(KeyError, lru.get, "1")112 self.assertEqual(lru.get("2"), 2, "should be 2")113 def test_delete_2(self): 114 """ Test Case: To check for delete functionality for one value """115 lru = LRU(15)116 lru.put("1", 1)117 lru.put("2", 2)118 lru.put("3", 3)119 lru.put("4", 4)120 lru.put("5", 5)121 lru.delete("5")122 self.assertRaises(KeyError, lru.get, "5")123 self.assertEqual(lru.get("3"), 3, "should be 3")124 def test_delete_3(self): 125 """ Test Case: To check for multiple delete functionality for one value """126 lru = LRU(1)127 lru.put("1", 1)128 lru.delete("1")129 self.assertRaises(KeyError, lru.get, "1")130 self.assertRaises(KeyError, lru.delete, "1")131 132 def test_size_1(self): 133 """ Test Case: To check for size of LRU with put and get functionality """134 lru = LRU(5)135 lru.put("1", 1)136 lru.put("2", 2)137 lru.put("3", 3)138 lru.put("4", 4)139 lru.put("5", 5)140 lru.put("6", 6)141 lru.put("7", 7)142 lru.put("8", 8)143 lru.put("9", 9)144 lru.put("10", 10)145 146 self.assertEqual(lru.get("10"), 10, "should be 10")147 self.assertRaises(KeyError, lru.get, "1")148 self.assertEqual(lru.get("9"), 9, "should be 9")149 self.assertRaises(KeyError, lru.get, "2")150 self.assertEqual(lru.get("8"), 8, "should be 8")151 self.assertRaises(KeyError, lru.get, "3")152 self.assertEqual(lru.get("7"), 7, "should be 7")153 self.assertRaises(KeyError, lru.get, "5")154 self.assertEqual(lru.get("6"), 6, "should be 6")155 def test_size_2(self): 156 """ Test Case: To check for size of LRU with multiple put and get functionality with different size initialization """157 lru = LRU(5)158 lru.put("1", 1)159 lru.put("2", 2)160 lru.put("3", 3)161 lru.put("4", 4)162 lru.put("5", 5)163 lru.put("6", 6)164 lru.put("7", 7)165 lru.put("8", 8)166 lru.put("9", 9)167 lru.put("10", 10)168 169 self.assertEqual(lru.get("10"), 10, "should be 10")170 self.assertRaises(KeyError, lru.get, "1")171 self.assertEqual(lru.get("9"), 9, "should be 10")172 self.assertRaises(KeyError, lru.get, "2")173 self.assertEqual(lru.get("8"), 8, "should be 10")174 self.assertRaises(KeyError, lru.get, "3")175 self.assertEqual(lru.get("7"), 7, "should be 10")176 self.assertRaises(KeyError, lru.get, "5")177 self.assertEqual(lru.get("6"), 6, "should be 10")178 lru = LRU(10)179 lru.put("1", 1)180 lru.put("2", 2)181 lru.put("3", 3)182 lru.put("4", 4)183 lru.put("5", 5)184 lru.put("6", 6)185 lru.put("7", 7)186 lru.put("8", 8)187 lru.put("9", 9)188 lru.put("10", 10)189 self.assertEqual(lru.get("1"), 1, "should be 1")190 self.assertEqual(lru.get("2"), 2, "should be 2")191 self.assertEqual(lru.get("3"), 3, "should be 3")192 self.assertEqual(lru.get("4"), 4, "should be 4")193 self.assertEqual(lru.get("5"), 5, "should be 5")194 self.assertEqual(lru.get("6"), 6, "should be 6")195 self.assertEqual(lru.get("7"), 7, "should be 7")196 self.assertEqual(lru.get("8"), 8, "should be 8")197 self.assertEqual(lru.get("9"), 9, "should be 9")198 self.assertEqual(lru.get("10"), 10, "should be 10")199 def test_reset_1(self): 200 """ Test Case: To check the reset funcitonality for the LRU algorithm """201 lru = LRU(5)202 lru.put("1", 1)203 lru.put("2", 2)204 lru.put("3", 3)205 lru.put("4", 4)206 lru.put("5", 5)207 lru.put("6", 6)208 lru.put("7", 7)209 lru.put("8", 8)210 lru.put("9", 9)211 lru.put("10", 10)212 213 self.assertEqual(lru.get("10"), 10, "should be 10")214 self.assertRaises(KeyError, lru.get, "1")215 self.assertEqual(lru.get("9"), 9, "should be 9")216 self.assertRaises(KeyError, lru.get, "2")217 lru.reset()218 self.assertRaises(KeyError, lru.get, "9")219 def test_reset_2(self): 220 """ Test Case: To check for reset functionality of LRU with put and get functionality """221 lru = LRU(5)222 lru.put("1", 1)223 lru.put("2", 2)224 lru.put("3", 3)225 lru.put("4", 4)226 lru.put("5", 5)227 lru.put("6", 6)228 lru.put("7", 7)229 lru.put("8", 8)230 lru.put("9", 9)231 lru.put("10", 10)232 lru.reset()233 self.assertRaises(KeyError, lru.get, "10")234 235 def test_reset_3(self): 236 """ Test Case: To check for reset functionality of LRU put and get functionality after using reset """237 lru = LRU(5)238 lru.put("1", 1)239 lru.put("2", 2)240 lru.put("3", 3)241 lru.put("4", 4)242 lru.put("5", 5)243 lru.put("6", 6)244 lru.put("7", 7)245 lru.put("8", 8)246 lru.put("9", 9)247 lru.put("10", 10)248 lru.reset()249 self.assertRaises(KeyError, lru.get, "10") 250 lru.put("1", 1)251 lru.put("2", 2)252 lru.put("3", 3)253 lru.put("4", 4)254 lru.put("5", 5)255 self.assertEqual(lru.get("1"), 1, "should be 1")256if __name__ == '__main__':...

Full Screen

Full Screen

pdumper.py

Source:pdumper.py Github

copy

Full Screen

...24 elif self.options == "listsymbols":25 self.handleListSymbols(expanded)26 else:27 self.handleListVars()28 def put(self, value):29 #sys.stdout.write(value)30 self.buffer += value31 def putField(self, name, value):32 self.put('%s="%s",' % (name, value))33 def putItemCount(self, count):34 self.put('value="<%s items>",' % count)35 def putEllipsis(self):36 self.put('{name="<incomplete>",value="",type="",numchild="0"},')37 def cleanType(self, type):38 t = str(type)39 if t.startswith("<type '") and t.endswith("'>"):40 t = t[7:-2]41 if t.startswith("<class '") and t.endswith("'>"):42 t = t[8:-2]43 return t44 def putType(self, type, priority = 0):45 self.putField("type", self.cleanType(type))46 def putAddress(self, addr):47 self.put('addr="%s",' % cleanAddress(addr))48 def putNumChild(self, numchild):49 self.put('numchild="%s",' % numchild)50 def putValue(self, value, encoding = None, priority = 0):51 self.putField("value", value)52 def putName(self, name):53 self.put('name="%s",' % name)54 def isExpanded(self, iname):55 #self.warn("IS EXPANDED: %s in %s" % (iname, self.expandedINames))56 if iname.startswith("None"):57 raise "Illegal iname '%s'" % iname58 #self.warn(" --> %s" % (iname in self.expandedINames))59 return iname in self.expandedINames60 def isExpandedIName(self, iname):61 return iname in self.expandedINames62 def itemFormat(self, item):63 format = self.formats.get(str(cleanAddress(item.value.address)))64 if format is None:65 format = self.typeformats.get(stripClassTag(str(item.value.type)))66 return format67 def dumpFrame(self, frame):68 for var in frame.f_locals.keys():69 if var == "__file__":70 continue71 #if var == "__name__":72 # continue73 if var == "__package__":74 continue75 if var == "qdebug":76 continue77 if var != '__builtins__':78 value = frame.f_locals[var]79 self.dumpValue(value, var, "local.%s" % var)80 def dumpValue(self, value, name, iname):81 t = type(value)82 tt = self.cleanType(t)83 if tt == "module" or tt == "function":84 return85 if str(value).startswith("<class '"):86 return87 # FIXME: Should we?88 if str(value).startswith("<enum-item "):89 return90 self.put("{")91 self.putField("iname", iname)92 self.putName(name)93 self.putType(tt)94 if tt == "NoneType":95 self.putValue("None")96 self.putNumChild(0)97 elif tt == "list" or tt == "tuple":98 self.putItemCount(len(value))99 #self.putValue(value)100 self.put("children=[")101 for i in xrange(len(value)):102 self.dumpValue(value[i], str(i), "%s.%d" % (iname, i))103 self.put("]")104 elif tt == "str":105 v = value106 self.putValue(v.encode('hex'))107 self.putField("valueencoded", 6)108 self.putNumChild(0)109 elif tt == "unicode":110 v = value111 self.putValue(v.encode('hex'))112 self.putField("valueencoded", 6)113 self.putNumChild(0)114 elif tt == "buffer":115 v = str(value)116 self.putValue(v.encode('hex'))117 self.putField("valueencoded", 6)118 self.putNumChild(0)119 elif tt == "xrange":120 b = iter(value).next()121 e = b + len(value)122 self.putValue("(%d, %d)" % (b, e))123 self.putNumChild(0)124 elif tt == "dict":125 self.putItemCount(len(value))126 self.putField("childnumchild", 2)127 self.put("children=[")128 i = 0129 for (k, v) in value.iteritems():130 self.put("{")131 self.putType(" ")132 self.putValue("%s: %s" % (k, v))133 if self.isExpanded(iname):134 self.put("children=[")135 self.dumpValue(k, "key", "%s.%d.k" % (iname, i))136 self.dumpValue(v, "value", "%s.%d.v" % (iname, i))137 self.put("]")138 self.put("},")139 i += 1140 self.put("]")141 elif tt == "class":142 pass143 elif tt == "module":144 pass145 elif tt == "function":146 pass147 elif str(value).startswith("<enum-item "):148 # FIXME: Having enums always shown like this is not nice.149 self.putValue(str(value)[11:-1])150 self.putNumChild(0)151 else:152 v = str(value)153 p = v.find(" object at ")154 if p > 1:155 v = "@" + v[p + 11:-1]156 self.putValue(v)157 if self.isExpanded(iname):158 self.put("children=[")159 for child in dir(value):160 if child == "__dict__":161 continue162 if child == "__doc__":163 continue164 if child == "__module__":165 continue166 attr = getattr(value, child)167 if callable(attr):168 continue169 try:170 self.dumpValue(attr, child, "%s.%s" % (iname, child))171 except:172 pass173 self.put("],")174 self.put("},")175 def warn(self, msg):176 self.putField("warning", msg)177 def handleListVars(self):178 # Trigger error to get a backtrace.179 frame = None180 #self.warn("frame: %s" % frame)181 try:182 raise ZeroDivisionError183 except ZeroDivisionError:184 frame = sys.exc_info()[2].tb_frame.f_back185 limit = 30186 n = 0187 isActive = False188 while frame is not None and n < limit:189 #self.warn("frame: %s" % frame.f_locals.keys())190 lineno = frame.f_lineno191 code = frame.f_code192 filename = code.co_filename193 name = code.co_name194 if isActive:195 linecache.checkcache(filename)196 line = linecache.getline(filename, lineno, frame.f_globals)197 self.dumpFrame(frame)198 if name == "<module>":199 isActive = False200 if name == "trace_dispatch":201 isActive = True202 frame = frame.f_back203 n = n + 1204 #sys.stdout.flush()205 def handleListModules(self):206 self.put("modules=[");207 for name in sys.modules:208 self.put("{")209 self.putName(name)210 self.putValue(sys.modules[name])211 self.put("},")212 self.put("]")213 #sys.stdout.flush()214 def handleListSymbols(self, module):215 #self.put("symbols=%s" % dir(sys.modules[module]))216 self.put("symbols=[");217 for name in sys.modules:218 self.put("{")219 self.putName(name)220 #self.putValue(sys.modules[name])221 self.put("},")222 self.put("]")223 #sys.stdout.flush()224 d = QDebug(options, expanded, typeformats, individualformats, watchers)225 #print d.buffer226 sys.stdout.write(d.buffer)...

Full Screen

Full Screen

qtcreator_debugging_helpers.py

Source:qtcreator_debugging_helpers.py Github

copy

Full Screen

1# this file contains functions needed by qtcreator to provide a better introspection into lanelet's objects.2# simply specify its path in qtCreator under Options->Debugger->Locals&Expressionts->Extra debugging helpers.3from dumper import *4def vectorSize(vectorValue):5 innerType = vectorValue.type[0]6 (start, finish, alloc) = vectorValue.split("ppp")7 size = int((finish - start) / innerType.size())8 return size9def mapSize(mapValue):10 (compare, stuff, parent, left, right, size) = mapValue.split('pppppp')11 return size12def unorderedMapSize(value):13 try:14 # gcc ~= 4.715 size = value["_M_element_count"].integer()16 start = value["_M_before_begin"]["_M_nxt"]17 except BaseException:18 try:19 # libc++ (Mac)20 size = value["_M_h"]["_M_element_count"].integer()21 start = value["_M_h"]["_M_bbegin"]["_M_node"]["_M_nxt"]22 except BaseException:23 try:24 # gcc 4.9.125 size = value["_M_h"]["_M_element_count"].integer()26 start = value["_M_h"]["_M_before_begin"]["_M_nxt"]27 except BaseException:28 # gcc 4.6.229 size = value["_M_element_count"].integer()30 start = value["_M_buckets"].dereference()31 return size32def displayStringValue(d, value):33 innerType = value.type[0]34 (data, size) = value.split("pI")35 d.check(0 <= size) # and size <= alloc and alloc <= 100*1000*1000)36 d.putCharArrayHelper(data, size, innerType, d.currentItemFormat(), makeExpandable=False)37def qdump__lanelet__LineString2d(d, value):38 data = value["constData_"]["_M_ptr"].dereference()39 d.putValue(data["id"].integer())40 d.putNumChild(4)41 if d.isExpanded():42 with Children(d):43 d.putSubItem("id", data["id"])44 d.putSubItem("inverted", value["inverted_"])45 d.putSubItem("attributes", data["attributes"])46 d.putSubItem("points", data["points_"])47def qdump__lanelet__ConstLineString2d(d, value):48 qdump__lanelet__LineString2d(d, value)49def qdump__lanelet__LineString3d(d, value):50 data = value["constData_"]["_M_ptr"].dereference()51 d.putValue(data["id"].integer())52 d.putNumChild(4)53 if d.isExpanded():54 with Children(d):55 d.putSubItem("id", data["id"])56 d.putSubItem("inverted", value["inverted_"])57 d.putSubItem("attributes", data["attributes"])58 d.putSubItem("points", data["points_"])59def qdump__lanelet__ConstLineString3d(d, value):60 qdump__lanelet__LineString3d(d, value)61def qdump__lanelet__Polygon3d(d, value):62 qdump__lanelet__LineString3d(d, value)63def qdump__lanelet__ConstPolygon3d(d, value):64 qdump__lanelet__ConstLineString3d(d, value)65def qdump__lanelet__Polygon2d(d, value):66 qdump__lanelet__LineString2d(d, value)67def qdump__lanelet__ConstPolygon2d(d, value):68 qdump__lanelet__ConstLineString2d(d, value)69def qdump__lanelet__Point3d(d, value):70 data = value["constData_"]["_M_ptr"].dereference()71 d.putValue(data["id"].integer())72 d.putNumChild(6)73 if d.isExpanded():74 p = data["point"]75 with Children(d):76 (x, y, z) = p.split('ddd')77 with SubItem(d, "x"):78 d.putValue(x)79 d.putType("double")80 with SubItem(d, "y"):81 d.putValue(y)82 d.putType("double")83 with SubItem(d, "z"):84 d.putValue(z)85 d.putType("double")86 d.putSubItem("id", data["id"])87 d.putSubItem("attributes", data["attributes"])88 d.putSubItem("point2d_", data["point2d_"])89def qdump__lanelet__Point2d(d, value):90 qdump__lanelet__Point3d(d, value)91def qdump__lanelet__ConstPoint3d(d, value):92 qdump__lanelet__Point3d(d, value)93def qdump__lanelet__ConstPoint2d(d, value):94 qdump__lanelet__Point3d(d, value)95def qdump__lanelet__Lanelet(d, value):96 data = value["constData_"]["_M_ptr"].dereference()97 d.putValue(data["id"].integer())98 d.putNumChild(8)99 if d.isExpanded():100 with Children(d):101 d.putSubItem("id", data["id"])102 d.putSubItem("attributes", data["attributes"])103 d.putSubItem("leftBound", data["leftBound_"])104 d.putSubItem("rightBound", data["rightBound_"])105 d.putSubItem("regulatoryElements", data["regulatoryElements_"])106 d.putSubItem("centerline", data["centerline_"])107 d.putSubItem("inverted", value["inverted_"])108def qdump__lanelet__ConstLanelet(d, value):109 qdump__lanelet__Lanelet(d, value)110def qdump__lanelet__Area(d, value):111 data = value["constData_"]["_M_ptr"].dereference()112 d.putValue(data["id"].integer())113 d.putNumChild(7)114 if d.isExpanded():115 with Children(d):116 d.putSubItem("id", data["id"])117 d.putSubItem("attributes", data["attributes"])118 d.putSubItem("outerBound", data["outerBound_"])119 d.putSubItem("innerBounds", data["innerBounds_"])120 d.putSubItem("regulatoryElements", data["regulatoryElements_"])121 d.putSubItem("outerBoundPolygon", data["outerBoundPolygon_"])122 d.putSubItem("innerBoundPolygons", data["innerBoundPolygons_"])123def qdump__lanelet__ConstArea(d, value):124 qdump__lanelet__Area(d, value)125def qdump__lanelet__CompoundPolygon3d(d, value):126 data = value["data_"]["_M_ptr"].dereference()127 d.putItemCount(vectorSize(data['ls_']))128 if d.isExpanded():129 with Children(d):130 d.putSubItem("data", data)131def qdump__lanelet__HybridMap(d, value):132 d.putItemCount(mapSize(value['m_']))133 d.putNumChild(2)134 if d.isExpanded():135 with Children(d):136 d.putSubItem("map", value["m_"])137 d.putSubItem("vector", value["v_"])138def qdump__lanelet__Attribute(d, value):139 displayStringValue(d, value["value_"])140 d.putNumChild(2)141 if d.isExpanded():142 with Children(d):143 d.putSubItem("cache_", value["cache_"])144 d.putSubItem("value_", value["value_"])145def qdump__lanelet__RegulatoryElement(d, value):146 data = value["constData_"]["_M_ptr"].dereference()147 d.putValue(data["id"].integer())148 d.putNumChild(3)149 if d.isExpanded():150 with Children(d):151 d.putSubItem("id", data["id"])152 d.putSubItem("attributes", data["attributes"])153 d.putSubItem("parameters", data["parameters"])154def qdump__lanelet__PrimitiveLayer(d, value):155 umap = value["elements_"]156 d.putItemCount(unorderedMapSize(umap))157 d.putNumChild(2)158 if d.isExpanded():159 with Children(d):160 d.putSubItem("elements", umap)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 'headers': {4 },5 body: JSON.stringify({6 {7 {8 "is": {9 }10 }11 }12 })13};14request(options, function (error, response) {15 if (error) throw new Error(error);16 console.log(response.body);17});18var request = require('request');19var options = {20 'headers': {21 }22};23request(options, function (error, response) {24 if (error) throw new Error(error);25 console.log(response.body);26});27{28 {29 {30 "is": {31 }32 }33 }34}

Full Screen

Using AI Code Generation

copy

Full Screen

1var http = require('http');2var options = {3 headers: {'Content-Type': 'application/json'}4};5var req = http.request(options, function(res) {6 console.log('STATUS: ' + res.statusCode);7 console.log('HEADERS: ' + JSON.stringify(res.headers));8 res.setEncoding('utf8');9 res.on('data', function (chunk) {10 console.log('BODY: ' + chunk);11 });12});13req.write(JSON.stringify({14 {15 {16 "equals": {17 }18 }19 {20 "is": {21 }22 }23 }24}));25req.end();26{27 {28 }29}30var http = require('http');31var options = {32 headers: {'Content-Type': 'application/json'}33};34var req = http.request(options, function(res) {35 console.log('STATUS: ' + res.statusCode);36 console.log('HEADERS: ' + JSON.stringify(res.headers));37 res.setEncoding('utf8');38 res.on('data', function (chunk) {39 console.log('BODY: ' + chunk);40 });41});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 headers: {4 },5 json: {6 "stubs": [{7 "responses": [{8 "is": {9 "headers": {10 },11 "body": {12 }13 }14 }]15 }]16 }17};18request(options, function(error, response, body) {19 if (!error && response.statusCode == 201) {20 console.log(body);21 }22});23var request = require('request');24var options = {25};26request(options, function(error, response, body) {27 if (!error && response.statusCode == 200) {28 console.log(body);29 }30});31var request = require('request');32var options = {33};34request(options, function(error, response, body) {35 if (!error && response.statusCode == 200) {36 console.log(body);37 }38});39var request = require('request');40var options = {41 headers: {42 },43 json: {44 "stubs": [{45 "responses": [{46 "is": {47 "headers": {48 },49 "body": {50 }51 }52 }]53 }]54 }55};56request(options, function(error, response, body) {57 if (!error && response.statusCode == 201) {58 console.log(body);59 }60});

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request');2const options = {3 headers: {4 },5 json: {6 {7 {8 "is": {9 "headers": {10 },11 "body": {12 }13 }14 }15 }16 }17};18request(options, function (error, response, body) {19 console.log('error:', error);20 console.log('statusCode:', response && response.statusCode);21 console.log('body:', body);22});23const request = require('request');24const options = {25 headers: {26 },27 json: {28 }29};30request(options, function (error, response, body) {31 console.log('error:', error);32 console.log('statusCode:', response && response.statusCode);33 console.log('body:', body);34});35const request = require('request');36const options = {37 headers: {38 }39};40request(options, function (error, response, body) {41 console.log('error:', error);42 console.log('statusCode:', response && response.statusCode);43 console.log('body:', body);44});45const request = require('request');46const options = {47 headers: {48 }49};50request(options, function (error, response, body) {51 console.log('error:', error);52 console.log('statusCode:', response && response

Full Screen

Using AI Code Generation

copy

Full Screen

1const request = require('request');2const options = {3 json: {4 {5 {6 is: {7 headers: { 'Content-Type': 'text/html' },8 }9 }10 }11 }12};13request(options, (error, response, body) => {14 if (!error && response.statusCode == 201) {15 console.log(body);16 }17});18const options = {19 json: {20 {21 {22 is: {23 headers: { 'Content-Type': 'text/html' },24 }25 }26 }27 }28};29request(options, (error, response, body) => {30 if (!error && response.statusCode == 201) {31 console.log(body);32 }33});34const options = {35};36request(options, (error, response, body) => {37 if (!error && response.statusCode == 200) {38 console.log(body);39 }40});41const options = {42};43request(options, (error, response, body) => {44 if (!error && response.statusCode == 200) {45 console.log(body);46 }47});48const options = {49};50request(options, (error, response, body) => {51 if (!error && response.statusCode == 200) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 "headers": {8 },9 }10 }11 }12 }13};14request(options, function (error, response, body) {15 if (!error && response.statusCode == 200) {16 console.log(body)17 }18});19var request = require('request');20var options = {21 json: {22 {23 {24 "is": {25 "headers": {26 },27 }28 }29 }30 }31};32request(options, function (error, response, body) {33 if (!error && response.statusCode == 200) {34 console.log(body)35 }36});37var request = require('request');38var options = {39};40request(options, function (error, response, body) {41 if (!error && response.statusCode == 200) {42 console.log(body)43 }44});45var request = require('request');46var options = {47};48request(options, function (error, response, body) {49 if (!error && response.statusCode == 200) {50 console.log(body)51 }52});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = {3 {4 {5 is: { body: 'Hello World!' }6 }7 }8};9mb.create(imposter).then(function (server) {10 console.log('Server running at %s', server.url);11 return server.get('/').then(function (response) {12 console.log('Response for GET: %s', response.body);13 return server.put('/', { body: 'Hello World!' }).then(function (response) {14 console.log('Response for PUT: %s', response.body);15 return server.del('/').then(function (response) {16 console.log('Response for DELETE: %s', response.body);17 return server.stop();18 });19 });20 });21});22var mb = require('mountebank');23var imposter = {24 {25 {26 is: { body: 'Hello World!' }27 }28 }29};30mb.create(imposter).then(function (server) {31 console.log('Server running at %s', server.url);32 return server.get('/').then(function (response) {33 console.log('Response for GET: %s', response.body);34 return server.put('/', { body: 'Hello World!' }).then(function (response) {35 console.log('Response for PUT: %s', response.body);36 return server.del('/').then(function (response) {37 console.log('Response for DELETE: %s', response.body);38 return server.stop();39 });40 });41 });42});43var mb = require('mountebank');44var imposter = {45 {46 {47 is: { body: 'Hello World!' }48 }49 }50};51mb.create(imposter).then(function (server) {52 console.log('Server running at %s', server.url);53 return server.get('/').then(function (response) {54 console.log('Response for

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