Best Python code snippet using playwright-python
gdbmacros.py
Source:gdbmacros.py
...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)...
test_attvars.py
Source:test_attvars.py
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)...
remote_api_put_stub_test.py
Source:remote_api_put_stub_test.py
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__':...
snippets_test.py
Source:snippets_test.py
...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...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!