Best JavaScript code snippet using wpt
test_domlette_interfaces.py
Source:test_domlette_interfaces.py
...3from Ft.Xml import XMLNS_NAMESPACE, Domlette, InputSource4def test_node_access(tester, doc):5 def test_attribute(name, items, mutator=None):6 for title, node, expected in items:7 tester.startTest("%s %s attribute" % (title, name))8 compared = getattr(node, name)9 if mutator is not None:10 compared = mutator(compared)11 tester.compare(expected, compared)12 tester.testDone()13 def test_method(name, items):14 for title, node, expected, args in items:15 tester.startTest("%s %s method" % (title, name))16 compared = getattr(node, name)(*args)17 tester.compare(expected, compared)18 tester.testDone()19 tester.startGroup("Node Access Interfaces")20 CHILD = getChild(doc)21 NS_CHILD = getNsChild(doc)22 TEXT = getFirstText(doc)23 COMMENT = getComment(doc)24 PI = getPi(doc)25 ATTR = getAttr(doc)26 NS_ATTR = getNsAttr(doc)27 test_attribute('childNodes',28 [('Document', doc, 2),29 ('Element', doc.documentElement, 9),30 ('Text', TEXT, 0),31 ('Comment', COMMENT, 0),32 ('PI', PI, 0),33 ], mutator=len)34 test_attribute('nodeName',35 [('Document', doc, '#document'),36 ('Element', CHILD, 'child'),37 ('NsElement', NS_CHILD, 'ft:nschild'),38 ('Text', TEXT, '#text'),39 ('Comment', COMMENT, '#comment'),40 ('PI', PI, 'xml-stylesheet'),41 ('Attr', ATTR, 'foo'),42 ('NsAttr', NS_ATTR, 'ft:foo'),43 ])44 test_attribute('nodeValue',45 [('Document', doc, None),46 ('Element', CHILD, None),47 ('Text', TEXT, 'Some Text'),48 ('Comment', COMMENT, 'A comment'),49 ('PI', PI, 'href="addr_book1.xsl" type="text/xml"'),50 ('Attr', ATTR, 'bar'),51 ])52 test_attribute('parentNode',53 [('Document', doc, None),54 ('Element', CHILD, doc.documentElement),55 ('Text', TEXT, CHILD),56 ('Comment', COMMENT, doc.documentElement),57 ('PI', PI, doc),58 ('Attr', ATTR, CHILD),59 ])60 test_attribute('firstChild',61 [('Document', doc, PI),62 ('Element', CHILD, TEXT),63 ('Text', TEXT, None),64 ('Comment', COMMENT, None),65 ('PI', PI, None),66 ('Attr', ATTR, None),67 ])68 test_attribute('lastChild',69 [('Document', doc, doc.documentElement),70 ('Element', CHILD, TEXT),71 ('Text', TEXT, None),72 ('Comment', COMMENT, None),73 ('PI', PI, None),74 ('Attr', ATTR, None),75 ])76 test_attribute('previousSibling',77 [('Document', doc, None),78 ('Element', CHILD, doc.documentElement.childNodes[0]),79 ('Text', TEXT, None),80 ('Comment', COMMENT, doc.documentElement.childNodes[2]),81 ('PI', PI, None),82 ('Attr', ATTR, None),83 ])84 test_attribute('nextSibling',85 [('Document', doc, None),86 ('Element', CHILD, doc.documentElement.childNodes[2]),87 ('Text', TEXT, None),88 ('Comment', COMMENT, doc.documentElement.childNodes[4]),89 ('PI', PI, doc.documentElement),90 ('Attr', ATTR, None),91 ])92 def mutator(arg):93 if arg is None: return None94 return len(arg)95 test_attribute('attributes',96 [('Document', doc, None),97 ('Element', CHILD, 1),98 ('Text', TEXT, None),99 ('Comment', COMMENT, None),100 ('PI', PI, None),101 ('Attr', ATTR, None),102 ], mutator)103 test_attribute('ownerDocument',104 [('Document', doc, None),105 ('Element', CHILD, doc),106 ('Text', TEXT, doc),107 ('Comment', COMMENT, doc),108 ('PI', PI, doc),109 ('Attr', ATTR, doc),110 ])111 test_attribute('namespaceURI',112 [('Document', doc, None),113 ('Element', CHILD, None),114 ('NsElement', NS_CHILD, 'http://fourthought.com'),115 ('Text', TEXT, None),116 ('Comment', COMMENT, None),117 ('PI', PI, None),118 ('Attr', ATTR, None),119 ('NsAttr', NS_ATTR, 'http://fourthought.com'),120 ])121 test_attribute('prefix',122 [('Document', doc, None),123 ('Element', CHILD, None),124 ('NsElement', NS_CHILD, 'ft'),125 ('Text', TEXT, None),126 ('Comment', COMMENT, None),127 ('PI', PI, None),128 ('Attr', ATTR, None),129 ('NsAttr', NS_ATTR, 'ft'),130 ])131 test_attribute('localName',132 [('Document', doc, None),133 ('Element', CHILD, 'child'),134 ('NsElement', NS_CHILD, 'nschild'),135 ('Text', TEXT, None),136 ('Comment', COMMENT, None),137 ('PI', PI, None),138 ('Attr', ATTR, 'foo'),139 ('NsAttr', NS_ATTR, 'foo'),140 ])141 test_attribute('nodeType',142 [('Document', doc, Node.DOCUMENT_NODE),143 ('Element', CHILD, Node.ELEMENT_NODE),144 ('Text', TEXT, Node.TEXT_NODE),145 ('Comment', COMMENT, Node.COMMENT_NODE),146 ('PI', PI, Node.PROCESSING_INSTRUCTION_NODE),147 ('Attr', ATTR, Node.ATTRIBUTE_NODE),148 ])149 test_method('hasChildNodes',150 [('Document', doc, True, ()),151 ('Element', CHILD, True, ()),152 ('Text', TEXT, False, ()),153 ('Comment', COMMENT, False, ()),154 ('PI', PI, False, ()),155 ('Attr', ATTR, False, ()),156 ])157 test_method('isSameNode',158 [('Document', doc, True, (doc,)),159 ('Document', doc, False, (doc.documentElement,)),160 ('Element', CHILD, True, (CHILD,)),161 ('Element', CHILD, False, (NS_CHILD,)),162 ('Text', TEXT, True, (TEXT,)),163 ('Text', TEXT, False, (doc.documentElement,)),164 ('Comment', COMMENT, True, (COMMENT,)),165 ('Comment', COMMENT, False, (doc.documentElement,)),166 ('PI', PI, True, (PI,)),167 ('PI', PI, False, (doc.documentElement,)),168 ('Attr', ATTR, True, (ATTR,)),169 ('Attr', ATTR, False, (NS_ATTR,)),170 ])171 tester.groupDone()172 return173def test_document_access(tester,dom):174 tester.startGroup("Document Access Interfaces")175 tester.startTest("DocType")176 tester.compare(None,dom.doctype)177 tester.testDone()178 tester.startTest("documentElement")179 tester.compare(dom.childNodes[1],dom.documentElement)180 tester.testDone()181 tester.startTest("implementation")182 tester.compare(True, hasattr(dom.implementation,'hasFeature'))183 tester.testDone()184 tester.groupDone()185def test_element_access(tester,dom):186 tester.startGroup("Element Access Interfaces")187 tester.startTest("attributes")188 tester.compare(1,len(getChild(dom).attributes.keys()))189 tester.testDone()190 tester.startTest("tagname")191 tester.compare('child',getChild(dom).tagName)192 tester.compare('ft:nschild',getNsChild(dom).tagName)193 tester.testDone()194 tester.startTest("getAttributeNodeNS")195 tester.compare(None,getChild(dom).getAttributeNodeNS(None,u'foo2'))196 tester.compare(getAttr(dom),getChild(dom).getAttributeNodeNS(None,u'foo'))197 tester.compare(getNsAttr(dom),getNsChild(dom).getAttributeNodeNS('http://fourthought.com','foo'))198 tester.compare(None,getNsChild(dom).getAttributeNodeNS('http://fourthought.com','foo2'))199 tester.testDone()200 tester.startTest("getAttributeNS")201 tester.compare('bar',getChild(dom).getAttributeNS(None,'foo'))202 tester.compare('',getChild(dom).getAttributeNS(None,'foo2'))203 tester.compare('nsbar',getNsChild(dom).getAttributeNS('http://fourthought.com','foo'))204 tester.compare('',getNsChild(dom).getAttributeNS('http://fourthought.com','foo2'))205 tester.testDone()206 tester.startTest("hasAttributeNS")207 tester.compare(1,getChild(dom).hasAttributeNS(None,'foo'))208 tester.compare(0,getChild(dom).hasAttributeNS(None,'foo2'))209 tester.compare(1,getNsChild(dom).hasAttributeNS('http://fourthought.com','foo'))210 tester.compare(0,getNsChild(dom).hasAttributeNS('http://fourthought.com','foo2'))211 tester.testDone()212 tester.groupDone()213def test_attr_access(tester,dom):214 tester.startGroup("Attribute Access Interfaces")215 tester.startTest("name attribute")216 tester.compare('foo',getAttr(dom).name)217 tester.compare('ft:foo',getNsAttr(dom).name)218 tester.testDone()219 tester.startTest("value attribute")220 tester.compare('bar',getAttr(dom).value)221 tester.compare('nsbar',getNsAttr(dom).value)222 tester.testDone()223 tester.startTest("specified attribute")224 tester.compare(1,getAttr(dom).specified)225 tester.testDone()226 tester.startTest("ownerElement attribute")227 tester.compare(getChild(dom),getAttr(dom).ownerElement)228 tester.compare(getNsChild(dom),getNsAttr(dom).ownerElement)229 tester.testDone()230 tester.groupDone()231def test_text_access(tester,dom):232 tester.startGroup("Text Access Interfaces")233 tester.startTest("data attribute")234 tester.compare('Some Text',getFirstText(dom).data)235 tester.testDone()236 tester.startTest("substringData method")237 tester.compare('Some',getFirstText(dom).substringData(0,4))238 tester.testDone()239 tester.groupDone()240def test_pi_access(tester,dom):241 tester.startGroup("Processing Instruction Access Interfaces")242 tester.startTest("target attribute")243 tester.compare('xml-stylesheet',getPi(dom).target)244 tester.testDone()245 tester.startTest("data attribute")246 tester.compare('href="addr_book1.xsl" type="text/xml"',getPi(dom).data)247 tester.testDone()248 tester.groupDone()249def test_comment_access(tester,dom):250 tester.startGroup("Comment Access Interfaces")251 tester.startTest("data attribute")252 tester.compare('A comment',getComment(dom).data)253 tester.testDone()254 tester.groupDone()255def test_imp_creation(tester,dom):256 tester.startTest('createDocument (empty)')257 doc = dom.implementation.createDocument(None,None,None)258 tester.compare(Node.DOCUMENT_NODE,doc.nodeType)259 tester.compare(None, doc.doctype)260 tester.compare(None, doc.documentElement)261 tester.compare(0, doc.hasChildNodes())262 tester.testDone()263 tester.startTest('createDocument (element only)')264 doc = dom.implementation.createDocument('http://foo.com', 'foo:bar', None)265 tester.compare(Node.DOCUMENT_NODE,doc.nodeType)266 tester.compare(None, doc.doctype)267 tester.compare(1, doc.hasChildNodes())268 tester.compare(1, len(doc.childNodes))269 tester.compare(doc.documentElement, doc.childNodes[0])270 tester.compare(Node.ELEMENT_NODE, doc.childNodes[0].nodeType)271 tester.compare('http://foo.com', doc.childNodes[0].namespaceURI)272 tester.compare('foo', doc.childNodes[0].prefix)273 tester.compare('bar', doc.childNodes[0].localName)274 tester.testDone()275 return276def test_document_creation(tester,dom):277 tester.startGroup("Document Creation Interfaces")278 tester.startTest('createElementNS')279 elem = dom.createElementNS('http://foo.com','foo:bar')280 tester.compare(Node.ELEMENT_NODE,elem.nodeType)281 tester.compare('http://foo.com',elem.namespaceURI)282 tester.compare('foo',elem.prefix)283 tester.compare('bar',elem.localName)284 tester.compare('foo:bar',elem.nodeName)285 tester.compare(dom,elem.ownerDocument)286 tester.testDone()287 tester.startTest('createElementNS exceptions')288 tester.testException(dom.createElementNS, (None, 'foo:bar'), NamespaceErr)289 tester.testDone()290 tester.startTest('createAttributeNs')291 attr = dom.createAttributeNS('http://foo.com','foo:bar')292 tester.compare(Node.ATTRIBUTE_NODE,attr.nodeType)293 tester.compare('http://foo.com',attr.namespaceURI)294 tester.compare('foo',attr.prefix)295 tester.compare('bar',attr.localName)296 tester.compare('foo:bar',attr.nodeName)297 tester.compare(dom,attr.ownerDocument)298 tester.testDone()299 tester.startTest('createAttributeNS exceptions')300 tester.testException(dom.createAttributeNS, (None, 'foo:bar'),301 NamespaceErr)302 tester.testDone()303 tester.startTest('createTextNode')304 text = dom.createTextNode('data')305 tester.compare(Node.TEXT_NODE,text.nodeType)306 tester.compare('data',text.data)307 tester.compare(dom,text.ownerDocument)308 tester.testDone()309 tester.startTest('createProcessingInstruction')310 pi = dom.createProcessingInstruction('target','data')311 tester.compare(Node.PROCESSING_INSTRUCTION_NODE,pi.nodeType)312 tester.compare('target',pi.target)313 tester.compare('data',pi.data)314 tester.compare(dom,pi.ownerDocument)315 tester.testDone()316 tester.startTest('createComment')317 com = dom.createComment('data')318 tester.compare(Node.COMMENT_NODE,com.nodeType)319 tester.compare('data',com.data)320 tester.compare(dom,com.ownerDocument)321 tester.testDone()322## tester.startTest('createDocumentFragment')323## df = dom.createDocumentFragment()324## tester.compare(Node.DOCUMENT_FRAGMENT_NODE,df.nodeType)325## tester.compare(dom,df.ownerDocument)326## tester.testDone()327 tester.groupDone()328def test_append_child(tester,dom):329 tester.startTest("Append Simple Child")330 elem = dom.createTextNode('data')331 child = getAppendChild(dom)332 child.appendChild(elem)333 tester.compare(1,len(child.childNodes))334 tester.compare(Node.TEXT_NODE,child.childNodes[0].nodeType)335 tester.compare('data',child.childNodes[0].data)336 tester.compare(child,elem.parentNode)337 tester.compare(elem,child.firstChild)338 tester.compare(elem,child.lastChild)339 tester.compare(None,elem.previousSibling)340 tester.compare(None,elem.nextSibling)341 tester.testDone()342 tester.startTest("Append Second Child")343 elem2 = dom.createTextNode('data2')344 child.appendChild(elem2)345 tester.compare(2,len(child.childNodes))346 tester.compare(Node.TEXT_NODE,child.childNodes[1].nodeType)347 tester.compare('data2',child.childNodes[1].data)348 tester.compare(child,elem2.parentNode)349 tester.compare(elem,child.firstChild)350 tester.compare(elem2,child.lastChild)351 tester.compare(None,elem.previousSibling)352 tester.compare(elem2,elem.nextSibling)353 tester.compare(elem,elem2.previousSibling)354 tester.compare(None,elem2.nextSibling)355 tester.testDone()356## tester.startTest("Append DF")357## df = dom.createDocumentFragment()358## elem3 = dom.createTextNode('data3')359## elem4 = dom.createTextNode('data4')360## df.appendChild(elem3)361## df.appendChild(elem4)362## child.appendChild(df)363## tester.compare(4,len(child.childNodes))364## tester.compare(elem4,child.lastChild)365## tester.compare(elem2,elem3.previousSibling)366## tester.compare(elem4,elem3.nextSibling)367## tester.compare(elem3,elem4.previousSibling)368## tester.compare(None,elem4.nextSibling)369## tester.compare(child,elem3.parentNode)370## tester.compare(child,elem4.parentNode)371## tester.testDone()372## tester.startTest("Append DF to empty")373## root = dom.createElementNS(None,'foo')374## df = dom.createDocumentFragment()375## elem5 = dom.createTextNode('data5')376## elem6 = dom.createTextNode('data6')377## df.appendChild(elem5)378## df.appendChild(elem6)379## root.appendChild(df)380## tester.compare(2,len(root.childNodes))381## tester.compare(elem5,root.firstChild)382## tester.compare(elem6,root.lastChild)383## tester.compare(None,elem5.previousSibling)384## tester.compare(elem6,elem5.nextSibling)385## tester.compare(elem5,elem6.previousSibling)386## tester.compare(None,elem6.nextSibling)387## tester.compare(root,elem5.parentNode)388## tester.compare(root,elem6.parentNode)389## tester.testDone()390 tester.startTest("Append New Element to a new document")391 newdoc = dom.implementation.createDocument(None,None,None)392 elem10 = newdoc.createElementNS(None,'foo')393 newdoc.appendChild(elem10)394 tester.compare(elem10,newdoc.documentElement)395 tester.testDone()396def test_normalize(tester, dom):397 tester.startGroup("Normalize")398 tester.startTest("Normalize All Text Nodes")399 child = getAppendChild(dom)400 child.normalize()401 tester.compare(1,len(child.childNodes))402 tester.compare("datadata2",child.childNodes[0].data)403 tester.testDone()404 tester.startTest("Normalize Mixed Text Nodes")405 child = getAppendChild(dom)406 sub1 = dom.createElementNS(None,'one')407 sub2 = dom.createElementNS(None,'two')408 t1 = dom.createTextNode('o')409 t2 = dom.createTextNode('t')410 t3 = dom.createTextNode('g')411 t4 = dom.createTextNode('h')412 child.appendChild(t1)413 child.appendChild(sub1)414 child.appendChild(t2)415 child.appendChild(t3)416 child.appendChild(sub2)417 child.appendChild(t4)418 child.normalize()419 tester.compare(5,len(child.childNodes))420 tester.compare("datadata2o",child.childNodes[0].data)421 tester.compare("tg",child.childNodes[2].data)422 tester.compare("h",child.childNodes[4].data)423 tester.testDone()424 tester.groupDone()425def test_insert_before(tester,dom):426 tester.startTest("Empty Insert")427 elem = dom.createTextNode('data')428 child = dom.createElementNS(None,'insertTest')429 child.insertBefore(elem,None)430 tester.compare(1,len(child.childNodes))431 tester.compare(child,elem.parentNode)432 tester.compare(Node.TEXT_NODE,child.childNodes[0].nodeType)433 tester.compare('data',child.childNodes[0].data)434 tester.compare(child,elem.parentNode)435 tester.compare(elem,child.firstChild)436 tester.compare(elem,child.lastChild)437 tester.compare(None,elem.previousSibling)438 tester.compare(None,elem.nextSibling)439 tester.testDone()440 tester.startTest("Second Insert")441 elem2 = dom.createTextNode('data2')442 child.insertBefore(elem2,elem)443 tester.compare(2,len(child.childNodes))444 tester.compare(child,elem2.parentNode)445 tester.compare(Node.TEXT_NODE,child.childNodes[0].nodeType)446 tester.compare('data2',child.childNodes[0].data)447 tester.compare(child,elem2.parentNode)448 tester.compare(elem2,child.firstChild)449 tester.compare(elem,child.lastChild)450 tester.compare(elem2,elem.previousSibling)451 tester.compare(None,elem.nextSibling)452 tester.compare(None,elem2.previousSibling)453 tester.compare(elem,elem2.nextSibling)454 tester.testDone()455## tester.startTest("DF Insert")456## df = dom.createDocumentFragment()457## elem3 = dom.createTextNode('data3')458## elem4 = dom.createTextNode('data4')459## df.appendChild(elem3)460## df.appendChild(elem4)461## child.insertBefore(df,elem)462## tester.compare(4,len(child.childNodes))463## tester.compare(child,elem3.parentNode)464## tester.compare(child,elem4.parentNode)465## tester.compare(elem2,child.firstChild)466## tester.compare(elem,child.lastChild)467## tester.compare(None,elem2.previousSibling)468## tester.compare(elem3,elem2.nextSibling)469## tester.compare(elem2,elem3.previousSibling)470## tester.compare(elem4,elem3.nextSibling)471## tester.compare(elem3,elem4.previousSibling)472## tester.compare(elem,elem4.nextSibling)473## tester.compare(elem4,elem.previousSibling)474## tester.compare(None,elem.nextSibling)475## tester.testDone()476## tester.startTest("DF Insert on empty")477## root = dom.createElementNS(None,'foo')478## df = dom.createDocumentFragment()479## elem5 = dom.createTextNode('data5')480## elem6 = dom.createTextNode('data6')481## df.appendChild(elem5)482## df.appendChild(elem6)483## root.insertBefore(df,None)484## tester.compare(2,len(root.childNodes))485## tester.compare(elem5,root.firstChild)486## tester.compare(elem6,root.lastChild)487## tester.compare(None,elem5.previousSibling)488## tester.compare(elem6,elem5.nextSibling)489## tester.compare(elem5,elem6.previousSibling)490## tester.compare(None,elem6.nextSibling)491## tester.compare(root,elem5.parentNode)492## tester.compare(root,elem6.parentNode)493## tester.testDone()494 tester.startTest("Insert on empty doc")495 newdoc = dom.implementation.createDocument(None,None,None)496 com = newdoc.createComment('foo')497 elem10 = newdoc.createElementNS(None,'foo')498 newdoc.appendChild(com)499 newdoc.insertBefore(elem10,com)500 tester.compare(elem10,newdoc.documentElement)501 tester.testDone()502def test_replace_child(tester,dom):503 tester.startTest("Simple Replace")504 root = dom.createElementNS(None,'root')505 elem = dom.createElementNS(None,'elem')506 elem2 = dom.createElementNS(None,'elem2')507 root.appendChild(elem)508 root.replaceChild(elem2,elem)509 tester.compare(1,len(root.childNodes))510 tester.compare(elem2,root.firstChild)511 tester.compare(elem2,root.lastChild)512 tester.compare(None,elem.parentNode)513 tester.compare(None,elem2.nextSibling)514 tester.compare(None,elem2.previousSibling)515 tester.compare(None,elem.nextSibling)516 tester.compare(None,elem.previousSibling)517 tester.testDone()518 tester.startTest("Replace on doc")519 newdoc = dom.implementation.createDocument(None,None,None)520 com = newdoc.createComment('foo')521 elem10 = newdoc.createElementNS(None,'foo')522 newdoc.appendChild(com)523 newdoc.replaceChild(elem10,com)524 tester.compare(elem10,newdoc.documentElement)525 tester.testDone()526def test_remove_child(tester,dom):527 tester.startTest("Simple Remove")528 root = dom.createElementNS(None,'root')529 elem = dom.createElementNS(None,'elem')530 root.appendChild(elem)531 root.removeChild(elem)532 tester.compare(0,len(root.childNodes))533 tester.compare(None,root.firstChild)534 tester.compare(None,root.lastChild)535 tester.compare(None,elem.parentNode)536 tester.compare(None,elem.previousSibling)537 tester.compare(None,elem.nextSibling)538 tester.testDone()539 tester.startTest("Remove on doc")540 newdoc = dom.implementation.createDocument(None,None,None)541 elem10 = newdoc.createElementNS(None,'foo')542 newdoc.appendChild(elem10)543 newdoc.removeChild(elem10)544 tester.compare(None,newdoc.documentElement)545 tester.testDone()546def test_node_modification(tester,dom):547 tester.startGroup("Node Modiciation Interfaces")548 test_append_child(tester,dom)549 test_normalize(tester,dom)550 test_insert_before(tester,dom)551 test_replace_child(tester,dom)552 test_remove_child(tester,dom)553 tester.groupDone()554def test_element_modification(tester,dom):555 tester.startGroup("Element Modiciation Interfaces")556 tester.startTest("setAttributeNS non-NS attr")557 root = dom.createElementNS(None,'foo')558 root.setAttributeNS(None,'foo','bar')559 tester.compare(True, root.hasAttributeNS(None,'foo'))560 attr = root.getAttributeNodeNS(None,'foo')561 tester.compare(None, attr.namespaceURI)562 tester.compare(None, attr.prefix)563 tester.compare('foo', attr.localName)564 tester.compare('foo', attr.nodeName)565 tester.compare('foo', attr.name)566 tester.compare('bar', attr.nodeValue)567 tester.compare('bar', attr.value)568 tester.testDone()569 tester.startTest("setAttributeNS NS attr")570 root.setAttributeNS('http://fourthought.com','ft:foo','bar')571 tester.compare(True, root.hasAttributeNS('http://fourthought.com','foo'))572 attr = root.getAttributeNodeNS('http://fourthought.com','foo')573 tester.compare('http://fourthought.com',attr.namespaceURI)574 tester.compare('ft',attr.prefix)575 tester.compare('foo',attr.localName)576 tester.compare('ft:foo',attr.nodeName)577 tester.compare('ft:foo',attr.name)578 tester.compare('bar',attr.nodeValue)579 tester.compare('bar',attr.value)580 tester.testDone()581 tester.startTest("setAttributeNodeNS NS attr")582 attr = dom.createAttributeNS('http://fourthought.com','ft:foo2')583 attr.value = 'bar'584 root.setAttributeNodeNS(attr)585 tester.compare(True, root.hasAttributeNS('http://fourthought.com','foo2'))586 attr = root.getAttributeNodeNS('http://fourthought.com','foo2')587 tester.compare('http://fourthought.com',attr.namespaceURI)588 tester.compare('ft',attr.prefix)589 tester.compare('foo2',attr.localName)590 tester.compare('ft:foo2',attr.nodeName)591 tester.compare('ft:foo2',attr.name)592 tester.compare('bar',attr.nodeValue)593 tester.compare('bar',attr.value)594 tester.testDone()595 tester.startTest("setAttributeNodeNS non-NS attr")596 attr = dom.createAttributeNS(None,'foo2')597 attr.value = 'bar'598 root.setAttributeNodeNS(attr)599 tester.compare(True, root.hasAttributeNS(None,'foo2'))600 attr = root.getAttributeNodeNS(None,'foo2')601 tester.compare(None,attr.namespaceURI)602 tester.compare(None, attr.prefix)603 tester.compare('foo2',attr.localName)604 tester.compare('foo2',attr.nodeName)605 tester.compare('foo2',attr.name)606 tester.compare('bar',attr.nodeValue)607 tester.compare('bar',attr.value)608 tester.testDone()609 tester.startTest("removeAttributeNode NS attr")610 root.setAttributeNS('http://fourthought.com', 'ft:foo2', 'bar')611 attr = root.getAttributeNodeNS('http://fourthought.com','foo2')612 root.removeAttributeNode(attr)613 tester.compare(False, root.hasAttributeNS('http://fourthought.com','foo2'))614 tester.testDone()615 tester.startTest("removeAttributeNode non-NS attr")616 root.setAttributeNS(None, 'foo2', 'bar')617 attr = root.getAttributeNodeNS(None,'foo2')618 root.removeAttributeNode(attr)619 tester.compare(False, root.hasAttributeNS(None,'foo2'))620 tester.testDone()621 tester.startTest("removeAttributeNS NS attr")622 root.removeAttributeNS('http://fourthought.com','foo')623 tester.compare(False, root.hasAttributeNS('http://fourthought.com','foo'))624 tester.testDone()625 tester.startTest("removeAttributeNS non-NS attr")626 root.removeAttributeNS(None,'foo')627 tester.compare(False, root.hasAttributeNS(None,'foo'))628 tester.testDone()629 tester.groupDone()630def test_text_modification(tester,dom):631 tester.startGroup("Text Modification")632 tester.startTest("set value")633 text = dom.createTextNode('data')634 text.data = 'new data'635 tester.compare('new data',text.data)636 tester.compare('new data',text.nodeValue)637 tester.testDone()638 tester.startTest("insertData")639 text.insertData(3,'f')640 tester.compare('newf data',text.data)641 tester.testDone()642 tester.startTest('appendData')643 text.appendData('g')644 tester.compare('newf datag',text.data)645 tester.testDone()646 tester.startTest('deleteData')647 text.deleteData(1,3)648 tester.compare('n datag',text.data)649 tester.testDone()650 tester.startTest('substringData')651 d = text.substringData(1,3)652 tester.compare(' da',d)653 tester.testDone()654 tester.groupDone()655def test_comment_modification(tester,dom):656 tester.startGroup("Comment Modification")657 tester.startTest("set value")658 comment = dom.createComment('data')659 comment.data = 'new data'660 tester.compare('new data',comment.data)661 tester.compare('new data',comment.nodeValue)662 tester.testDone()663 tester.startTest("insertData")664 comment.insertData(3,'f')665 tester.compare('newf data',comment.data)666 tester.testDone()667 tester.startTest('appendData')668 comment.appendData('g')669 tester.compare('newf datag',comment.data)670 tester.testDone()671 tester.startTest('deleteData')672 comment.deleteData(1,3)673 tester.compare('n datag',comment.data)674 tester.testDone()675 tester.startTest('substringData')676 d = comment.substringData(1,3)677 tester.compare(' da',d)678 tester.testDone()679 tester.groupDone()680def test_processing_instruction_modification(tester,dom):681 tester.startGroup("Processing Instruction Modification")682 pi = dom.createProcessingInstruction('target','data')683 tester.startTest("set data")684 pi.data = 'new data'685 tester.compare('new data',pi.data)686 tester.compare('new data',pi.nodeValue)687 tester.testDone()688 tester.groupDone()689def test_interface(tester,domMod):690 tester.startGroup("Dom Module Interface")691 tester.startTest("TestTree")692 tester.compare(True, hasattr(domMod,'TestTree'))693 dom = domMod.TestTree()694 tester.compare('docelem',dom.documentElement.nodeName)695 tester.testDone()696 tester.startTest("ValParse")697 tester.compare(True, hasattr(domMod,'ValParse'))698 tester.testDone()699 tester.startTest("NonvalParse")700 tester.compare(True, hasattr(domMod,'NonvalParse'))701 tester.testDone()702 tester.groupDone()703 return704def test_access(tester,domMod):705 tester.startGroup("Access Interfaces")706 dom = domMod.TestTree()707 test_node_access(tester,dom)708 test_document_access(tester,dom)709 test_element_access(tester,dom)710 test_attr_access(tester,dom)711 test_text_access(tester,dom)712 test_pi_access(tester,dom)713 test_comment_access(tester,dom)714 tester.groupDone()715 return716def test_reader_access(tester,domMod,doc):717 tester.startGroup("Access Interfaces after parsing")718 isrc = InputSource.DefaultFactory.fromString(doc,'reader')719 dom = domMod.NonvalParse(isrc)720 test_node_access(tester, dom)721 test_document_access(tester, dom)722 test_element_access(tester, dom)723 test_attr_access(tester, dom)724 test_text_access(tester, dom)725 test_pi_access(tester, dom)726 test_comment_access(tester, dom)727 tester.groupDone()728 return729def test_clone_node(tester,domMod):730 tester.startGroup("cloneNode")731 dom = domMod.TestTree()732 tester.startTest("shallow")733 newNode = dom.documentElement.cloneNode(0)734 tester.compare('docelem',newNode.nodeName)735 tester.compare(None,newNode.namespaceURI)736 tester.compare('docelem',newNode.localName)737 tester.compare(0,len(newNode.childNodes))738 tester.compare(1,len(newNode.attributes))739 tester.compare(True, newNode.attributes.has_key((XMLNS_NAMESPACE, 'ft')))740 tester.compare('http://fourthought.com',newNode.attributes[(XMLNS_NAMESPACE, 'ft')].value)741 tester.testDone()742 tester.startTest("deep")743 newNode = getChild(dom).cloneNode(1)744 tester.compare('child',newNode.nodeName)745 tester.compare(None,newNode.namespaceURI)746 tester.compare('child',newNode.localName)747 tester.compare(1,len(newNode.childNodes))748 tester.compare(True, hasattr(newNode.childNodes[0],'data'))749 tester.compare('Some Text',newNode.childNodes[0].data)750 tester.compare(1,len(newNode.attributes))751 tester.compare(True, newNode.attributes.has_key((None, 'foo')))752 tester.compare('bar',newNode.attributes[(None, 'foo')].value)753 tester.testDone()754 tester.groupDone()755 return756def test_import_node(tester,domMod):757 tester.startTest("importNode deep")758 dom = domMod.TestTree()759 doc = Domlette.implementation.createDocument(None,None,None)760 root = doc.createElementNS("http://foo.com","foo:import-root")761 root.setAttributeNS(None,"ID","15")762 text = doc.createTextNode("Imported Text")763 root.appendChild(text)764 newRoot = dom.importNode(root,1)765 tester.compare(dom,newRoot.ownerDocument)766 tester.compare(dom,newRoot.childNodes[0].ownerDocument)767 tester.testDone()768 return769def test_mutate(tester,domMod):770 tester.startGroup("Mutation Interfaces")771 dom = domMod.TestTree()...
test_time.py
Source:test_time.py
...13 return time.strftime('%Y-%m-%dT%H:%M:%S' + offset_str, loc_tuple)14def test_instance(tester):15 tester.startGroup("Test DateTime Instance")16 tester.startGroup("Test Seconds")17 tester.startTest('10s + 5ms')18 d = Time.DT(0,0,0,0,0,10,5,0,"",0,0)19 tester.compare(10,d.second())20 tester.compare(5,d.milliSecond())21 tester.testDone()22 tester.startTest('10s + 5001ms')23 d = Time.DT(0,0,0,0,0,10,5001,0,"",0,0)24 tester.compare(15,d.second())25 tester.compare(1,d.milliSecond())26 tester.testDone()27 tester.groupDone()28 tester.startGroup("Test Minutes")29 tester.startTest("1m 0s")30 d = Time.DT(0,0,0,0,1,0,0,0,"",0,0)31 tester.compare(1,d.minute())32 tester.compare(1,d.minute(local=1))33 tester.testDone()34 tester.startTest("1m 0s, offset 20m")35 d = Time.DT(0,0,0,0,1,0,0,0,"",0,20)36 tester.compare(1,d.minute())37 tester.compare(21,d.minute(local=1))38 tester.testDone()39 tester.startTest("1m 65s, offset 20m")40 d = Time.DT(0,0,0,0,1,65,0,0,"",0,20)41 tester.compare(2,d.minute())42 tester.compare(22,d.minute(local=1))43 tester.compare(5,d.second())44 tester.testDone()45 tester.groupDone()46 tester.startGroup("Test Hour")47 tester.startTest("1h 0m")48 d = Time.DT(0,0,0,1,0,0,0,0,"",0,0)49 tester.compare(1,d.hour())50 tester.compare(1,d.hour(local=1))51 tester.testDone()52 tester.startTest("1h 0m, offset -2h")53 d = Time.DT(0,0,0,1,0,0,0,0,"",-2,0)54 tester.compare(1,d.hour())55 tester.compare(23,d.hour(local=1))56 tester.testDone()57 tester.startTest("10h 125m, offset -15h 65m")58 d = Time.DT(0,0,0,10,125,0,0,0,"",-15,65)59 tester.compare(12,d.hour())60 tester.compare(22,d.hour(local=1))61 tester.compare(5,d.minute())62 tester.compare(10,d.minute(local=1))63 tester.testDone()64 tester.groupDone()65 tester.startGroup("Time Zones")66 tester.startTest("0h 0m, offset -6h, summer")67 d = Time.DT(0,0,0,0,0,0,0,1,"",-6,0)68 tester.compare("MDT",d.tzName())69 tester.compare(-6,d.tzHourOffset())70 tester.compare(0,d.tzMinuteOffset())71 tester.compare(18,d.hour(local=1))72 tester.compare(0,d.hour())73 tester.testDone()74 tester.startTest("0h 0m, offset -6h, winter")75 d = Time.DT(0,0,0,0,0,0,0,0,"",-6,0)76 tester.compare("CST",d.tzName())77 tester.compare(-6,d.tzHourOffset())78 tester.compare(0,d.tzMinuteOffset())79 tester.compare(18,d.hour(local=1))80 tester.compare(0,d.hour())81 tester.testDone()82 tester.startTest("0h 0m, offset -7h, summer")83 d = Time.DT(0,0,0,0,0,0,0,1,"",-7,0)84 tester.compare("PDT",d.tzName())85 tester.compare(-7,d.tzHourOffset())86 tester.compare(0,d.tzMinuteOffset())87 tester.compare(17,d.hour(local=1))88 tester.compare(0,d.hour())89 tester.testDone()90 tester.startTest("0h 0m, offset -7h, winter")91 d = Time.DT(0,0,0,0,0,0,0,0,"",-7,0)92 tester.compare("MST",d.tzName())93 tester.compare(-7,d.tzHourOffset())94 tester.compare(0,d.tzMinuteOffset())95 tester.compare(17,d.hour(local=1))96 tester.compare(0,d.hour())97 tester.testDone()98 tester.groupDone()99 tester.startGroup("Test Date")100 tester.startTest("Y2001, M1, D1")101 d = Time.DT(2001,1,1,0,0,0,0,0,"",0,0)102 tester.compare(2001,d.year())103 tester.compare(1,d.month())104 tester.compare(1,d.day())105 tester.compare(1,d.day(local=1))106 tester.testDone()107 tester.startTest("Y2001, M2, D1, 1h, offset -2h")108 d = Time.DT(2001,2,1,1,0,0,0,0,"",-2,0)109 tester.compare(2001,d.year())110 tester.compare(2,d.month())111 tester.compare(1,d.month(local=1))112 tester.compare(1,d.day())113 tester.compare(31,d.day(local=1))114 tester.compare(23,d.hour(local=1))115 tester.testDone()116 tester.startTest("Y2001, M2, D1, 33h")117 d = Time.DT(2001,2,1,33,0,0,0,0,"",0,0)118 tester.compare(2001,d.year())119 tester.compare(2,d.month())120 tester.compare(2,d.day())121 tester.compare(9,d.hour())122 tester.testDone()123 tester.startTest("Y2000, M2, D30")124 d = Time.DT(2000,2,30,00,0,0,0,0,"",0,0)125 tester.compare(2000,d.year())126 tester.compare(3,d.month())127 tester.compare(1,d.day())128 tester.testDone()129 tester.startTest("Y2001, M2, D30")130 d = Time.DT(2001,2,30,00,0,0,0,0,"",0,0)131 tester.compare(2001,d.year())132 tester.compare(3,d.month())133 tester.compare(2,d.day())134 tester.testDone()135 tester.groupDone()136 tester.groupDone()137def test_iso(tester):138 tester.startGroup("ISO Time Parser")139 for i,h,m,s,ms in [("T232050",23,20,50,0),140 ("23:20:50",23,20,50,0),141 ("T23:20:50",23,20,50,0),142 ("T2320",23,20,0,0),143 ("T23:20",23,20,0,0),144 ("23:20",23,20,0,0),145 ("T23",23,0,0,0),146 ("T232050,5",23,20,50,500),147 ("T232050.5",23,20,50,500),148 ("T23:20:50,5",23,20,50,500),149 ("T23:20:50.5",23,20,50,500),150 ("23:20:50,5",23,20,50,500),151 ("23:20:50.5",23,20,50,500),152 ("T2320,9",23,20,54,0),153 ("T2320.9",23,20,54,0),154 ("T23:20,9",23,20,54,0),155 ("T23:20.9",23,20,54,0),156 ("23:20,9",23,20,54,0),157 ("23:20.9",23,20,54,0),158 ("T23,3",23,18,0,0),159 ("T23.3",23,18,0,0),160 ("T-2050",None,20,50,0),161 ("T-20:50",None,20,50,0),162 ("T-20",None,20,0,0),163 ("T--50",None,None,50,0),164 ("T11,3",11,18,0,0),165 ("T11.3",11,18,0,0),166 ("T-20,9",None,20,54,0),167 ("T-20.9",None,20,54,0),168 ("T-2050,5",None,20,50,500),169 ("T-2050.5",None,20,50,500),170 ("T-20:50,5",None,20,50,500),171 ("T-20:50.5",None,20,50,500),172 ("T--50,5",None,None,50,500),173 ("T--50.5",None,None,50,500),174 ("T000000",0,0,0,0),175 ("T00:00:00",0,0,0,0),176 ("T240000",0,0,0,0),177 ("T24:00:00",0,0,0,0),178 ]:179 tester.startTest(i)180 d = Time.FromISO8601(i)181 if h is None:182 h = time.localtime()[3]183 if m is None:184 m = time.localtime()[4]185 tester.compare(h,d.hour())186 tester.compare(m,d.minute())187 tester.compare(s,d.second())188 tester.compare(ms,d.milliSecond())189 tester.testDone()190 tester.groupDone()191 tester.startGroup("ISO Time and TZ Parser")192 for i,h,m,s,tzh,tzm,lh,lm in [("232030Z",23,20,30,0,0,23,20),193 ("T232030Z",23,20,30,0,0,23,20),194 ("23:20:30Z",23,20,30,0,0,23,20),195 ("T23:20:30Z",23,20,30,0,0,23,20),196 ("2320Z",23,20,0,0,0,23,20),197 ("23:20Z",23,20,0,0,0,23,20),198 ("T2320Z",23,20,0,0,0,23,20),199 ("T23:20Z",23,20,0,0,0,23,20),200 ("23Z",23,0,0,0,0,23,0),201 ("T23Z",23,0,0,0,0,23,0),202 ("T152746+0130",13,57,46,1,30,15,27),203 ("T152746+01",14,27,46,1,00,15,27),204 ("T15:27:46+01:30",13,57,46,1,30,15,27),205 ("T15:27:46+01",14,27,46,1,00,15,27),206 ("152746+0130",13,57,46,1,30,15,27),207 ("152746+01",14,27,46,1,00,15,27),208 ("15:27:46+01:30",13,57,46,1,30,15,27),209 ("15:27:46+01",14,27,46,1,00,15,27),210 ("T152746-0530",20,57,46,-5,-30,15,27),211 ("152746-0530",20,57,46,-5,-30,15,27),212 ("T15:27:46-05:30",20,57,46,-5,-30,15,27),213 ("15:27:46-05:30",20,57,46,-5,-30,15,27),214 ("T152746-05",20,27,46,-5,0,15,27),215 ("152746-05",20,27,46,-5,0,15,27),216 ("T15:27:46-05",20,27,46,-5,0,15,27),217 ("15:27:46-05",20,27,46,-5,0,15,27),218 ]:219 tester.startTest(i)220 d = Time.FromISO8601(i)221 tester.compare(h,d.hour())222 tester.compare(m,d.minute())223 tester.compare(s,d.second())224 #tester.compare(tzh,d.tzHourOffset())225 #tester.compare(tzm,d.tzMinuteOffset())226 #tester.compare(lh,d.hour(local=1))227 #tester.compare(lm,d.minute(local=1))228 tester.testDone()229 tester.groupDone()230 tester.startGroup("ISO Date Parser")231 for i,y,m,d in [("19850412",1985,4,12),232 ("1985-04-12",1985,4,12),233 ("1985-04",1985,4,1),234 ("1985",1985,1,1),235 ("1900",1900,1,1),236 ("850412",2085,04,12),237 ("85-04-12",2085,04,12),238 ("-8504",2085,04,1),239 ("-85-04",2085,04,1),240 ("-85",2085,01,1),241 ("--0412",None,04,12),242 ("--04-12",None,04,12),243 ("--04",None,04,1),244 ("---12",None,None,12),245 ]:246 tester.startTest(i)247 dt = Time.FromISO8601(i)248 now = time.localtime()249 if y is None:250 y = now[0]251 if m is None:252 m = now[1]253 tester.compare(y,dt.year())254 tester.compare(m,dt.month())255 tester.compare(d,dt.day())256 tester.testDone()257 tester.groupDone()258 tester.startGroup("ISO Ordinal Date Parser")259 for i,y,m,d in [("1985102",1985,4,12),260 ("1985-102",1985,4,12),261 ("85102",2085,04,12),262 ("85-102",2085,04,12),263 (calendar.isleap(time.localtime()[0])264 and "-103" or "-102",None,04,12),265 ]:266 tester.startTest(i)267 dt = Time.FromISO8601(i)268 now = time.localtime()269 if y is None:270 y = now[0]271 if m is None:272 m = now[1]273 tester.compare(y,dt.year())274 tester.compare(m,dt.month())275 tester.compare(d,dt.day())276 tester.testDone()277 tester.groupDone()278 tester.startGroup("ISO Week Date Parser")279 for i,y,m,d in [("1985W155",1985,4,12),280 ("1985-W15-5",1985,4,12),281 ("1985W15",1985,4,8),282 ("1985-W15",1985,4,8),283 ("85W155",2085,04,13),284 ("85-W15-5",2085,04,13),285 ("85W15",2085,04,9),286 ("85-W15",2085,04,9),287 ("-5W155",2005,04,15),288 ("-5-W15-5",2005,04,15),289# date of week 15, day 5 varies from year to year290# ("-W155",None,04,13),291# ("-W15-5",None,04,13),292# ("-W15",None,04,9),293# ("-W15",None,04,9),294 ]:295 tester.startTest(i)296 dt = Time.FromISO8601(i)297 now = time.localtime()298 if y is None:299 y = now[0]300 if m is None:301 m = now[1]302 tester.compare(y,dt.year())303 tester.compare(m,dt.month())304 tester.compare(d,dt.day())305 tester.testDone()306 tester.groupDone()307 tester.startGroup("ISO Combined Date Parser")308 for i,y,m,d,h,min,s,ms,tzh,tzm,ld,lh,lm in [("19850412T101530",1985,4,12,10,15,30,0,0,0,12,10,15),309 ("19850412T1015",1985,4,12,10,15,0,0,0,0,12,10,15),310 ("19850412T10",1985,4,12,10,0,0,0,0,0,12,10,0),311 ("1985-04-12T10:15:30",1985,4,12,10,15,30,0,0,0,12,10,15),312 ("1985-04-12T10:15",1985,4,12,10,15,0,0,0,0,12,10,15),313 ("1985-04-12T10",1985,4,12,10,0,0,0,0,0,12,10,0),314 ("1985102T23:50:30",1985,4,12,23,50,30,0,0,0,12,23,50),315 ("1985102T23:50",1985,4,12,23,50,0,0,0,0,12,23,50),316 ("1985102T23",1985,4,12,23,0,0,0,0,0,12,23,0),317 ("1985-102T23:50:30",1985,4,12,23,50,30,0,0,0,12,23,50),318 ("1985-102T23:50",1985,4,12,23,50,0,0,0,0,12,23,50),319 ("1985-102T23",1985,4,12,23,0,0,0,0,0,12,23,0),320 ("1985W155T235030",1985,4,12,23,50,30,0,0,0,12,23,50),321 ("1985W155T2350",1985,4,12,23,50,0,0,0,0,12,23,50),322 ("1985W155T23",1985,4,12,23,0,0,0,0,0,12,23,0),323 ("1985-W15-5T23:50:30",1985,4,12,23,50,30,0,0,0,12,23,50),324 ("1985-W15-5T23:50",1985,4,12,23,50,0,0,0,0,12,23,50),325 ("1985-W15-5T23",1985,4,12,23,0,0,0,0,0,12,23,0),326 #Some with TZ327 ("1985-04-12T10:15:30,5+03:30",1985,4,12,6,45,30,500,3,30,12,10,15),328 ]:329 tester.startTest(i)330 dt = Time.FromISO8601(i)331 tester.compare(y,dt.year())332 tester.compare(m,dt.month())333 tester.compare(d,dt.day())334 tester.compare(h,dt.hour())335 tester.compare(min,dt.minute())336 tester.compare(s,dt.second())337 tester.compare(ms,dt.milliSecond())338 tester.compare(tzh,dt.tzHourOffset())339 tester.compare(tzm,dt.tzMinuteOffset())340 tester.compare(ld,dt.day(local=1))341 tester.compare(lh,dt.hour(local=1))342 tester.compare(lm,dt.minute(local=1))343 tester.testDone()344 tester.groupDone()345def test_rfc822(tester):346 tester.startGroup("RFC 822 Parsing")347 for i,y,m,d,h,min,s,ms,tzh,tzm,ld,lh,lm in [("Thu, Jan 4 2001 09:15:39 MDT",348 2001,349 1,350 4,351 15,352 15,353 39,354 0,355 -6,356 0,357 4,358 9,359 15),360 ("Tue, May 18 1999 13:45:50 GMT",361 1999,362 5,363 18,364 13,365 45,366 50,367 0,368 0,369 0,370 18,371 13,372 45),373 ]:374 tester.startTest(i)375 dt = Time.FromRFC822(i)376 tester.compare(y,dt.year())377 tester.compare(m,dt.month())378 tester.compare(d,dt.day())379 tester.compare(h,dt.hour())380 tester.compare(min,dt.minute())381 tester.compare(s,dt.second())382 tester.compare(ms,dt.milliSecond())383 tester.compare(tzh,dt.tzHourOffset())384 tester.compare(tzm,dt.tzMinuteOffset())385 tester.compare(ld,dt.day(local=1))386 tester.compare(lh,dt.hour(local=1))387 tester.compare(lm,dt.minute(local=1))388 tester.testDone()389 tester.groupDone()390def test_serialize(tester):391 tester.startGroup("ISO Time Serializer")392 for i,o,ol in [("T10:30:50","T10:30:50Z","T10:30:50Z"),393 ("T10:30:50+0130","T09:00:50Z","T10:30:50+01:30"),394 ("T10:30:50,5+0130","T09:00:50,5Z","T10:30:50,5+01:30"),395 ]:396 tester.startTest(i)397 dt = Time.FromISO8601(i)398 e = dt.asISO8601Time()399 tester.compare(o,e)400 e = dt.asISO8601Time(local=1)401 tester.compare(ol,e)402 tester.testDone()403 tester.groupDone()404 tester.startGroup("ISO Date Serializer")405 for i,o in [("20011217","2001-12-17"),406 ("20010133","2001-02-02"),407 ]:408 tester.startTest(i)409 dt = Time.FromISO8601(i)410 e = dt.asISO8601Date()411 tester.compare(o,e)412 e = dt.asISO8601Date(local=1)413 tester.compare(o,e)414 tester.testDone()415 tester.groupDone()416 tester.startGroup("ISO Date Time Serializer")417 for i,o,ol in [("20011217T10:30:50","2001-12-17T10:30:50Z","2001-12-17T10:30:50Z"),418 ("20011217T10:30:50+0130","2001-12-17T09:00:50Z","2001-12-17T10:30:50+01:30"),419 ]:420 tester.startTest(i)421 dt = Time.FromISO8601(i)422 e = dt.asISO8601DateTime()423 tester.compare(o,e)424 e = dt.asISO8601DateTime(local=1)425 tester.compare(ol,e)426 tester.testDone()427 tester.groupDone()428 tester.startGroup("RFC822 Date Time Serializer")429 for i,o,ol in [("Thu, 04 Jan 2001 09:15:39 MDT","Thu, 04 Jan 2001 15:15:39 GMT","Thu, 04 Jan 2001 09:15:39 MDT"),430 ("Fri, 05 Jan 2001 09:15:39 GMT","Fri, 05 Jan 2001 09:15:39 GMT","Fri, 05 Jan 2001 09:15:39 GMT"),431 ]:432 tester.startTest(i)433 dt = Time.FromRFC822(i)434 e = dt.asRFC822DateTime()435 tester.compare(o,e)436 e = dt.asRFC822DateTime(local=1)437 tester.compare(ol,e)438 tester.testDone()439 tester.groupDone()440def test_python_tuple(tester):441 tester.startGroup("Python time tuple")442 for i,o in [((2001,12,17,13,15,30,0,0,-1),"2001-12-17T13:15:30Z"),443 ((2000,1,33,13,15,30,0,0,-1),"2000-02-02T13:15:30Z"),444 ]:445 tester.startTest(repr(i))446 ol = utcTupleToLocal8601(i)447 dt = Time.FromPythonTimeTuple(i)448 e = dt.asISO8601DateTime()449 tester.compare(o,e)450 e = dt.asISO8601DateTime(local=1)451 tester.compare(ol,e)452 e = dt.asPythonTimeTuple()453 tester.testDone()454 tester.groupDone()455 tester.startTest("Python time")456 t = time.time()457 dt = Time.FromPythonTime(t)458 test = time.gmtime(t)459 tester.compare(dt.year(),test[0])460 tester.compare(dt.month(),test[1])461 tester.compare(dt.day(),test[2])462 tester.compare(dt.hour(),test[3])463 tester.compare(dt.minute(),test[4])464 tester.compare(dt.second(),test[5])465 tester.testDone()466 return467def Test(tester):468 test_instance(tester)469 test_iso(tester)...
test_test_results.py
Source:test_test_results.py
...65 self.assertEqual(1, self.result._calls)66 # The hook in asserter must have been called too, otherwise the67 # assertion about ordering won't have completed.68 self.assertEqual(1, self.decorated._calls)69 def test_startTest(self):70 self.result.startTest(self)71 def test_startTestRun(self):72 self.result.startTestRun()73 def test_stopTest(self):74 self.result.stopTest(self)75 def test_stopTestRun(self):76 self.result.stopTestRun()77 def test_addError(self):78 self.result.addError(self, subunit.RemoteError())79 def test_addError_details(self):80 self.result.addError(self, details={})81 def test_addFailure(self):82 self.result.addFailure(self, subunit.RemoteError())83 def test_addFailure_details(self):84 self.result.addFailure(self, details={})85 def test_addSuccess(self):86 self.result.addSuccess(self)87 def test_addSuccess_details(self):88 self.result.addSuccess(self, details={})89 def test_addSkip(self):90 self.result.addSkip(self, "foo")91 def test_addSkip_details(self):92 self.result.addSkip(self, details={})93 def test_addExpectedFailure(self):94 self.result.addExpectedFailure(self, subunit.RemoteError())95 def test_addExpectedFailure_details(self):96 self.result.addExpectedFailure(self, details={})97 def test_addUnexpectedSuccess(self):98 self.result.addUnexpectedSuccess(self)99 def test_addUnexpectedSuccess_details(self):100 self.result.addUnexpectedSuccess(self, details={})101 def test_progress(self):102 self.result.progress(1, subunit.PROGRESS_SET)103 def test_wasSuccessful(self):104 self.result.wasSuccessful()105 def test_shouldStop(self):106 self.result.shouldStop107 def test_stop(self):108 self.result.stop()109 def test_time(self):110 self.result.time(None)111class TestAutoTimingTestResultDecorator(unittest.TestCase):112 def setUp(self):113 # And end to the chain which captures time events.114 terminal = TimeCapturingResult()115 # The result object under test.116 self.result = subunit.test_results.AutoTimingTestResultDecorator(117 terminal)118 self.decorated = terminal119 def test_without_time_calls_time_is_called_and_not_None(self):120 self.result.startTest(self)121 self.assertEqual(1, len(self.decorated._calls))122 self.assertNotEqual(None, self.decorated._calls[0])123 def test_no_time_from_progress(self):124 self.result.progress(1, subunit.PROGRESS_CUR)125 self.assertEqual(0, len(self.decorated._calls))126 def test_no_time_from_shouldStop(self):127 self.decorated.stop()128 self.result.shouldStop129 self.assertEqual(0, len(self.decorated._calls))130 def test_calling_time_inhibits_automatic_time(self):131 # Calling time() outputs a time signal immediately and prevents132 # automatically adding one when other methods are called.133 time = datetime.datetime(2009,10,11,12,13,14,15, iso8601.Utc())134 self.result.time(time)135 self.result.startTest(self)136 self.result.stopTest(self)137 self.assertEqual(1, len(self.decorated._calls))138 self.assertEqual(time, self.decorated._calls[0])139 def test_calling_time_None_enables_automatic_time(self):140 time = datetime.datetime(2009,10,11,12,13,14,15, iso8601.Utc())141 self.result.time(time)142 self.assertEqual(1, len(self.decorated._calls))143 self.assertEqual(time, self.decorated._calls[0])144 # Calling None passes the None through, in case other results care.145 self.result.time(None)146 self.assertEqual(2, len(self.decorated._calls))147 self.assertEqual(None, self.decorated._calls[1])148 # Calling other methods doesn't generate an automatic time event.149 self.result.startTest(self)150 self.assertEqual(3, len(self.decorated._calls))151 self.assertNotEqual(None, self.decorated._calls[2])152 def test_set_failfast_True(self):153 self.assertFalse(self.decorated.failfast)154 self.result.failfast = True155 self.assertTrue(self.decorated.failfast)156class TestTagCollapsingDecorator(TestCase):157 def test_tags_collapsed_outside_of_tests(self):158 result = ExtendedTestResult()159 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)160 tag_collapser.tags(set(['a']), set())161 tag_collapser.tags(set(['b']), set())162 tag_collapser.startTest(self)163 self.assertEquals(164 [('tags', set(['a', 'b']), set([])),165 ('startTest', self),166 ], result._events)167 def test_tags_collapsed_outside_of_tests_are_flushed(self):168 result = ExtendedTestResult()169 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)170 tag_collapser.startTestRun()171 tag_collapser.tags(set(['a']), set())172 tag_collapser.tags(set(['b']), set())173 tag_collapser.startTest(self)174 tag_collapser.addSuccess(self)175 tag_collapser.stopTest(self)176 tag_collapser.stopTestRun()177 self.assertEquals(178 [('startTestRun',),179 ('tags', set(['a', 'b']), set([])),180 ('startTest', self),181 ('addSuccess', self),182 ('stopTest', self),183 ('stopTestRun',),184 ], result._events)185 def test_tags_forwarded_after_tests(self):186 test = subunit.RemotedTestCase('foo')187 result = ExtendedTestResult()188 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)189 tag_collapser.startTestRun()190 tag_collapser.startTest(test)191 tag_collapser.addSuccess(test)192 tag_collapser.stopTest(test)193 tag_collapser.tags(set(['a']), set(['b']))194 tag_collapser.stopTestRun()195 self.assertEqual(196 [('startTestRun',),197 ('startTest', test),198 ('addSuccess', test),199 ('stopTest', test),200 ('tags', set(['a']), set(['b'])),201 ('stopTestRun',),202 ],203 result._events)204 def test_tags_collapsed_inside_of_tests(self):205 result = ExtendedTestResult()206 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)207 test = subunit.RemotedTestCase('foo')208 tag_collapser.startTest(test)209 tag_collapser.tags(set(['a']), set())210 tag_collapser.tags(set(['b']), set(['a']))211 tag_collapser.tags(set(['c']), set())212 tag_collapser.stopTest(test)213 self.assertEquals(214 [('startTest', test),215 ('tags', set(['b', 'c']), set(['a'])),216 ('stopTest', test)],217 result._events)218 def test_tags_collapsed_inside_of_tests_different_ordering(self):219 result = ExtendedTestResult()220 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)221 test = subunit.RemotedTestCase('foo')222 tag_collapser.startTest(test)223 tag_collapser.tags(set(), set(['a']))224 tag_collapser.tags(set(['a', 'b']), set())225 tag_collapser.tags(set(['c']), set())226 tag_collapser.stopTest(test)227 self.assertEquals(228 [('startTest', test),229 ('tags', set(['a', 'b', 'c']), set()),230 ('stopTest', test)],231 result._events)232 def test_tags_sent_before_result(self):233 # Because addSuccess and friends tend to send subunit output234 # immediately, and because 'tags:' before a result line means235 # something different to 'tags:' after a result line, we need to be236 # sure that tags are emitted before 'addSuccess' (or whatever).237 result = ExtendedTestResult()238 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)239 test = subunit.RemotedTestCase('foo')240 tag_collapser.startTest(test)241 tag_collapser.tags(set(['a']), set())242 tag_collapser.addSuccess(test)243 tag_collapser.stopTest(test)244 self.assertEquals(245 [('startTest', test),246 ('tags', set(['a']), set()),247 ('addSuccess', test),248 ('stopTest', test)],249 result._events)250class TestTimeCollapsingDecorator(TestCase):251 def make_time(self):252 # Heh heh.253 return datetime.datetime(254 2000, 1, self.getUniqueInteger(), tzinfo=iso8601.UTC)255 def test_initial_time_forwarded(self):256 # We always forward the first time event we see.257 result = ExtendedTestResult()258 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)259 a_time = self.make_time()260 tag_collapser.time(a_time)261 self.assertEquals([('time', a_time)], result._events)262 def test_time_collapsed_to_first_and_last(self):263 # If there are many consecutive time events, only the first and last264 # are sent through.265 result = ExtendedTestResult()266 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)267 times = [self.make_time() for i in range(5)]268 for a_time in times:269 tag_collapser.time(a_time)270 tag_collapser.startTest(subunit.RemotedTestCase('foo'))271 self.assertEquals(272 [('time', times[0]), ('time', times[-1])], result._events[:-1])273 def test_only_one_time_sent(self):274 # If we receive a single time event followed by a non-time event, we275 # send exactly one time event.276 result = ExtendedTestResult()277 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)278 a_time = self.make_time()279 tag_collapser.time(a_time)280 tag_collapser.startTest(subunit.RemotedTestCase('foo'))281 self.assertEquals([('time', a_time)], result._events[:-1])282 def test_duplicate_times_not_sent(self):283 # Many time events with the exact same time are collapsed into one284 # time event.285 result = ExtendedTestResult()286 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)287 a_time = self.make_time()288 for i in range(5):289 tag_collapser.time(a_time)290 tag_collapser.startTest(subunit.RemotedTestCase('foo'))291 self.assertEquals([('time', a_time)], result._events[:-1])292 def test_no_times_inserted(self):293 result = ExtendedTestResult()294 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)295 a_time = self.make_time()296 tag_collapser.time(a_time)297 foo = subunit.RemotedTestCase('foo')298 tag_collapser.startTest(foo)299 tag_collapser.addSuccess(foo)300 tag_collapser.stopTest(foo)301 self.assertEquals(302 [('time', a_time),303 ('startTest', foo),304 ('addSuccess', foo),305 ('stopTest', foo)], result._events)306class TestByTestResultTests(testtools.TestCase):307 def setUp(self):308 super(TestByTestResultTests, self).setUp()309 self.log = []310 self.result = subunit.test_results.TestByTestResult(self.on_test)311 if sys.version_info >= (3, 0):312 self.result._now = iter(range(5)).__next__313 else:314 self.result._now = iter(range(5)).next315 def assertCalled(self, **kwargs):316 defaults = {317 'test': self,318 'tags': set(),319 'details': None,320 'start_time': 0,321 'stop_time': 1,322 }323 defaults.update(kwargs)324 self.assertEqual([defaults], self.log)325 def on_test(self, **kwargs):326 self.log.append(kwargs)327 def test_no_tests_nothing_reported(self):328 self.result.startTestRun()329 self.result.stopTestRun()330 self.assertEqual([], self.log)331 def test_add_success(self):332 self.result.startTest(self)333 self.result.addSuccess(self)334 self.result.stopTest(self)335 self.assertCalled(status='success')336 def test_add_success_details(self):337 self.result.startTest(self)338 details = {'foo': 'bar'}339 self.result.addSuccess(self, details=details)340 self.result.stopTest(self)341 self.assertCalled(status='success', details=details)342 def test_tags(self):343 if not getattr(self.result, 'tags', None):344 self.skipTest("No tags in testtools")345 self.result.tags(['foo'], [])346 self.result.startTest(self)347 self.result.addSuccess(self)348 self.result.stopTest(self)349 self.assertCalled(status='success', tags=set(['foo']))350 def test_add_error(self):351 self.result.startTest(self)352 try:353 1/0354 except ZeroDivisionError:355 error = sys.exc_info()356 self.result.addError(self, error)357 self.result.stopTest(self)358 self.assertCalled(359 status='error',360 details={'traceback': TracebackContent(error, self)})361 def test_add_error_details(self):362 self.result.startTest(self)363 details = {"foo": text_content("bar")}364 self.result.addError(self, details=details)365 self.result.stopTest(self)366 self.assertCalled(status='error', details=details)367 def test_add_failure(self):368 self.result.startTest(self)369 try:370 self.fail("intentional failure")371 except self.failureException:372 failure = sys.exc_info()373 self.result.addFailure(self, failure)374 self.result.stopTest(self)375 self.assertCalled(376 status='failure',377 details={'traceback': TracebackContent(failure, self)})378 def test_add_failure_details(self):379 self.result.startTest(self)380 details = {"foo": text_content("bar")}381 self.result.addFailure(self, details=details)382 self.result.stopTest(self)383 self.assertCalled(status='failure', details=details)384 def test_add_xfail(self):385 self.result.startTest(self)386 try:387 1/0388 except ZeroDivisionError:389 error = sys.exc_info()390 self.result.addExpectedFailure(self, error)391 self.result.stopTest(self)392 self.assertCalled(393 status='xfail',394 details={'traceback': TracebackContent(error, self)})395 def test_add_xfail_details(self):396 self.result.startTest(self)397 details = {"foo": text_content("bar")}398 self.result.addExpectedFailure(self, details=details)399 self.result.stopTest(self)400 self.assertCalled(status='xfail', details=details)401 def test_add_unexpected_success(self):402 self.result.startTest(self)403 details = {'foo': 'bar'}404 self.result.addUnexpectedSuccess(self, details=details)405 self.result.stopTest(self)406 self.assertCalled(status='success', details=details)407 def test_add_skip_reason(self):408 self.result.startTest(self)409 reason = self.getUniqueString()410 self.result.addSkip(self, reason)411 self.result.stopTest(self)412 self.assertCalled(413 status='skip', details={'reason': text_content(reason)})414 def test_add_skip_details(self):415 self.result.startTest(self)416 details = {'foo': 'bar'}417 self.result.addSkip(self, details=details)418 self.result.stopTest(self)419 self.assertCalled(status='skip', details=details)420 def test_twice(self):421 self.result.startTest(self)422 self.result.addSuccess(self, details={'foo': 'bar'})423 self.result.stopTest(self)424 self.result.startTest(self)425 self.result.addSuccess(self)426 self.result.stopTest(self)427 self.assertEqual(428 [{'test': self,429 'status': 'success',430 'start_time': 0,431 'stop_time': 1,432 'tags': set(),433 'details': {'foo': 'bar'}},434 {'test': self,435 'status': 'success',436 'start_time': 2,437 'stop_time': 3,438 'tags': set(),439 'details': None},440 ],441 self.log)442class TestCsvResult(testtools.TestCase):443 def parse_stream(self, stream):444 stream.seek(0)445 reader = csv.reader(stream)446 return list(reader)447 def test_csv_output(self):448 stream = StringIO()449 result = subunit.test_results.CsvResult(stream)450 if sys.version_info >= (3, 0):451 result._now = iter(range(5)).__next__452 else:453 result._now = iter(range(5)).next454 result.startTestRun()455 result.startTest(self)456 result.addSuccess(self)457 result.stopTest(self)458 result.stopTestRun()459 self.assertEqual(460 [['test', 'status', 'start_time', 'stop_time'],461 [self.id(), 'success', '0', '1'],462 ],463 self.parse_stream(stream))464 def test_just_header_when_no_tests(self):465 stream = StringIO()466 result = subunit.test_results.CsvResult(stream)467 result.startTestRun()468 result.stopTestRun()469 self.assertEqual(...
test_compare.py
Source:test_compare.py
...86 def closeDB(self) :87 if self.db is not None:88 self.db.close()89 self.db = None90 def startTest(self) :91 pass92 def finishTest(self, expected = None) :93 if expected is not None:94 self.check_results(expected)95 self.closeDB()96 def check_results(self, expected) :97 curs = self.db.cursor()98 try:99 index = 0100 rec = curs.first()101 while rec:102 key, ignore = rec103 self.assertLess(index, len(expected),104 "to many values returned from cursor")105 self.assertEqual(expected[index], key,106 "expected value `%s' at %d but got `%s'"107 % (expected[index], index, key))108 index = index + 1109 rec = curs.next()110 self.assertEqual(index, len(expected),111 "not enough values returned from cursor")112 finally:113 curs.close()114class BtreeKeyCompareTestCase(AbstractBtreeKeyCompareTestCase) :115 def runCompareTest(self, comparator, data) :116 self.startTest()117 self.createDB(comparator)118 self.addDataToDB(data)119 self.finishTest(data)120 def test_lexical_ordering(self) :121 self.runCompareTest(lexical_cmp, _expected_lexical_test_data)122 def test_reverse_lexical_ordering(self) :123 expected_rev_data = _expected_lexical_test_data[:]124 expected_rev_data.reverse()125 self.runCompareTest(make_reverse_comparator(lexical_cmp),126 expected_rev_data)127 def test_compare_function_useless(self) :128 self.startTest()129 def socialist_comparator(l, r) :130 return 0131 self.createDB(socialist_comparator)132 self.addDataToDB(['b', 'a', 'd'])133 # all things being equal the first key will be the only key134 # in the database... (with the last key's value fwiw)135 self.finishTest(['b'])136class BtreeExceptionsTestCase(AbstractBtreeKeyCompareTestCase) :137 def test_raises_non_callable(self) :138 self.startTest()139 self.assertRaises(TypeError, self.createDB, 'abc')140 self.assertRaises(TypeError, self.createDB, None)141 self.finishTest()142 def test_set_bt_compare_with_function(self) :143 self.startTest()144 self.createDB(lexical_cmp)145 self.finishTest()146 def check_results(self, results) :147 pass148 def test_compare_function_incorrect(self) :149 self.startTest()150 def bad_comparator(l, r) :151 return 1152 # verify that set_bt_compare checks that comparator('', '') == 0153 self.assertRaises(TypeError, self.createDB, bad_comparator)154 self.finishTest()155 def verifyStderr(self, method, successRe) :156 """157 Call method() while capturing sys.stderr output internally and158 call self.fail() if successRe.search() does not match the stderr159 output. This is used to test for uncatchable exceptions.160 """161 stdErr = sys.stderr162 sys.stderr = StringIO()163 try:164 method()165 finally:166 temp = sys.stderr167 sys.stderr = stdErr168 errorOut = temp.getvalue()169 if not successRe.search(errorOut) :170 self.fail("unexpected stderr output:\n"+errorOut)171 if sys.version_info < (3, 0) : # XXX: How to do this in Py3k ???172 sys.exc_traceback = sys.last_traceback = None173 def _test_compare_function_exception(self) :174 self.startTest()175 def bad_comparator(l, r) :176 if l == r:177 # pass the set_bt_compare test178 return 0179 raise RuntimeError, "i'm a naughty comparison function"180 self.createDB(bad_comparator)181 #print "\n*** test should print 2 uncatchable tracebacks ***"182 self.addDataToDB(['a', 'b', 'c']) # this should raise, but...183 self.finishTest()184 def test_compare_function_exception(self) :185 self.verifyStderr(186 self._test_compare_function_exception,187 re.compile('(^RuntimeError:.* naughty.*){2}', re.M|re.S)188 )189 def _test_compare_function_bad_return(self) :190 self.startTest()191 def bad_comparator(l, r) :192 if l == r:193 # pass the set_bt_compare test194 return 0195 return l196 self.createDB(bad_comparator)197 #print "\n*** test should print 2 errors about returning an int ***"198 self.addDataToDB(['a', 'b', 'c']) # this should raise, but...199 self.finishTest()200 def test_compare_function_bad_return(self) :201 self.verifyStderr(202 self._test_compare_function_bad_return,203 re.compile('(^TypeError:.* return an int.*){2}', re.M|re.S)204 )205 def test_cannot_assign_twice(self) :206 def my_compare(a, b) :207 return 0208 self.startTest()209 self.createDB(my_compare)210 self.assertRaises(RuntimeError, self.db.set_bt_compare, my_compare)211class AbstractDuplicateCompareTestCase(unittest.TestCase) :212 env = None213 db = None214 if (sys.version_info < (2, 7)) or ((sys.version_info >= (3,0)) and215 (sys.version_info < (3, 2))) :216 def assertLess(self, a, b, msg=None) :217 return self.assertTrue(a<b, msg=msg)218 def setUp(self) :219 self.filename = self.__class__.__name__ + '.db'220 self.homeDir = get_new_environment_path()221 env = db.DBEnv()222 env.open(self.homeDir,223 db.DB_CREATE | db.DB_INIT_MPOOL224 | db.DB_INIT_LOCK | db.DB_THREAD)225 self.env = env226 def tearDown(self) :227 self.closeDB()228 if self.env is not None:229 self.env.close()230 self.env = None231 test_support.rmtree(self.homeDir)232 def addDataToDB(self, data) :233 for item in data:234 self.db.put("key", item)235 def createDB(self, dup_comparator) :236 self.db = db.DB(self.env)237 self.setupDB(dup_comparator)238 self.db.open(self.filename, "test", db.DB_BTREE, db.DB_CREATE)239 def setupDB(self, dup_comparator) :240 self.db.set_flags(db.DB_DUPSORT)241 self.db.set_dup_compare(dup_comparator)242 def closeDB(self) :243 if self.db is not None:244 self.db.close()245 self.db = None246 def startTest(self) :247 pass248 def finishTest(self, expected = None) :249 if expected is not None:250 self.check_results(expected)251 self.closeDB()252 def check_results(self, expected) :253 curs = self.db.cursor()254 try:255 index = 0256 rec = curs.first()257 while rec:258 ignore, data = rec259 self.assertLess(index, len(expected),260 "to many values returned from cursor")261 self.assertEqual(expected[index], data,262 "expected value `%s' at %d but got `%s'"263 % (expected[index], index, data))264 index = index + 1265 rec = curs.next()266 self.assertEqual(index, len(expected),267 "not enough values returned from cursor")268 finally:269 curs.close()270class DuplicateCompareTestCase(AbstractDuplicateCompareTestCase) :271 def runCompareTest(self, comparator, data) :272 self.startTest()273 self.createDB(comparator)274 self.addDataToDB(data)275 self.finishTest(data)276 def test_lexical_ordering(self) :277 self.runCompareTest(lexical_cmp, _expected_lexical_test_data)278 def test_reverse_lexical_ordering(self) :279 expected_rev_data = _expected_lexical_test_data[:]280 expected_rev_data.reverse()281 self.runCompareTest(make_reverse_comparator(lexical_cmp),282 expected_rev_data)283class DuplicateExceptionsTestCase(AbstractDuplicateCompareTestCase) :284 def test_raises_non_callable(self) :285 self.startTest()286 self.assertRaises(TypeError, self.createDB, 'abc')287 self.assertRaises(TypeError, self.createDB, None)288 self.finishTest()289 def test_set_dup_compare_with_function(self) :290 self.startTest()291 self.createDB(lexical_cmp)292 self.finishTest()293 def check_results(self, results) :294 pass295 def test_compare_function_incorrect(self) :296 self.startTest()297 def bad_comparator(l, r) :298 return 1299 # verify that set_dup_compare checks that comparator('', '') == 0300 self.assertRaises(TypeError, self.createDB, bad_comparator)301 self.finishTest()302 def test_compare_function_useless(self) :303 self.startTest()304 def socialist_comparator(l, r) :305 return 0306 self.createDB(socialist_comparator)307 # DUPSORT does not allow "duplicate duplicates"308 self.assertRaises(db.DBKeyExistError, self.addDataToDB, ['b', 'a', 'd'])309 self.finishTest()310 def verifyStderr(self, method, successRe) :311 """312 Call method() while capturing sys.stderr output internally and313 call self.fail() if successRe.search() does not match the stderr314 output. This is used to test for uncatchable exceptions.315 """316 stdErr = sys.stderr317 sys.stderr = StringIO()318 try:319 method()320 finally:321 temp = sys.stderr322 sys.stderr = stdErr323 errorOut = temp.getvalue()324 if not successRe.search(errorOut) :325 self.fail("unexpected stderr output:\n"+errorOut)326 if sys.version_info < (3, 0) : # XXX: How to do this in Py3k ???327 sys.exc_traceback = sys.last_traceback = None328 def _test_compare_function_exception(self) :329 self.startTest()330 def bad_comparator(l, r) :331 if l == r:332 # pass the set_dup_compare test333 return 0334 raise RuntimeError, "i'm a naughty comparison function"335 self.createDB(bad_comparator)336 #print "\n*** test should print 2 uncatchable tracebacks ***"337 self.addDataToDB(['a', 'b', 'c']) # this should raise, but...338 self.finishTest()339 def test_compare_function_exception(self) :340 self.verifyStderr(341 self._test_compare_function_exception,342 re.compile('(^RuntimeError:.* naughty.*){2}', re.M|re.S)343 )344 def _test_compare_function_bad_return(self) :345 self.startTest()346 def bad_comparator(l, r) :347 if l == r:348 # pass the set_dup_compare test349 return 0350 return l351 self.createDB(bad_comparator)352 #print "\n*** test should print 2 errors about returning an int ***"353 self.addDataToDB(['a', 'b', 'c']) # this should raise, but...354 self.finishTest()355 def test_compare_function_bad_return(self) :356 self.verifyStderr(357 self._test_compare_function_bad_return,358 re.compile('(^TypeError:.* return an int.*){2}', re.M|re.S)359 )360 def test_cannot_assign_twice(self) :361 def my_compare(a, b) :362 return 0363 self.startTest()364 self.createDB(my_compare)365 self.assertRaises(RuntimeError, self.db.set_dup_compare, my_compare)366def test_suite() :367 res = unittest.TestSuite()368 res.addTest(unittest.makeSuite(ComparatorTests))369 res.addTest(unittest.makeSuite(BtreeExceptionsTestCase))370 res.addTest(unittest.makeSuite(BtreeKeyCompareTestCase))371 res.addTest(unittest.makeSuite(DuplicateExceptionsTestCase))372 res.addTest(unittest.makeSuite(DuplicateCompareTestCase))373 return res374if __name__ == '__main__':...
test_domlette_memory.py
Source:test_domlette_memory.py
...29 pass30class TestDocumentFragment(Domlette.DocumentFragment, TestNode):31 pass32def test_empty_node(tester,domMod):33 tester.startTest("Empty Document")34 StartNodeCounting()35 doc = TestDocument()36 tester.compare(1, GetNodeCount())37 del doc38 tester.compare(0, GetNodeCount())39 tester.testDone()40 tester.startTest("Empty Text")41 StartNodeCounting()42 doc = TestDocument()43 text = TestText(doc, "Foo")44 tester.compare(2, GetNodeCount())45 del text46 tester.compare(1, GetNodeCount())47 tester.testDone()48 tester.startTest("Empty Element")49 StartNodeCounting()50 elem = TestElement(doc, None,"Foo")51 tester.compare(1, GetNodeCount())52 del elem53 tester.compare(0, GetNodeCount())54 tester.testDone()55 tester.startTest("Empty Attribute")56 StartNodeCounting()57 attr = TestAttr(doc, None,"Foo")58 tester.compare(1, GetNodeCount())59 del attr60 tester.compare(0, GetNodeCount())61 tester.testDone()62 tester.startTest("Empty Comment")63 StartNodeCounting()64 com = TestComment(doc, "Foo")65 tester.compare(1, GetNodeCount())66 del com67 tester.compare(0, GetNodeCount())68 tester.testDone()69 tester.startTest("Empty Processing Instruction")70 StartNodeCounting()71 pi = TestProcessingInstruction(doc, "Foo", "Bar")72 tester.compare(1, GetNodeCount())73 del pi74 tester.compare(0, GetNodeCount())75 tester.testDone()76 tester.startTest("Empty Document Fragment")77 StartNodeCounting()78 df = TestDocumentFragment(doc)79 tester.compare(1, GetNodeCount())80 del df81 tester.compare(0, GetNodeCount())82 tester.testDone()83def test_small_tree(tester,domMod):84 gc.collect() #Force to clean everything up85 tester.startTest("Single Parent -> child rel")86 doc = TestDocument()87 StartNodeCounting()88 elem = TestElement(doc, None, "Foo")89 elem2 = TestElement(doc, None, "Foo2")90 elem.appendChild(elem2)91 tester.compare(2, GetNodeCount())92 del elem93 del elem294 gc.collect() #Force collection95 tester.compare(0, GetNodeCount())96 del doc97 tester.testDone()98 tester.startTest("Document -> elem rel")99 StartNodeCounting()100 doc = TestDocument()101 elem = TestElement(doc, None, "Foo")102 doc.appendChild(elem)103 tester.compare(2, GetNodeCount())104 del doc105 del elem106 gc.collect() #Force collection107 tester.compare(0, GetNodeCount())108 tester.testDone()109 tester.startTest("Document -> text rel")110 StartNodeCounting()111 doc = TestDocument()112 text = TestText(doc, "Foo")113 doc.appendChild(text)114 tester.compare(2, GetNodeCount())115 del doc116 del text117 gc.collect() #Force collection118 tester.compare(0, GetNodeCount())119 tester.testDone()120 tester.startTest("Document -> pi rel")121 StartNodeCounting()122 doc = TestDocument()123 pi = TestProcessingInstruction(doc, "Foo", "Bar")124 doc.appendChild(pi)125 tester.compare(2, GetNodeCount())126 del doc127 del pi128 gc.collect() #Force collection129 tester.compare(0, GetNodeCount())130 tester.testDone()131 tester.startTest("Document -> comment rel")132 StartNodeCounting()133 doc = TestDocument()134 com = TestComment(doc, "Foo")135 doc.appendChild(com)136 tester.compare(2, GetNodeCount())137 del doc138 del com139 gc.collect() #Force collection140 tester.compare(0, GetNodeCount())141 tester.testDone()142def test_df_tree(tester,domMod):143 gc.collect() #Force to clean everything up144 tester.startTest("Document Fragment Tree")145 doc = TestDocument()146 StartNodeCounting()147 df = TestDocumentFragment(doc)148 elem = TestElement(doc, None, "Foo")149 elem2 = TestElement(doc, None, "Foo2")150 df.appendChild(elem)151 df.appendChild(elem2)152 tester.compare(3, GetNodeCount())153 del elem154 del elem2155 del df156 gc.collect() #Force collection157 tester.compare(0, GetNodeCount())158 tester.testDone()159def test_attributes(tester,domMod):160 gc.collect() #Force to clean everything up161 tester.startTest("Element with setAttributeNodeNS")162 doc = TestDocument()163 StartNodeCounting()164 elem = TestElement(doc, None, "Foo")165 attr = TestAttr(doc, None, "Foo")166 elem.setAttributeNodeNS(attr)167 tester.compare(2, GetNodeCount())168 del elem169 del attr170 gc.collect() #Force collection171 tester.compare(0, GetNodeCount())172 tester.testDone()173 tester.startTest("Element with setAttributeNS")174 doc = TestDocument()175 StartNodeCounting()176 elem = TestElement(doc, None, "Foo")177 elem.setAttributeNS(None, "Foo", "Bar")178 tester.compare(2, GetNodeCount())179 del elem180 gc.collect() #Force collection181 tester.compare(0, GetNodeCount())182 tester.testDone()183# -- cyclic garbage collection -----------------------------------------184def test_cycles(tester,domMod):185 tester.startGroup("Reclaiming of Cyclic Memory")186 test_empty_node(tester,domMod)187 test_small_tree(tester,domMod)188 test_df_tree(tester,domMod)189 test_attributes(tester,domMod)190 tester.groupDone()191# -- reference counts --------------------------------------------------192def TestRefCounts(tester, document):193 from sys import getrefcount194 def node_refcounts(node, expected):195 if isinstance(node, Domlette.Element):196 # test element's children197 for child in node:198 expected = node_refcounts(child, expected)199 # test element's attributes200 for attr in node.attributes.itervalues():201 expected = node_refcounts(attr, expected)202 # Reference count:203 # +1 for getrefcount() argument204 # +1 for node_refcounts() argument205 # +1 for iterator binding206 # +1 for outer binding207 # +1 for local binding208 msg = node.__class__.__name__ + ' refcounts'209 tester.compare(5, getrefcount(node), msg)210 return expected + 1211 # Reference count:212 # +1 for getrefcount() argument213 # +1 for TestRefCounts() argument214 # +1 for outer binding215 # +1 for local binding216 expected = 4217 for node in document:218 expected = node_refcounts(node, expected)219 msg = document.__class__.__name__ + ' refcounts'220 tester.compare(expected, getrefcount(document), msg)221 return222def test_refcounts(tester,domMod):223 tester.startGroup("Low Level Ref Counts")224 tester.startTest("Empty Document")225 gc.collect()226 assert not gc.garbage, gc.garbage227 doc = TestDocument()228 TestRefCounts(tester, doc)229 del doc230 gc.collect()231 tester.compare(0, len(gc.garbage))232 tester.testDone()233 # Ensure that all local bindings are deleted except for 'doc', obviously.234 tester.startTest("Constructor Created Document")235 gc.collect()236 assert not gc.garbage237 doc = TestDocument()238 elem = TestElement(doc, 'http://foo.com', 'foo:root')239 doc.appendChild(elem)240 text = TestText(doc, "Data1")241 elem.appendChild(text)242 del text243 pi = TestProcessingInstruction(doc, "tar", "Data3")244 doc.insertBefore(pi, elem)245 del pi246 comment = TestComment(doc, "Data2")247 doc.appendChild(comment)248 del comment249 elem2 = TestElement(doc, 'http://foo2.com', 'foo2:child')250 elem2.setAttributeNS('http://foo2.com', 'foo2:attr', 'value')251 elem.appendChild(elem2)252 del elem2253 del elem254 TestRefCounts(tester, doc)255 del doc256 gc.collect()257 tester.compare(0, len(gc.garbage))258 tester.testDone()259 # Ensure that all local bindings are deleted except for 'doc', obviously.260 tester.startTest("DOM Created Document")261 gc.collect()262 assert not gc.garbage263 doc = domMod.implementation.createDocument(None, None, None)264 elem = doc.createElementNS('http://foo.com', 'foo:root')265 doc.appendChild(elem)266 text = doc.createTextNode("Data1")267 elem.appendChild(text)268 del text269 pi = doc.createProcessingInstruction("tar", "Data3")270 doc.insertBefore(pi, elem)271 del pi272 comment = doc.createComment("Data2")273 doc.appendChild(comment)274 del comment275 elem2 = doc.createElementNS('http://foo2.com', 'foo2:child')276 elem2.setAttributeNS('http://foo2.com', 'foo2:attr', 'value')277 elem.appendChild(elem2)278 del elem2279 del elem280 TestRefCounts(tester, doc)281 del doc282 gc.collect()283 tester.compare(0, len(gc.garbage))284 tester.testDone()285 from test_domlette_readers import SMALL_XML, LARGE_XML286 tester.startTest("Small parsed XML")287 isrc = InputSource.DefaultFactory.fromString(SMALL_XML, 'mem')288 gc.collect()289 assert not gc.garbage290 doc = domMod.NonvalParse(isrc)291 TestRefCounts(tester, doc)292 del doc293 gc.collect()294 tester.compare(0, len(gc.garbage))295 tester.testDone()296 tester.startTest("Large parsed XML")297 isrc = InputSource.DefaultFactory.fromString(LARGE_XML, 'mem')298 gc.collect()299 assert not gc.garbage300 doc = domMod.NonvalParse(isrc)301 TestRefCounts(tester, doc)302 del doc303 gc.collect()304 tester.compare(0, len(gc.garbage))305 tester.testDone()306 tester.startTest("Small parsed XML w/ mod")307 isrc = InputSource.DefaultFactory.fromString(SMALL_XML, 'mem')308 gc.collect()309 assert not gc.garbage310 doc = domMod.NonvalParse(isrc)311 for ctr in xrange(1000):312 doc.documentElement.setAttributeNS('http://foo.com', 'bar', 'baz')313 gc.collect()314 TestRefCounts(tester, doc)315 del doc316 gc.collect()317 tester.compare(0, len(gc.garbage))318 tester.testDone()319 tester.groupDone()320 return...
test_skipping.py
Source:test_skipping.py
1import unittest2from unittest.test.support import LoggingResult3class Test_TestSkipping(unittest.TestCase):4 def test_skipping(self):5 class Foo(unittest.TestCase):6 def test_skip_me(self):7 self.skipTest("skip")8 events = []9 result = LoggingResult(events)10 test = Foo("test_skip_me")11 test.run(result)12 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])13 self.assertEqual(result.skipped, [(test, "skip")])14 # Try letting setUp skip the test now.15 class Foo(unittest.TestCase):16 def setUp(self):17 self.skipTest("testing")18 def test_nothing(self): pass19 events = []20 result = LoggingResult(events)21 test = Foo("test_nothing")22 test.run(result)23 self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])24 self.assertEqual(result.skipped, [(test, "testing")])25 self.assertEqual(result.testsRun, 1)26 def test_skipping_subtests(self):27 class Foo(unittest.TestCase):28 def test_skip_me(self):29 with self.subTest(a=1):30 with self.subTest(b=2):31 self.skipTest("skip 1")32 self.skipTest("skip 2")33 self.skipTest("skip 3")34 events = []35 result = LoggingResult(events)36 test = Foo("test_skip_me")37 test.run(result)38 self.assertEqual(events, ['startTest', 'addSkip', 'addSkip',39 'addSkip', 'stopTest'])40 self.assertEqual(len(result.skipped), 3)41 subtest, msg = result.skipped[0]42 self.assertEqual(msg, "skip 1")43 self.assertIsInstance(subtest, unittest.TestCase)44 self.assertIsNot(subtest, test)45 subtest, msg = result.skipped[1]46 self.assertEqual(msg, "skip 2")47 self.assertIsInstance(subtest, unittest.TestCase)48 self.assertIsNot(subtest, test)49 self.assertEqual(result.skipped[2], (test, "skip 3"))50 def test_skipping_decorators(self):51 op_table = ((unittest.skipUnless, False, True),52 (unittest.skipIf, True, False))53 for deco, do_skip, dont_skip in op_table:54 class Foo(unittest.TestCase):55 @deco(do_skip, "testing")56 def test_skip(self): pass57 @deco(dont_skip, "testing")58 def test_dont_skip(self): pass59 test_do_skip = Foo("test_skip")60 test_dont_skip = Foo("test_dont_skip")61 suite = unittest.TestSuite([test_do_skip, test_dont_skip])62 events = []63 result = LoggingResult(events)64 suite.run(result)65 self.assertEqual(len(result.skipped), 1)66 expected = ['startTest', 'addSkip', 'stopTest',67 'startTest', 'addSuccess', 'stopTest']68 self.assertEqual(events, expected)69 self.assertEqual(result.testsRun, 2)70 self.assertEqual(result.skipped, [(test_do_skip, "testing")])71 self.assertTrue(result.wasSuccessful())72 def test_skip_class(self):73 @unittest.skip("testing")74 class Foo(unittest.TestCase):75 def test_1(self):76 record.append(1)77 record = []78 result = unittest.TestResult()79 test = Foo("test_1")80 suite = unittest.TestSuite([test])81 suite.run(result)82 self.assertEqual(result.skipped, [(test, "testing")])83 self.assertEqual(record, [])84 def test_skip_non_unittest_class(self):85 @unittest.skip("testing")86 class Mixin:87 def test_1(self):88 record.append(1)89 class Foo(Mixin, unittest.TestCase):90 pass91 record = []92 result = unittest.TestResult()93 test = Foo("test_1")94 suite = unittest.TestSuite([test])95 suite.run(result)96 self.assertEqual(result.skipped, [(test, "testing")])97 self.assertEqual(record, [])98 def test_expected_failure(self):99 class Foo(unittest.TestCase):100 @unittest.expectedFailure101 def test_die(self):102 self.fail("help me!")103 events = []104 result = LoggingResult(events)105 test = Foo("test_die")106 test.run(result)107 self.assertEqual(events,108 ['startTest', 'addExpectedFailure', 'stopTest'])109 self.assertEqual(result.expectedFailures[0][0], test)110 self.assertTrue(result.wasSuccessful())111 def test_expected_failure_with_wrapped_class(self):112 @unittest.expectedFailure113 class Foo(unittest.TestCase):114 def test_1(self):115 self.assertTrue(False)116 events = []117 result = LoggingResult(events)118 test = Foo("test_1")119 test.run(result)120 self.assertEqual(events,121 ['startTest', 'addExpectedFailure', 'stopTest'])122 self.assertEqual(result.expectedFailures[0][0], test)123 self.assertTrue(result.wasSuccessful())124 def test_expected_failure_with_wrapped_subclass(self):125 class Foo(unittest.TestCase):126 def test_1(self):127 self.assertTrue(False)128 @unittest.expectedFailure129 class Bar(Foo):130 pass131 events = []132 result = LoggingResult(events)133 test = Bar("test_1")134 test.run(result)135 self.assertEqual(events,136 ['startTest', 'addExpectedFailure', 'stopTest'])137 self.assertEqual(result.expectedFailures[0][0], test)138 self.assertTrue(result.wasSuccessful())139 def test_expected_failure_subtests(self):140 # A failure in any subtest counts as the expected failure of the141 # whole test.142 class Foo(unittest.TestCase):143 @unittest.expectedFailure144 def test_die(self):145 with self.subTest():146 # This one succeeds147 pass148 with self.subTest():149 self.fail("help me!")150 with self.subTest():151 # This one doesn't get executed152 self.fail("shouldn't come here")153 events = []154 result = LoggingResult(events)155 test = Foo("test_die")156 test.run(result)157 self.assertEqual(events,158 ['startTest', 'addSubTestSuccess',159 'addExpectedFailure', 'stopTest'])160 self.assertEqual(len(result.expectedFailures), 1)161 self.assertIs(result.expectedFailures[0][0], test)162 self.assertTrue(result.wasSuccessful())163 def test_unexpected_success(self):164 class Foo(unittest.TestCase):165 @unittest.expectedFailure166 def test_die(self):167 pass168 events = []169 result = LoggingResult(events)170 test = Foo("test_die")171 test.run(result)172 self.assertEqual(events,173 ['startTest', 'addUnexpectedSuccess', 'stopTest'])174 self.assertFalse(result.failures)175 self.assertEqual(result.unexpectedSuccesses, [test])176 self.assertFalse(result.wasSuccessful())177 def test_unexpected_success_subtests(self):178 # Success in all subtests counts as the unexpected success of179 # the whole test.180 class Foo(unittest.TestCase):181 @unittest.expectedFailure182 def test_die(self):183 with self.subTest():184 # This one succeeds185 pass186 with self.subTest():187 # So does this one188 pass189 events = []190 result = LoggingResult(events)191 test = Foo("test_die")192 test.run(result)193 self.assertEqual(events,194 ['startTest',195 'addSubTestSuccess', 'addSubTestSuccess',196 'addUnexpectedSuccess', 'stopTest'])197 self.assertFalse(result.failures)198 self.assertEqual(result.unexpectedSuccesses, [test])199 self.assertFalse(result.wasSuccessful())200 def test_skip_doesnt_run_setup(self):201 class Foo(unittest.TestCase):202 wasSetUp = False203 wasTornDown = False204 def setUp(self):205 Foo.wasSetUp = True206 def tornDown(self):207 Foo.wasTornDown = True208 @unittest.skip('testing')209 def test_1(self):210 pass211 result = unittest.TestResult()212 test = Foo("test_1")213 suite = unittest.TestSuite([test])214 suite.run(result)215 self.assertEqual(result.skipped, [(test, "testing")])216 self.assertFalse(Foo.wasSetUp)217 self.assertFalse(Foo.wasTornDown)218 def test_decorated_skip(self):219 def decorator(func):220 def inner(*a):221 return func(*a)222 return inner223 class Foo(unittest.TestCase):224 @decorator225 @unittest.skip('testing')226 def test_1(self):227 pass228 result = unittest.TestResult()229 test = Foo("test_1")230 suite = unittest.TestSuite([test])231 suite.run(result)232 self.assertEqual(result.skipped, [(test, "testing")])233if __name__ == "__main__":...
test_pythonic.py
Source:test_pythonic.py
1#!/usr/bin/env python2from TestSuite import EMPTY_NAMESPACE3def test(tester):4 tester.startGroup('Python Representation')5 tester.startTest('Creating test environment')6 from xml.dom import implementation7 dt = implementation.createDocumentType('','','')8 doc = implementation.createDocument(EMPTY_NAMESPACE,'ROOT',dt)9 c = doc.createComment("Comment")10 tester.testDone()11 tester.startTest('Test Attribute')12 a = doc.createAttribute('ATTR_NAME')13 a.value = 'ATTR_VALUE'14 tester.message(str(a))15 tester.testDone()16 tester.startTest('Testing CDATASection')17 c1 = doc.createCDATASection('Short String')18 tester.message(str(c1))19 c2 = doc.createCDATASection('This is a much longer string, over 20 characters')20 tester.message(str(c2))21 tester.testDone()22 tester.startTest('Testing Comment')23 c1 = doc.createComment('Short Comment')24 tester.message(str(c1))25 c2 = doc.createComment('This is a much longer comment, over 20 characters')26 tester.message(str(c2))27 tester.testDone()28 tester.startTest('Testing Document')29 tester.message(str(doc))30 tester.testDone()31 tester.startTest('Testing Document Fragment')32 df = doc.createDocumentFragment()33 tester.message(str(df))34 tester.testDone()35 tester.startTest('Testing Element')36 e = doc.createElement('ELEMENT')37 tester.message(str(e))38 tester.testDone()39 tester.startTest('Testing Entity')40 e = doc._4dom_createEntity("ID1","ID2","NAME")41 tester.message(str(e))42 tester.testDone()43 tester.startTest('Testing Entity Reference')44 e = doc.createEntityReference('E-Ref')45 tester.message(str(e))46 tester.testDone()47 tester.startTest('Testing NamedNodeMap')48 nnm = implementation._4dom_createNamedNodeMap()49 tester.message(str(nnm))50 tester.testDone()51 tester.startTest('Testing NodeList')52 nl = implementation._4dom_createNodeList([e])53 tester.message(str(nl))54 tester.testDone()55 tester.startTest('Testing Notation')56 n = doc._4dom_createNotation("ID1","ID2","NAME")57 tester.message(str(n))58 tester.testDone()59 tester.startTest('Testing ProcessingInstruction')60 p = doc.createProcessingInstruction('This-is-a-long-target', 'short data')61 tester.message(str(p))62 tester.testDone()63 tester.startTest('Testing Text')64 t = doc.createTextNode('This is a very long text string')65 tester.message(str(t))66 tester.testDone()67 return tester.groupDone()68if __name__ == '__main__':69 import sys70 import TestSuite71 tester = TestSuite.TestSuite()72 retVal = test(tester)...
buzzer.py
Source:buzzer.py
1# Import the required module. 2import RPi.GPIO as GPIO 3#Setup the Pins For Input 4GPIO.setmode(GPIO.BCM)5GPIO.setup(2, GPIO.IN) 6GPIO.setup(3, GPIO.IN) 7GPIO.setup(25, GPIO.IN) 8GPIO.setup(11, GPIO.IN) 9#Vars for Checking if there is a change10unoorange=011dosorange=112unopink=013dospink=114unoblau=015dosblau=116unogruen=017dosgruen=118while 1:19 # Oranger Buzzer20 if GPIO.input(2):21 if unoorange==dosorange:22 file = open("buzzer.txt", "r")23 starttest = file.readline(5)24 file.close()25 if starttest =="start":26 #Prints in the shell27 print "Orange"28 #using txt file as a cash for the color, later used by the info-beamer29 file = open("buzzer.txt", "w")30 file.write("Orange")31 file.close()32 unoorange=033 dosorange=134 else: 35 if unoorange!=dosorange:36 if open("buzzer.txt", "r") !="Tot2":37 print "tot1"38 unoorange=dosorange39 #Pinker Buzzer 40 if GPIO.input(3):41 if unopink==dospink:42 file = open("buzzer.txt", "r")43 starttest = file.readline(5)44 file.close()45 if starttest =="start":46 print "Pink"47 file = open("buzzer.txt", "w")48 file.write("Pink")49 file.close()50 unopink=051 dospink=152 else: 53 if unopink!=dospink:54 print "Tot2"55 unopink=dospink56 57 #Blauer Buzzer 58 if GPIO.input(25):59 if unoblau==dosblau:60 file = open("buzzer.txt", "r")61 starttest = file.readline(5)62 file.close()63 if starttest =="start":64 print "Blau"65 file = open("buzzer.txt", "w")66 file.write("Blau")67 file.close()68 unoblau=069 dosblau=170 else: 71 if unoblau!=dosblau:72 print "Tot3"73 unoblau=dosblau74 75 #Gruener Buzzer 76 if GPIO.input(11):77 if unogruen==dosgruen:78 file = open("buzzer.txt", "r")79 starttest = file.readline(5)80 file.close()81 if starttest =="start":82 print "Gruen"83 file = open("buzzer.txt", "w")84 file.write("Gruen")85 file.close()86 unogruen=087 dosgruen=188 else: 89 if unogruen!=dosgruen:90 print "Tot4"91 unogruen=dosgruen92 #Neustart-Checker 93 file = open("buzzer.txt", "r")94 starttest = file.readline(5)95 file.close()96 if starttest !="start":97 reset=""98 reset=raw_input("Neustart? - Return.")99 file = open("buzzer.txt", "w")100 file.write("start")101 file.close()102 103 ...
Using AI Code Generation
1var wpt = require('wpt');2 if (err) {3 console.log(err);4 } else {5 console.log(data);6 }7});8var wpt = require('wpt');9 if (err) {10 console.log(err);11 } else {12 console.log(data);13 }14});15var wpt = require('wpt');16 if (err) {17 console.log(err);18 } else {19 console.log(data);20 }21});22var wpt = require('wpt');23 if (err) {24 console.log(err);25 } else {26 console.log(data);27 }28});29var wpt = require('wpt');30 if (err) {31 console.log(err);32 } else {33 console.log(data);34 }35});36var wpt = require('wpt');37 if (err) {38 console.log(err);39 } else {40 console.log(data);41 }42});
Using AI Code Generation
1var wpt = require('wpt');2 console.log(data);3});4var wpt = require('wpt');5var options = {6};7 console.log(data);8});9var wpt = require('wpt');10wpt.getTestResults('140619_A7_1BC', function(data) {11 console.log(data);12});13var wpt = require('wpt');14wpt.getLocations(function(data) {15 console.log(data);16});17var wpt = require('wpt');18wpt.getTesters(function(data) {19 console.log(data);20});21var wpt = require('wpt');22wpt.getLocations(function(data) {23 console.log(data);24});25var wpt = require('wpt');26wpt.getTestHistory(function(data) {27 console.log(data);28});29var wpt = require('wpt');30wpt.getVideo('140619_A7_1BC', function(data) {31 console.log(data);32});33var wpt = require('wpt');
Using AI Code Generation
1var wpt = require('wpt.js');2 console.log(data);3});4var wpt = require('wpt.js');5exports.startTest = function(url, callback) {6 callback(response);7};
Using AI Code Generation
1var wpt = require('./wpt.js');2var test = new wpt();3console.log(data);4});5var request = require('request');6var WPT = function(){7var wptKey = 'A.6f4f2c4b3d4f8e5b6c7d8e9f0g1h2i3j4k5l6m7n8o9p';8var wptLocation = 'Dulles:Chrome';9var wptConnectivity = 'Cable';10var wptRuns = 1;11var wptPrivate = 0;12var wptPollResults = 10;13var wptPollResultsDelay = 5000;14var wpt = this;15this.startTest = function(url, browser, callback){16var data = {17};18if(browser && browser == 'IE'){19data.location = 'Dulles:IE10';20}21request.post({url: wptServer, form: data}, function(err, httpResponse, body){22if(err){23callback(err);24}25else{26var data = JSON.parse(body);27var testId = data.data.testId;28wpt.pollResults(testId, callback);29}30});31}32this.pollResults = function(testId, callback){33var data = {34};35var url = wptServer + '?' + querystring.stringify(data);36request.get(url, function(err, httpResponse, body){37if(err){38callback(err);39}40else{41var data = JSON.parse(body);42if(data.statusCode == 101){43setTimeout(function(){44wpt.pollResults(testId, callback);45}, wptPollResultsDelay);46}47else if(data.statusCode == 200){48callback(data);49}50else{51callback(data.statusText);52}53}54});55}56}57module.exports = WPT;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!