Best Python code snippet using autotest_python
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__':...
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!!