Ejemplo n.º 1
0
    def test_specialAttributesInHTML(self):
        tag = AdvancedTag('div')
        tag.attributes['style'] = 'position: absolute; color: purple'

        outerHTML = tag.outerHTML

        assert 'position: absolute' in outerHTML , 'Missing style attribute in outerHTML'
        assert 'purple' in outerHTML , 'Missing style attribute in outerHTML'
Ejemplo n.º 2
0
    def test_setAttribute(self):
        tag = AdvancedTag('div')

        tag.setAttribute('id', 'abc')

        assert tag.getAttribute('id') == 'abc' , 'Expected id to be abc'

        assert tag.getAttribute('blah') == None , 'Expected unset attribute to return None, actually returned %s' %(tag.getAttribute('blah'),)
    def test_unknownStillAttribute(self):
        '''
            test_unknownStillAttribute - Test that setting an unknwon attribute still sets it in HTML
        '''
        tag = AdvancedTag('div')

        tag.setAttribute('squiggle', 'wiggle')

        htmlStr = str(tag)

        assert 'squiggle="wiggle"' in htmlStr

        squiggleAttrValue = tag.getAttribute('squiggle')

        assert squiggleAttrValue == 'wiggle', "Expected 'squiggle' attribute from tag.getAttribute to return 'wiggle'. Got: " + repr(
            squiggleAttrValue)
Ejemplo n.º 4
0
    def test_maxLength(self):
        '''
            test_maxLength - Test the "maxLength" attribute
        '''

        inputEm = AdvancedTag('input')

        assert inputEm.maxlength is None, 'Expected .maxlength to not be valid (should be .maxLength)'

        assert inputEm.maxLength == -1, 'Expected default .maxLength to be -1'

        inputEm.maxLength = 5

        assert inputEm.maxLength == 5, 'Expected to be able to set maxLength to 5 and get 5 back, but got: ' + repr(
            inputEm.maxLength)

        inputEmHTML = str(inputEm)

        assert 'maxlength="5"' in inputEmHTML, 'Expected .maxLength to set the "maxlength" attribute. Got: ' + inputEmHTML

        maxLengthAttr = inputEm.getAttribute('maxlength', None)
        assert maxLengthAttr == "5", 'Expected .getAttribute("maxlength") to return "5", but got: ' + repr(
            maxLengthAttr)

        inputEm.maxLength = 0

        assert inputEm.maxLength == 0, 'Expected to be able to set maxLength to 0'

        gotException = False
        try:
            inputEm.maxLength = -4
        except Exception as e:
            gotException = e

        assert gotException is not False, 'Expected to get an exception when setting maxLength < 0. Did not.'

        try:
            inputEm.setAttribute('maxlength', '-5')
        except Exception as e:
            raise AssertionError(
                'Expected to be able to use .setAttribute to set "maxlength" to an invalid value, but got exception: %s: %s'
                % (e.__class__.__name__, str(e)))

        inputEmHTML = str(inputEm)

        assert 'maxlength="-5"' in inputEmHTML, 'Expected .setAttribute to really set an invalid value on the HTML. Should be maxlength="-5", but got: ' + inputEmHTML

        maxLengthValue = None
        try:
            maxLengthValue = inputEm.maxLength
        except Exception as e:
            raise AssertionError(
                'Expected to be able to query .maxLength after .setAttribute to an invalid value, but got an exception: %s: %s'
                % (e.__class__.__name__, str(e)))

        assert maxLengthValue == -1, 'Expected invalid attribute value to return "-1" on .maxLength access, but got: ' + repr(
            maxLengthValue)
Ejemplo n.º 5
0
    def test_insertAfter(self):
        parser = self.getItemsParser()

        itemsEm = parser.getElementById('items')
        assert itemsEm , 'Expected  to get <div id="outer" '

        newItem =  AdvancedTag('div')
        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item1point5' }
        )

        itemsEm.insertAfter(newItem,  itemsEm.getElementById('item1'))
        childIds = [x.id for x in itemsEm.getElementsByName('item')]

        assert childIds == ['item1', 'item1point5', 'item2'] , 'Expected items to be ordered. Got: %s' %(str(childIds,))

        newItem =  AdvancedTag('div')
        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item3' 
            }
        )

        # test None as before item inserts at end
        itemsEm.insertAfter(newItem, None)
        childIds = [x.id for x in itemsEm.getElementsByName('item')]

        assert childIds == ['item1', 'item1point5', 'item2','item3'] , 'Expected items to be ordered. Got: %s' %(str(childIds,))
        newItem =  AdvancedTag('div')
Ejemplo n.º 6
0
    def test_setAttributes(self):
        tag = AdvancedTag('div')
        tag.setAttributes({'id': 'abc', 'name': 'cheese', 'x-attr': 'bazing'})

        assert tag.getAttribute('id') == 'abc'
        assert tag.getAttribute('name') == 'cheese'
        assert tag.getAttribute('x-attr') == 'bazing'
Ejemplo n.º 7
0
    def test_setClassNameString(self):
        '''
            test_setClassNameString - Test setting the "className" attribute on an AdvancedTag and it being reflected.
        '''

        tag = AdvancedTag('div')

        assert "class=" not in tag.getHTML() , "Expected to not find 'class=' when none is set. Got: " + tag.getHTML()

        assert 'class' not in tag.attributes , 'Expected "class" to not be "in" attributes'

        # Try initial set

        tag.className = "cheese is good"

        assert 'class' in tag.attributes , 'Expected "class" to be "in" attributes'


        assert tag.className == "cheese is good" , "Expected className to equal 'cheese is good' after assign on className attribute. Got: " + repr(tag.className)

        assert 'class="cheese is good"' in str(tag) , "Expected to find class=\"cheese is good\" after set on className attribute. Got: " + str(tag)

        assert tag.classList == ['cheese', 'is', 'good'] , "Expected classList to be set after setting on className attribute. Got: " + repr(tag.classList)

        assert 'class' in tag.attributes.keys() ,  'Expected "class" to be in .keys()'

        # Try changing

        tag.className = "hello world"

        assert tag.className == "hello world" , "Expected to be able to change className attribute. Got: " + repr(tag.className)

        assert 'class="hello world"' in str(tag) , "Expected to be able to change className and have it show up in html attribute. Got: " + str(tag)

        assert tag.classList == ['hello', 'world'] , "Expected to be able to change className attribute, but update not reflected in classList. Got: " + repr(tag.classList)

        # Try removing

        tag.className = ''

        assert tag.className == '' , "Expected to be able to clear className attribute. Got: " + repr(tag.className)

        assert "class=" not in str(tag) , "Expected class attribute to not be on HTML representation after clearing className. Got: " + str(tag)

        assert tag.classList == [] , "Expected to be able to clear className attribute, but did not update classList to empty list. Got: " + repr(tag.classList)
Ejemplo n.º 8
0
    def test_strClassList(self):
        '''
            test_strClassList - Assert that a classList can be str'd (equiv to tag.classList.toString()) to get a " " join
        '''

        x = AdvancedTag('div')

        x.className = 'hello world welcome to the pizza haven'

        classList = x.classList

        assert len(classList) == 7, 'Expected classList to contain 7 elements'

        strClassName = str(classList)

        assert strClassName == 'hello world welcome to the pizza haven', 'Expected to be able to str() the .classList to get className'

        assert strClassName == x.className, 'Expected str of classList to be the same as .className'
Ejemplo n.º 9
0
    def test_strClassList(self):
        '''
            test_strClassList - Assert that a classList can be str'd (equiv to tag.classList.toString()) to get a " " join
        '''

        x = AdvancedTag('div')

        x.className = 'hello world welcome to the pizza haven'

        classList = x.classList

        assert len(classList) == 7 , 'Expected classList to contain 7 elements'

        strClassName = str(classList)

        assert strClassName == 'hello world welcome to the pizza haven' , 'Expected to be able to str() the .classList to get className'

        assert strClassName == x.className , 'Expected str of classList to be the same as .className'
Ejemplo n.º 10
0
    def test_setClassNameSetAttribute(self):
        '''
            test_setClassNameSetAttribute - Test setting/changing/removing the class attribute using setAttribute and friends.
        '''
        tag = AdvancedTag('div')

        assert "class=" not in tag.getHTML() , "Expected to not find 'class=' when none is set. Got: " + tag.getHTML()

        # Try initial set

        tag.setAttribute("class", "cheese is good")

        assert tag.className == "cheese is good" , "Expected className to equal 'cheese is good' after setAttribute('class', ...). Got: " + repr(tag.className)

        assert 'class="cheese is good"' in str(tag) , "Expected to find class=\"cheese is good\" after setAttribute('class', ...). Got: " + str(tag)

        assert tag.classList == ['cheese', 'is', 'good'] , "Expected classList to be set after setAttribute('class', ...). Got: " + repr(tag.classList)

        # Try changing

        tag.setAttribute("class", "hello world")

        assert tag.className == "hello world" , "Expected to be able to change class using setAttribute('class', ...). Got: " + repr(tag.className)

        assert 'class="hello world"' in str(tag) , "Expected to be able to change class using setAttribute('class', ...)  and have it show up in html attribute. Got: " + str(tag)

        assert tag.classList == ['hello', 'world'] , "Expected to be able to change class using setAttribute('class', ...), but update not reflected in classList. Got: " + repr(tag.classList)

        # Try removing, both through removeAttribute and setAttribute('class', '')

        tag1 = tag.cloneNode()

        tag2 = tag.cloneNode()

        tag1.removeAttribute('class')

        assert tag1.className == '' , "Expected to be able to clear class attribute using removeAttribute. Got: " + repr(tag1.className)

        assert "class=" not in str(tag1) , "Expected class attribute to not be on HTML representation after removeAttribute. Got: " + str(tag1)

        assert tag1.classList == [] , "Expected to be able to clear class attribut with removeAttributee, but did not update classList to empty list. Got: " + repr(tag1.classList)

        # Ensure cloneNode unlinked class attribute
        assert tag2.className == 'hello world', 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). className was effected.'
        assert tag2.classList == ['hello', 'world'], 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). classList was effected.'
        assert 'class="hello world"' in str(tag2), 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). class on string of html was effected.'

        tag2.setAttribute('class', '')

        assert tag2.className == '' , "Expected to be able to clear class attribute using setAttribute('class', ''). Got: " + repr(tag2.className)

        assert "class=" not in str(tag2) , "Expected class attribute to not be on HTML representation after setAttribute('class', ''). Got: " + str(tag2)

        assert tag2.classList == [] , "Expected to be able to clear class attribut with setAttribute('class', '')e, but did not update classList to empty list. Got: " + repr(tag2.classList)
Ejemplo n.º 11
0
    def test_classListCopy(self):
        '''
            test_classListCopy - Test that changing the list returned from .classList
                    does NOT affect the class attributes on a node (same as JS).
        '''

        tag = AdvancedTag('div')

        tag.className = "hello world"

        classList = tag.classList

        classList.append('xxx')

        assert 'xxx' not in tag.className , 'Expected .classList return to be independent of source tag, but changing affected className attribute'

        assert 'class="hello world"' in str(tag) , 'Expected .classList return to be independent of source tag, but changing affected class in HTML representation'

        assert tag.classList == ['hello', 'world'] , 'Expected .classList return to be independent of source tag, but changing affected return of .classList'
Ejemplo n.º 12
0
    def test_specialAttributes(self):
        tag = AdvancedTag('div')
        tag.setAttribute('style', 'position: absolute')
        styleValue = str(tag.getAttribute('style'))
        styleValue = styleValue.strip()
        assert styleValue == 'position: absolute', 'Expected position: absolute, got %s' % (
            str(tag.getAttribute('style')), )

        tag.setAttribute('className', 'one two')
        assert str(tag.className).strip(
        ) == 'one two', 'Expected classname to be "one two", got %s' % (repr(
            str(tag.className).strip()), )
Ejemplo n.º 13
0
    def test_appending(self):
        parser = AdvancedHTMLParser()

        parser.parseStr("""<div id='outer'> <div id='items'> <div name="item" id="item1" >item1</div> <div name="item" id="item2" >item2</div> </div> </div>""")

        itemsEm = parser.getElementById('items')
        assert itemsEm , 'Expected  to get <div id="outer" '

        assert len(itemsEm.children) == 2 , 'Expected two children'

        newItem =  AdvancedTag('div')
        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item3' }
        )

        itemsEm.appendNode(newItem)

        assert parser.getElementById('item3') , 'Expected to get item3 after append'
        assert len(parser.getElementsByName('item')) == 3, 'Expected after append that 3 nodes are  set'
        assert itemsEm.children[2].getAttribute('id') == 'item3' , 'Expected to be third attribute'

        newItem =  AdvancedTag('div')
        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item2point5' }
        )

        itemsEm.insertAfter(newItem, itemsEm.children[1])
        childIds = [x.id for x in itemsEm.getElementsByName('item')]

        assert childIds == ['item1', 'item2', 'item2point5', 'item3'] , 'Expected items to be ordered. Got: %s' %(str(childIds,))
Ejemplo n.º 14
0
    def test_spanAttributeOnCol(self):
        '''
            test_spanAttributeOnCol - Tests the "span" attribute on a "col"
        '''

        colEm = AdvancedTag('col')

        assert colEm.span == 1, 'Expected default for col.span to be 1. Got: ' + repr(
            colEm.span)

        colEm.span = 5

        assert colEm.span == 5, 'Expected to be able to set col.span to 5, but returned: ' + repr(
            colEm.span)

        colEmHTML = str(colEm)

        assert 'span="5"' in colEmHTML, 'Expected span="5" to show up after setting col.span to 5. Got: ' + repr(
            colEmHTML)

        colEm.span = -5

        assert colEm.span == 1, 'Expected col.span to be clamped to a minimum of 1. Got: ' + repr(
            colEm.span)

        colEm.span = 1
        assert colEm.span == 1, 'Expected col.span to be clamped to a minimum of 1. Got: ' + repr(
            colEm.span)

        colEm.span = 1500

        assert colEm.span == 1000, 'Expected col.span to be clamped to a maximum of 1000. Got: ' + repr(
            ColEm.span)
Ejemplo n.º 15
0
    def test_setAttribute(self):
        tag = AdvancedTag('div')

        tag.setAttribute('id', 'abc')

        assert tag.getAttribute('id') == 'abc', 'Expected id to be abc'

        assert tag.getAttribute(
            'blah'
        ) == None, 'Expected unset attribute to return None, actually returned %s' % (
            tag.getAttribute('blah'), )
Ejemplo n.º 16
0
    def test_insertBefore(self):
        parser = self.getItemsParser()

        itemsEm = parser.getElementById('items')
        assert itemsEm , 'Failed to get <div id="items" '

        newItem =  AdvancedTag('div')
        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item1point5'
            }
        )

        blocksBefore = copy.copy(itemsEm.blocks)
        childrenBefore = copy.copy(itemsEm.children)

        gotException = False
        try:
            itemsEm.insertBefore(newItem, parser.getElementById('outer'))
        except ValueError:
            gotException = True
        except Exception as otherExc:
            exc_info = sys.exc_info()
            traceback.print_exception(*exc_info)

            raise AssertionError('Expected insertBefore to raise ValueError if I try to insert before an item that does not exist.')

        assert gotException , 'Expected to get ValueError trying to insert before an element not contained within the node'

        assert blocksBefore == itemsEm.blocks , 'Expected blocks to NOT be changed on insertBefore error case'
        assert childrenBefore == itemsEm.children , 'Expected children to NOT be changed on insertBefore error case'


        ret = itemsEm.insertBefore(newItem, itemsEm.getElementById('item2'))
        assert ret == newItem , 'Expected insertBefore to return the added element'

        childIds = [x.id for x in itemsEm.getElementsByName('item')]

        assert childIds == ['item1', 'item1point5', 'item2'] , 'Expected items to be ordered. Got: %s' %(str(childIds,))
        newItem =  AdvancedTag('div')


        newItem.setAttributes( {
            'name' : 'item',
            'id' : 'item3'
            }
        )

        # test None as before item inserts at end
        itemsEm.insertBefore(newItem, None)
        childIds = [x.id for x in itemsEm.getElementsByName('item')]

        assert childIds == ['item1', 'item1point5', 'item2', 'item3'] , 'Expected items to be ordered. Got: %s' %(str(childIds,))
        newItem =  AdvancedTag('div')
Ejemplo n.º 17
0
    def test_classListCopy(self):
        '''
            test_classListCopy - Test that changing the list returned from .classList
                    does NOT affect the class attributes on a node (same as JS).
        '''

        tag = AdvancedTag('div')

        tag.className = "hello world"

        classList = tag.classList

        classList.append('xxx')

        assert 'xxx' not in tag.className, 'Expected .classList return to be independent of source tag, but changing affected className attribute'

        assert 'class="hello world"' in str(
            tag
        ), 'Expected .classList return to be independent of source tag, but changing affected class in HTML representation'

        assert tag.classList == [
            'hello', 'world'
        ], 'Expected .classList return to be independent of source tag, but changing affected return of .classList'
Ejemplo n.º 18
0
    def test_specialAttributes(self):
        tag = AdvancedTag('div')
        tag.setAttribute('style', 'position: absolute')
        styleValue = str(tag.getAttribute('style'))
        styleValue = styleValue.strip()
        assert styleValue == 'position: absolute' , 'Expected position: absolute, got %s' %(str(tag.getAttribute('style')),)

        tag.setAttribute('className', 'one two')
        assert str(tag.className).strip() == 'one two' , 'Expected classname to be "one two", got %s' %(repr(str(tag.className).strip()),)
Ejemplo n.º 19
0
    def test_colsAttribute(self):
        '''
            test_colsAttribute - Tests the "cols" attribute

                NOTE: This differs in behaviour between a textarea and a frameset
        '''

        textareaEm = AdvancedTag('textarea')

        assert textareaEm.cols == 20, 'Expected default "cols" for textarea to be 20, but got: ' + repr(
            textareaEm.cols)

        textareaEm.cols = 100

        assert textareaEm.cols == 100, 'Expected to be able to set "cols" to 100 and that value stick, but got: ' + repr(
            textareaEm.cols)

        textareaEmHTML = str(textareaEm)

        assert 'cols="100"' in textareaEmHTML, 'Expected to find "cols" attribute set to "100" in HTML, but got: ' + repr(
            textareaEmHTML)

        textareaEm.cols = 0

        assert textareaEm.cols == 20, 'Expected an invalid value in "cols" attribute on textarea to return 20, but got: ' + repr(
            textareaEm.cols)

        framesetEm = AdvancedTag('frameset')

        assert framesetEm.cols == '', 'Expected "cols" attribute on frameset to default to empty string, but got: ' + repr(
            framesetEm.cols)

        framesetEm.cols = "5"

        assert framesetEm.cols == "5", 'Expected to be able to set "cols" attribute to "5" and it apply, but got: ' + repr(
            framesetEm.cols)

        framesetEmHTML = str(framesetEm)

        assert 'cols="5"' in framesetEmHTML, 'Expected "cols" attribute to be set to "5" in HTML representation, but got: ' + repr(
            framesetEmHTML)

        framesetEm.cols = "bologna"

        assert framesetEm.cols == "bologna", 'Expected to be able to set "cols" to any string, set to "bologna" but got back: ' + repr(
            framesetEm.cols)
Ejemplo n.º 20
0
    def test_crossOrigin(self):
        '''
            test crossOrigin attribute
        '''

        img = AdvancedTag('img')

        assert img.crossOrigin is None, 'Default for crossOrigin (never set) should be None (null). Got: ' + repr(
            img.crossOrigin)

        img.crossOrigin = 'blah'

        assert img.crossOrigin == 'anonymous', 'Default dot-access value for invalid crossOrigin should be "anonymous". Got: ' + repr(
            img.crossOrigin)

        imgHTML = str(img)

        assert 'crossorigin' in imgHTML, 'Expected "crossOrigin" to be converted to "crossorigin" in HTML. Got: ' + imgHTML

        assert 'crossorigin="blah"' in imgHTML, 'Expected whatever was set via img.crossOrigin = "blah" to show up in html text, even though the dot-access variable is different. Got: ' + imgHTML

        img.crossOrigin = 'use-credentials'
        imgHTML = str(img)

        assert img.crossOrigin == 'use-credentials', 'Expected "use-credentials" value to be retained for crossOrigin. Got: ' + repr(
            img.crossOrigin)

        assert 'crossorigin="use-credentials"' in imgHTML, 'Expected crossorigin="use-credentials" to be retained in HTML. Got: ' + imgHTML

        img.crossOrigin = 'anonymous'
        imgHTML = str(img)

        assert img.crossOrigin == 'anonymous', 'Expected "anonymous" value to be retained for crossOrigin. Got: ' + repr(
            img.crossOrigin)

        assert 'crossorigin="anonymous"' in imgHTML, 'Expected crossorigin="anonymous" to be retained in HTML. Got: ' + imgHTML
Ejemplo n.º 21
0
    def test_setAttributes(self):
        tag = AdvancedTag('div')
        tag.setAttributes( {
            'id' : 'abc',
            'name'  :  'cheese',
            'x-attr' : 'bazing'
        })

        assert tag.getAttribute('id') == 'abc'
        assert tag.getAttribute('name') == 'cheese'
        assert tag.getAttribute('x-attr') == 'bazing'
Ejemplo n.º 22
0
    def test_setRoot(self):
        parser = AdvancedHTMLParser()
        assert not parser.root, 'Root should start blank'

        root = AdvancedTag('html')
        parser.setRoot(root)

        assert parser.root, 'Expected root to be set'
        assert parser.root.tagName == 'html', 'Expected root node to be tagName=html'

        parser.reset()

        assert not parser.root, 'Expected parser root to be blank after reset is called'

        parser.parseStr(root.outerHTML)
        root = parser.getRoot()

        assert parser.root, 'Expected root to be set'
        assert parser.root.tagName == 'html', 'Expected root node to be tagName=html'
    def test_inputAutocomplete(self):
        '''
            test input autocomplete attribute
        '''

        inputEm = AdvancedTag('input')

        assert inputEm.autocomplete == '', 'Expected default for unset "autocomplete" to be "". Got: ' + repr(
            inputEm.autocomplete)

        inputEm.autocomplete = 'on'
        inputHTML = str(inputEm)

        assert inputEm.autocomplete == 'on', 'Expected autocomplete="on" to retain on. Got: ' + repr(
            inputEm.autocomplete)

        assert inputEm.getAttribute(
            'autocomplete'
        ) == 'on', 'Expected getAttribute to return the value on a binary attribute when provided'

        assert 'autocomplete="on"' in inputHTML, 'Expected html property to be set. Got: ' + repr(
            inputHTML)

        inputEm.autocomplete = 'blah'

        assert inputEm.autocomplete == '', 'Expected autocomplete="blah" to use invalid fallback of "". Got: ' + repr(
            inputEm.autocomplete)

        inputEm.autocomplete = 'off'
        inputHTML = str(inputEm)

        assert inputEm.autocomplete == 'off', 'Expected to be able to switch autocomplete to off. Got: ' + repr(
            inputEm.autocomplete)

        assert 'autocomplete="off"' in inputHTML, 'Expected html property to be set. Got: ' + repr(
            inputHTML)

        inputEm.autocomplete = ''
        inputHTML = str(inputEm)

        assert inputEm.autocomplete == '', 'Expected to be able to set autocomplete to empty string. Got: ' + repr(
            inputEm.autocomplete)

        assert 'autocomplete=""' in inputHTML, 'Expected html property to be set to empty string. Got: ' + repr(
            inputHTML)
Ejemplo n.º 24
0
    def test_specialAttributes(self):
        tag = AdvancedTag('div')

        assert tag.spellcheck is False, 'Expected default value of "spellcheck" field via dot-access to be False'
        assert 'spellcheck' not in str(
            tag
        ), 'Expected "spellcheck" to not show up in HTML representation before set. Got: ' + str(
            tag)

        tag.spellcheck = True

        assert tag.spellcheck is True, 'Expected after setting spellcheck to True, dot-access returns True.'

        tagHTML = str(tag)

        assert 'spellcheck="true"' in tagHTML, "Expected spellcheck to have value of string 'true' in HTML representation. Got: " + tagHTML

        tag.spellcheck = False
        tagHTML = str(tag)

        assert tag.spellcheck is False, 'Expected spellcheck to have dot-access value of False after being set to False. Got: ' + repr(
            tag.spellcheck)
        assert 'spellcheck="false"' in tagHTML, "Expected spellcheck to have value of string 'false' in HTML representation after being set to False. Got: " + tagHTML
        assert tag.getAttribute(
            'spellcheck'
        ) == 'false', 'Expected getAttribute("spellcheck") to return string "false" in HTML representation. Got: ' + repr(
            tag.getAttribute('spellcheck'))

        tag.spellcheck = "yes"

        assert tag.spellcheck is True, 'Expected after setting spellcheck to "yes", dot-access reutrns True. Got: ' + repr(
            tag.spellcheck)
        tagHTML = str(tag)

        assert 'spellcheck="true"' in tagHTML, "Expected spellcheck to have value of string 'true' in HTML representation after being set to 'yes'. Got: " + tagHTML

        assert tag.getAttribute(
            'spellcheck'
        ) == "true", "Expected getAttribute('spellcheck') to return string of True"
Ejemplo n.º 25
0
    def test_formMethod(self):
        '''
            test the form's "method" attribute
        '''

        formEm = AdvancedTag('form')

        assert formEm.method == 'get', 'Expected default for form.method to be "get". Got: ' + repr(
            formEm.method)

        formEm.method = 'get'

        assert formEm.method == 'get', 'Expected to be able to set form.method to "get". Got: ' + repr(
            formEm.method)

        formHTML = str(formEm)

        assert 'method="get"' in formHTML, 'Expected html attribute method to be set in html representation. Got: ' + repr(
            formHTML)

        formEm.method = 'post'
        formHTML = str(formEm)

        assert formEm.method == 'post', 'Expected to be able to set form.method to "post". Got: ' + repr(
            formEm.method)

        assert 'method="post"' in formHTML, 'Expected html attribute method to be set in html representation. Got: ' + repr(
            formHTML)

        formEm.method = 'POST'
        formHTML = str(formEm)

        assert formEm.method == 'post', 'Expected to be able to set form.method to "POST" and it be converted to lowercase for dot-access. Got: ' + repr(
            formEm.method)

        assert 'method="POST"' in formHTML, 'Expected html attribute method to be set in html representation as given (i.e. not lowercased). Got: ' + repr(
            formHTML)

        # NOTE: This is strange, but it is the behaviour as the w3 spec only allows "post" or "get" to be values,
        #         even though other methods exist.
        formEm.method = 'put'
        formHTML = str(formEm)

        assert formEm.method == 'get', 'Expected dot-access to only support "get" and "post", and default to "get" for invalid values. Got: ' + repr(
            formEm.method)

        assert 'method="put"' in formHTML, 'Expected html representation to have the value as provided, even though dot-access returns a different value. Got: ' + repr(
            formHTML)
Ejemplo n.º 26
0
    def test_multipleRoot(self):
        parser = AdvancedHTMLParser()

        root1 =  AdvancedTag('div')
        root1.setAttribute('id', 'div1')

        root2 = AdvancedTag('div')
        root2.setAttribute('id', 'div2')

        parser.parseStr(root1.outerHTML + root2.outerHTML)

        assert len(parser.getRootNodes()) == 2, 'Expected two root nodes on tree'

        foundRoot1 = parser.getElementById('div1')
        assert foundRoot1, 'Expected to find id=div1 in multi-root tree'

        foundRoot2 = parser.getElementById('div2')
        assert foundRoot2, 'Expected to find id=div1 in multi-root tree'

        combinedHTML = (foundRoot1.outerHTML + foundRoot2.outerHTML).replace('\n', '').strip()
        parsedHTML = parser.getHTML().replace('\n', '').strip()

        assert combinedHTML == parsedHTML, 'Expected single element outerHTMLs to match parser HTML. """\n%s\n""" != """\n%s\n"""' %(combinedHTML, parsedHTML)
Ejemplo n.º 27
0
    def test_setAttributesOnItem(self):
        tag = AdvancedTag('div')

        tag.id = 'hello'

        assert tag.id == 'hello', 'Expected to be able to set special attribute "id" and have it show up as both attribute and on item'
        assert tag.getAttribute(
            'id', ''
        ) == 'hello', 'Expected to be able to set special attribute "id" and have it show up as both attribute and on item'

        tag.name = 'cheese'

        assert tag.name == 'cheese', 'Expected to be able to set special attribute "name" and have it show up as both attribute and on item'
        assert tag.getAttribute(
            'name', ''
        ) == 'cheese', 'Expected to be able to set special attribute "name" and have it show up as both attribute and on item'

        assert tag.tabIndex == -1, 'Expected default tab index (unset) to be -1'

        tag.tabIndex = 5

        assert 'tabindex="5"' in tag.outerHTML, 'Expected setting the tabIndex to set tabindex attribute on html'
Ejemplo n.º 28
0
    def test_formAutocomplete(self):
        '''
            test form autocomplete attribute
        '''

        formEm = AdvancedTag('form')

        assert formEm.autocomplete == 'on', 'Expected default for unset "autocomplete" to be "on". Got: ' + repr(
            formEm.autocomplete)

        formEm.autocomplete = 'on'
        formHTML = str(formEm)

        assert formEm.autocomplete == 'on', 'Expected autocomplete="on" to retain on. Got: ' + repr(
            formEm.autocomplete)

        assert 'autocomplete="on"' in formHTML, 'Expected html property to be set. Got: ' + repr(
            formHTML)

        formEm.autocomplete = 'blah'

        assert formEm.autocomplete == 'on', 'Expected autocomplete="blah" to use invalid fallback of "on". Got: ' + repr(
            formEm.autocomplete)

        formEm.autocomplete = 'off'
        formHTML = str(formEm)

        assert formEm.autocomplete == 'off', 'Expected to be able to switch autocomplete to off. Got: ' + repr(
            formEm.autocomplete)

        assert 'autocomplete="off"' in formHTML, 'Expected html property to be set. Got: ' + repr(
            formHTML)

        formEm.autocomplete = ''
        formHTML = str(formEm)

        assert formEm.autocomplete == 'on', 'Expected setting autocomplete to empty string to revert to invalid, "on". Got: ' + repr(
            formEm.autocomplete)

        assert 'autocomplete=""' in formHTML, 'Expected html property to be set to empty string. Got: ' + repr(
            formHTML)
Ejemplo n.º 29
0
    def test_attributesCase(self):
        '''
            test_attributesCase - Test that getAttribute and setAttribute force lowercase for keys
        '''

        em = AdvancedTag('input')

        em.setAttribute('MaXlEnGtH', '5')

        html = str(em)

        assert 'maxlength="5"' in html, 'Expected setAttribute to lowercase the key before setting. Got: ' + html

        assert em.getAttribute(
            'MAXlength', None
        ) == '5', 'Expected getAttribute to lowercase the key before setting.'

        assert em.hasAttribute(
            'maXlenGTH') is True, 'Expected hasAttribute to lowercase the key'

        assert 'MaxLength' in em.attributes, 'Expected "in" operator to lowercase the key'
Ejemplo n.º 30
0
    def test_multipleRoot(self):
        parser = AdvancedHTMLParser()

        root1 =  AdvancedTag('div')
        root1.setAttribute('id', 'div1')

        root2 = AdvancedTag('div')
        root2.setAttribute('id', 'div2')

        parser.parseStr(root1.outerHTML + root2.outerHTML)

        assert len(parser.getRootNodes()) == 2, 'Expected two root nodes on tree'

        foundRoot1 = parser.getElementById('div1')
        assert foundRoot1, 'Expected to find id=div1 in multi-root tree'

        foundRoot2 = parser.getElementById('div2')
        assert foundRoot2, 'Expected to find id=div1 in multi-root tree'

        combinedHTML = (foundRoot1.outerHTML + foundRoot2.outerHTML).replace('\n', '').strip()
        parsedHTML = parser.getHTML().replace('\n', '').strip()

        assert combinedHTML == parsedHTML, 'Expected single element outerHTMLs to match parser HTML. """\n%s\n""" != """\n%s\n"""' %(combinedHTML, parsedHTML)
Ejemplo n.º 31
0
    def test_tagOperators(self):

        parser = AdvancedHTMLParser()
        parser.parseStr('''<html> <body>
        <div id="hello"  class="classX classY" cheese="cheddar" > <span>Child</span><span>Other Child</span> </div>
        <div id="hello2" class="classX classY" cheese="cheddar" > <span>Child</span><span>Other Child</span> </div>
        <div id="goodbye" one="1"> Yay </div>

        <div id="sameAttrChildren">
          <div class="classX classY" cheese="gouda">Blah</div>
          <div class="classX classY" cheese="gouda">Blah</div>
        </div>
</body></html>''')

        helloTag = parser.getElementById('hello')
        assert helloTag, 'Expected to fetch tag with id="hello" but failed.'

        hello2Tag = parser.getElementById('hello2')
        assert hello2Tag, 'Expected to fetch tag with id="hello2" but failed.'

        goodbyeTag = parser.getElementById('goodbye')
        assert goodbyeTag, 'Expected to fetch tag with id="goodbye" but failed.'

        tagsEq = (helloTag == hello2Tag)

        assert tagsEq is False, "Expected different tags with same attributes names to not be =="

        tagsNe = (helloTag != hello2Tag)

        assert tagsNe is True, "Expected different tags with same attributes names to be !="

        sameTagEq = (helloTag == helloTag)

        assert sameTagEq is True, "Expected same tag to == itself"

        diffTagsEq = (helloTag == goodbyeTag)

        assert diffTagsEq is False, "Expected different tags with different attributes to not be =="

        diffTagsNe = (helloTag != goodbyeTag)

        assert diffTagsNe is True, "Expected different tags with different attributes to be !="

        helloTagCopy = copy.copy(helloTag)

        copyEq = (helloTag == helloTagCopy)

        assert copyEq is False, "Expected copy of tag to not == original"

        copyNe = (helloTag != helloTagCopy)

        assert copyNe is True, "Expected copy of tag to != original"

        helloTagCopyRecon = AdvancedTag(helloTag.tagName,
                                        helloTag.getAttributesList(),
                                        helloTag.isSelfClosing)

        copyEq = (helloTag == helloTagCopyRecon)

        assert copyEq is False, "Expected reconstruction of tag to not == original"

        copyNe = (helloTag != helloTagCopyRecon)

        assert copyNe is True, "Expected reconstruction of tag to != original"

        helloTagFetch2 = parser.getElementById('hello')

        fetchEq = (helloTag == helloTagFetch2)

        assert fetchEq is True, "Expected fetching the same tag is =="

        fetchNe = (helloTag != helloTagFetch2)

        assert fetchNe is False, "Expected fetching the same tag to not be !="

        sameAttrChildrenEm = parser.getElementById('sameAttrChildren')

        child1 = sameAttrChildrenEm.children[0]
        child2 = sameAttrChildrenEm.children[1]

        childrenEq = (child1 == child2)

        assert childrenEq is False, "Expected elements with exact same attributes and values but different individual tags to not be =="

        childrenNe = (child1 != child2)

        assert childrenNe is True, "Expected elements with exact same attributes and values but different individual tags to be !="
Ejemplo n.º 32
0
    def test_setClassNameString(self):
        '''
            test_setClassNameString - Test setting the "className" attribute on an AdvancedTag and it being reflected.
        '''

        tag = AdvancedTag('div')

        assert "class=" not in tag.getHTML(
        ), "Expected to not find 'class=' when none is set. Got: " + tag.getHTML(
        )

        assert 'class' not in tag.attributes, 'Expected "class" to not be "in" attributes'

        # Try initial set

        tag.className = "cheese is good"

        assert 'class' in tag.attributes, 'Expected "class" to be "in" attributes'

        assert tag.className == "cheese is good", "Expected className to equal 'cheese is good' after assign on className attribute. Got: " + repr(
            tag.className)

        assert 'class="cheese is good"' in str(
            tag
        ), "Expected to find class=\"cheese is good\" after set on className attribute. Got: " + str(
            tag)

        assert tag.classList == [
            'cheese', 'is', 'good'
        ], "Expected classList to be set after setting on className attribute. Got: " + repr(
            tag.classList)

        assert 'class' in tag.attributes.keys(
        ), 'Expected "class" to be in .keys()'

        # Try changing

        tag.className = "hello world"

        assert tag.className == "hello world", "Expected to be able to change className attribute. Got: " + repr(
            tag.className)

        assert 'class="hello world"' in str(
            tag
        ), "Expected to be able to change className and have it show up in html attribute. Got: " + str(
            tag)

        assert tag.classList == [
            'hello', 'world'
        ], "Expected to be able to change className attribute, but update not reflected in classList. Got: " + repr(
            tag.classList)

        # Try removing

        tag.className = ''

        assert tag.className == '', "Expected to be able to clear className attribute. Got: " + repr(
            tag.className)

        assert "class=" not in str(
            tag
        ), "Expected class attribute to not be on HTML representation after clearing className. Got: " + str(
            tag)

        assert tag.classList == [], "Expected to be able to clear className attribute, but did not update classList to empty list. Got: " + repr(
            tag.classList)
Ejemplo n.º 33
0
    def test_tagClassMethods(self):
        '''
            test_tagClassMethods - test class methods like addClass, removeClass, hasClass
        '''

        tag = AdvancedTag('div')

        ret = tag.removeClass('blah')
        assert ret is None, "Expected to get None from tag.removeClass trying to remove non-existant class. Got: " + repr(
            ret)

        # Set initial classes
        tag.className = "hello world"

        # Add a class
        tag.addClass("welcome")

        assert 'class="hello world welcome"' in str(
            tag
        ), "Expected addClass to add class, but did not change HTML representation. Got: " + str(
            tag)

        assert tag.className == "hello world welcome", "Expected addClass to add class, but did not change className property. Got: " + repr(
            tag.className)

        assert tag.classList == [
            'hello', 'world', 'welcome'
        ], "Expected addClass to add class, but did not return expected ordered classList. Got: " + repr(
            tag.classList)

        assert tag.hasClass(
            "hello"), "Expected hasClass('hello') to return True."
        assert tag.hasClass(
            "world"), "Expected hasClass('world') to return True."
        assert tag.hasClass(
            "welcome"), "Expected hasClass('welcome') to return True."
        assert not tag.hasClass(
            "blah"), "Expected hasClass('blah') to return False."

        # Remove middle class

        tag.removeClass("world")

        assert 'class="hello welcome"' in str(
            tag
        ), "Expected removeClass to remove class, but did not change HTML representation. Got: " + str(
            tag)

        assert tag.className == "hello welcome", "Expected removeClass to remove class, but did not change className property. Got: " + repr(
            tag.className)

        assert tag.classList == [
            "hello", "welcome"
        ], "Expected removeClass to remove class, but did get expected classList. Got: " + repr(
            tag.classList)

        # Try to add a duplicate class

        tag.addClass("hello")
        assert 'class="hello welcome"' in str(
            tag
        ), "Expected addClass to not add duplicate class, but changed HTML representation. Got: " + str(
            tag)

        assert tag.className == "hello welcome", "Expected addClass to not add duplicate class, but changed className property. Got: " + repr(
            tag.className)

        assert tag.classList == [
            'hello', 'welcome'
        ], "Expected addClass to not add duplicate class, but did not return expected ordered classList. Got: " + repr(
            tag.classList)
Ejemplo n.º 34
0
    def test_stripClassName(self):
        '''
            test_stripClassName - Ensure class names are properly stripped
        '''
        x = AdvancedTag('div')

        x.addClass("  hello")

        assert x.className == "hello", "Expected className to be stripped after addClass. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello"
        ], "Expected 'class' to be stripped in 'classList' after addClass. Got: " + repr(
            x.classList)

        x = AdvancedTag('div')

        x.className = "  hello   goodbye"

        assert x.className == "hello goodbye", "Expected className to be stripped after setting .className. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected className to be stripped and empty strings removed on classList. Got: " + repr(
            x.classList)

        x.addClass("hello  ")

        assert x.className == "hello goodbye", "Expected addClass to strip class name before trying to add so as to not duplicate. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected addClass to strip class name before trying to add so as to not duplicate. Got: " + repr(
            x.classList)

        x.addClass("")

        assert x.className == "hello goodbye", "Expected addClass on empty string to not affect className. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected addClass on empty string to not affect classList. Got: " + repr(
            x.classList)

        x.addClass("  ")

        assert x.className == "hello goodbye", "Expected addClass on whitespace string to not affect className. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected addClass on whitespace string to not affect classList. Got: " + repr(
            x.classList)

        x.removeClass("")

        assert x.className == "hello goodbye", "Expected removeClass on empty string to not affect className. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected removeClass on empty string to not affect classList. Got: " + repr(
            x.classList)

        x.removeClass(" ")

        assert x.className == "hello goodbye", "Expected removeClass on whitespace string to not affect className. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected removeClass on whitespace string to not affect classList. Got: " + repr(
            x.classList)

        x = AdvancedTag('div')

        x.className = "hello   goodbye  "

        assert x.className == "hello goodbye", "Expected setting class with extra whitespace to have extra whitespace stripped. className attribute not as expected. Got: " + repr(
            x.className)

        assert x.classList == [
            "hello", "goodbye"
        ], "Expected setting class with extra whitespace to have extra whitespace stripped. classList not as expected. Got: " + repr(
            x.className)

        x.addClass('cheddar butter')

        assert x.className == 'hello goodbye cheddar butter', 'Expected tag.addClass("cheddar butter") to add both "cheddar" and "butter" classes, but .className attribute only shows: ' + repr(
            x.className)

        assert x.classList == [
            'hello', 'goodbye', 'cheddar', 'butter'
        ], 'Expected tag.addClass("cheddar butter") to add both "cheddar" and "butter" classes, but .classList attribute only shows: ' + repr(
            x.classList)

        x.removeClass("   hello    cheddar ")

        assert x.className == "goodbye butter", "Expected tag.removeClass('   hello    cheddar ') to split and strip and remove both 'hello' and 'cheddar' classes. className only shows: " + repr(
            x.className)

        assert x.classList == [
            "goodbye", "butter"
        ], "Expected tag.removeClass('   hello    cheddar ') to split and strip and remove both 'hello' and 'cheddar' classes. classList only shows: " + repr(
            x.classList)
Ejemplo n.º 35
0
    def test_stripClassName(self):
        '''
            test_stripClassName - Ensure class names are properly stripped
        '''
        x = AdvancedTag('div')

        x.addClass("  hello")

        assert x.className == "hello" , "Expected className to be stripped after addClass. Got: " + repr(x.className)

        assert x.classList == ["hello"] , "Expected 'class' to be stripped in 'classList' after addClass. Got: " + repr(x.classList)


        x = AdvancedTag('div')

        x.className = "  hello   goodbye"

        assert x.className == "hello goodbye" , "Expected className to be stripped after setting .className. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"] , "Expected className to be stripped and empty strings removed on classList. Got: " + repr(x.classList)


        x.addClass("hello  ")

        assert x.className == "hello goodbye" , "Expected addClass to strip class name before trying to add so as to not duplicate. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"] , "Expected addClass to strip class name before trying to add so as to not duplicate. Got: " + repr(x.classList)


        x.addClass("")

        assert x.className == "hello goodbye" , "Expected addClass on empty string to not affect className. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"], "Expected addClass on empty string to not affect classList. Got: " + repr(x.classList)

        x.addClass("  ")

        assert x.className == "hello goodbye" , "Expected addClass on whitespace string to not affect className. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"], "Expected addClass on whitespace string to not affect classList. Got: " + repr(x.classList)

        x.removeClass("")

        assert x.className == "hello goodbye" , "Expected removeClass on empty string to not affect className. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"], "Expected removeClass on empty string to not affect classList. Got: " + repr(x.classList)

        x.removeClass(" ")

        assert x.className == "hello goodbye" , "Expected removeClass on whitespace string to not affect className. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"], "Expected removeClass on whitespace string to not affect classList. Got: " + repr(x.classList)

        x = AdvancedTag('div')

        x.className = "hello   goodbye  "

        assert x.className == "hello goodbye" , "Expected setting class with extra whitespace to have extra whitespace stripped. className attribute not as expected. Got: " + repr(x.className)

        assert x.classList == ["hello", "goodbye"], "Expected setting class with extra whitespace to have extra whitespace stripped. classList not as expected. Got: " + repr(x.className)

        x.addClass('cheddar butter')

        assert x.className == 'hello goodbye cheddar butter' , 'Expected tag.addClass("cheddar butter") to add both "cheddar" and "butter" classes, but .className attribute only shows: ' + repr(x.className)

        assert x.classList == ['hello', 'goodbye', 'cheddar', 'butter'] , 'Expected tag.addClass("cheddar butter") to add both "cheddar" and "butter" classes, but .classList attribute only shows: ' + repr(x.classList)


        x.removeClass("   hello    cheddar ")

        assert x.className == "goodbye butter" , "Expected tag.removeClass('   hello    cheddar ') to split and strip and remove both 'hello' and 'cheddar' classes. className only shows: " + repr(x.className)

        assert x.classList == ["goodbye", "butter"] , "Expected tag.removeClass('   hello    cheddar ') to split and strip and remove both 'hello' and 'cheddar' classes. classList only shows: " + repr(x.classList)
Ejemplo n.º 36
0
    def test_setClassNameSetAttribute(self):
        '''
            test_setClassNameSetAttribute - Test setting/changing/removing the class attribute using setAttribute and friends.
        '''
        tag = AdvancedTag('div')

        assert "class=" not in tag.getHTML(
        ), "Expected to not find 'class=' when none is set. Got: " + tag.getHTML(
        )

        # Try initial set

        tag.setAttribute("class", "cheese is good")

        assert tag.className == "cheese is good", "Expected className to equal 'cheese is good' after setAttribute('class', ...). Got: " + repr(
            tag.className)

        assert 'class="cheese is good"' in str(
            tag
        ), "Expected to find class=\"cheese is good\" after setAttribute('class', ...). Got: " + str(
            tag)

        assert tag.classList == [
            'cheese', 'is', 'good'
        ], "Expected classList to be set after setAttribute('class', ...). Got: " + repr(
            tag.classList)

        # Try changing

        tag.setAttribute("class", "hello world")

        assert tag.className == "hello world", "Expected to be able to change class using setAttribute('class', ...). Got: " + repr(
            tag.className)

        assert 'class="hello world"' in str(
            tag
        ), "Expected to be able to change class using setAttribute('class', ...)  and have it show up in html attribute. Got: " + str(
            tag)

        assert tag.classList == [
            'hello', 'world'
        ], "Expected to be able to change class using setAttribute('class', ...), but update not reflected in classList. Got: " + repr(
            tag.classList)

        # Try removing, both through removeAttribute and setAttribute('class', '')

        tag1 = tag.cloneNode()

        tag2 = tag.cloneNode()

        tag1.removeAttribute('class')

        assert tag1.className == '', "Expected to be able to clear class attribute using removeAttribute. Got: " + repr(
            tag1.className)

        assert "class=" not in str(
            tag1
        ), "Expected class attribute to not be on HTML representation after removeAttribute. Got: " + str(
            tag1)

        assert tag1.classList == [], "Expected to be able to clear class attribut with removeAttributee, but did not update classList to empty list. Got: " + repr(
            tag1.classList)

        # Ensure cloneNode unlinked class attribute
        assert tag2.className == 'hello world', 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). className was effected.'
        assert tag2.classList == [
            'hello', 'world'
        ], 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). classList was effected.'
        assert 'class="hello world"' in str(
            tag2
        ), 'Expected clearing tag1 (cloned node of tag) to not affect tag2 (another cloned node of tag). class on string of html was effected.'

        tag2.setAttribute('class', '')

        assert tag2.className == '', "Expected to be able to clear class attribute using setAttribute('class', ''). Got: " + repr(
            tag2.className)

        assert "class=" not in str(
            tag2
        ), "Expected class attribute to not be on HTML representation after setAttribute('class', ''). Got: " + str(
            tag2)

        assert tag2.classList == [], "Expected to be able to clear class attribut with setAttribute('class', '')e, but did not update classList to empty list. Got: " + repr(
            tag2.classList)
Ejemplo n.º 37
0
    def test_tagClassMethods(self):
        '''
            test_tagClassMethods - test class methods like addClass, removeClass, hasClass
        '''

        tag = AdvancedTag('div')

        ret = tag.removeClass('blah')
        assert ret is None , "Expected to get None from tag.removeClass trying to remove non-existant class. Got: " + repr(ret)

        # Set initial classes
        tag.className = "hello world"

        # Add a class
        tag.addClass("welcome")

        assert 'class="hello world welcome"' in str(tag) , "Expected addClass to add class, but did not change HTML representation. Got: " + str(tag)

        assert tag.className == "hello world welcome" , "Expected addClass to add class, but did not change className property. Got: " + repr(tag.className)

        assert tag.classList == ['hello', 'world', 'welcome'] , "Expected addClass to add class, but did not return expected ordered classList. Got: " + repr(tag.classList)

        assert tag.hasClass("hello") , "Expected hasClass('hello') to return True."
        assert tag.hasClass("world") , "Expected hasClass('world') to return True."
        assert tag.hasClass("welcome") , "Expected hasClass('welcome') to return True."
        assert not tag.hasClass("blah") , "Expected hasClass('blah') to return False."


        # Remove middle class

        tag.removeClass("world")

        assert 'class="hello welcome"' in str(tag) , "Expected removeClass to remove class, but did not change HTML representation. Got: " + str(tag)

        assert tag.className == "hello welcome" , "Expected removeClass to remove class, but did not change className property. Got: " + repr(tag.className)

        assert tag.classList == ["hello", "welcome" ], "Expected removeClass to remove class, but did get expected classList. Got: " + repr(tag.classList)


        # Try to add a duplicate class

        tag.addClass("hello")
        assert 'class="hello welcome"' in str(tag) , "Expected addClass to not add duplicate class, but changed HTML representation. Got: " + str(tag)

        assert tag.className == "hello welcome" , "Expected addClass to not add duplicate class, but changed className property. Got: " + repr(tag.className)

        assert tag.classList == ['hello', 'welcome' ] , "Expected addClass to not add duplicate class, but did not return expected ordered classList. Got: " + repr(tag.classList)
Ejemplo n.º 38
0
    def test_classNames(self):
        tag = AdvancedTag('div')
        tag.addClass('abc')

        assert tag.hasClass('abc'), 'Failed to add class'
        assert 'abc' in tag.outerHTML , 'Failed to add class in outerHTML'

        tag.addClass('def')

        assert tag.hasClass('abc'), 'Failed to retain class'
        assert 'abc' in tag.outerHTML , ' Failed to retain in outerHTML'

        assert tag.hasClass('def'), 'Failed to add second class'
        assert 'def' in tag.outerHTML , ' Failed to add to outerHTML'

        tag.removeClass('abc')
        assert not tag.hasClass('abc'), 'Failed to remove class'
        assert 'abc' not in tag.outerHTML , 'Failed to remove class from outerHTML'

        assert tag.hasClass('def'), 'Failed to retain class'
        assert 'def' in tag.outerHTML , ' Failed to retain in outerHTML'
Ejemplo n.º 39
0
    def test_iframeSandbox(self):
        '''
            Test iframe's "sandbox" attribute
        '''
        from AdvancedHTMLParser.SpecialAttributes import DOMTokenList

        iframeEm = AdvancedTag('iframe')

        assert isinstance(
            iframeEm.sandbox, DOMTokenList
        ), 'Expected iframe.sandbox to be a "DOMTokenList", but got: ' + str(
            iframeEm.sandbox.__class__.__name__)

        iframeEm.sandbox = ''

        sandbox = iframeEm.sandbox

        assert isinstance(
            sandbox, DOMTokenList
        ), 'Expected after setting iframe.sandbox = "" to retain a DOMTokenList on access, but got: ' + str(
            iframeEm.sandbox.__class__.__name__)

        assert len(
            sandbox
        ) == 0, 'Expected to have no elements after setting to empty string, but got: ' + repr(
            sandbox)

        iframeEm.sandbox = 'one two three'

        sandbox = iframeEm.sandbox
        assert isinstance(
            sandbox, DOMTokenList
        ), 'Expected after setting iframe.sandbox = "one two three" to retain a DOMTokenList on access, but got: ' + str(
            iframeEm.sandbox.__class__.__name__)

        assert len(
            sandbox
        ) == 3, 'Expected to have 3 elements in sandbox. Got: ' + repr(sandbox)

        assert sandbox[
            0] == 'one', 'Expected first element to be "one". Got: ' + repr(
                sandbox[0])
        assert sandbox[
            1] == 'two', 'Expected second element to be "two". Got: ' + repr(
                sandbox[1])
        assert sandbox[
            2] == 'three', 'Expected third element to be "third". Got: ' + repr(
                sandbox[2])

        assert str(
            sandbox
        ) == 'one two three', 'Expected str of sandbox attr to be "one two three". Got: ' + repr(
            str(sandbox))

        iframeEmHTML = str(iframeEm)

        assert 'sandbox="one two three"' in iframeEmHTML, 'Expected sandbox="one two three" to be in HTML, but got: ' + iframeEmHTML

        sandbox.append('Hello')

        assert len(
            iframeEm.sandbox
        ) == 3, 'Expected appending to the DOMTokenList returned to have no effect.'
Ejemplo n.º 40
0
    def test_classNames(self):
        tag = AdvancedTag('div')
        tag.addClass('abc')

        assert tag.hasClass('abc'), 'Failed to add class'
        assert 'abc' in tag.outerHTML, 'Failed to add class in outerHTML'

        tag.addClass('def')

        assert tag.hasClass('abc'), 'Failed to retain class'
        assert 'abc' in tag.outerHTML, ' Failed to retain in outerHTML'

        assert tag.hasClass('def'), 'Failed to add second class'
        assert 'def' in tag.outerHTML, ' Failed to add to outerHTML'

        tag.removeClass('abc')
        assert not tag.hasClass('abc'), 'Failed to remove class'
        assert 'abc' not in tag.outerHTML, 'Failed to remove class from outerHTML'

        assert tag.hasClass('def'), 'Failed to retain class'
        assert 'def' in tag.outerHTML, ' Failed to retain in outerHTML'
Ejemplo n.º 41
0
    def test_removeAttribute(self):
        '''
            test_removeAttribute - Test removing attributes
        '''

        tag = AdvancedTag('div')

        tag.setAttribute('align', 'left')
        tag.setAttribute('title', 'Hover text')

        htmlStr = str(tag)

        assert 'align="left"' in htmlStr, 'Expected setAttribute("align", "left") to result in align="left" in HTML representation. Got: ' + htmlStr

        alignAttrValue = tag.getAttribute('align')

        assert alignAttrValue == 'left', 'Expected getAttribute("align") to return "left" after having set align to "left". Got: ' + repr(
            alignAttrValue)

        tag.removeAttribute('align')

        htmlStr = str(tag)

        assert 'align="left"' not in htmlStr, 'Expected removeAttribute("align") to remove align="left" from HTML representation. Got: ' + htmlStr

        alignAttrValue = tag.getAttribute('align')

        assert alignAttrValue != 'left', 'Expected removeAttribute("align") to remove align: left from attributes map. Got: ' + repr(
            alignAttrValue)

        tag.removeAttribute('title')

        htmlStr = str(tag)

        assert 'align="left"' not in htmlStr, 'Expected after all attributes removed via removeAttribute that align="left" would not be present. Got: ' + htmlStr
        assert 'title=' not in htmlStr, 'Expected after all attributes removed via removeAttribute that align="left" would not be present. Got: ' + htmlStr

        attributes = tag.attributes

        assert 'align' not in attributes, 'Expected to NOT find "align" within the attributes. Got: ' + repr(
            attributes)
        assert 'title' not in attributes, 'Expected to NOT find "align" within the attributes. Got: ' + repr(
            attributes)
Ejemplo n.º 42
0
    def test_delAttributes(self):
        '''
            test_delAttributes - Test deleting attributes
        '''
        tag = AdvancedTag('div')

        tag.setAttribute('id', 'abc')

        tag.style = 'display: block; float: left'

        tagHTML = tag.toHTML()

        assert 'id="abc"' in tagHTML, 'Expected id="abc" to be present in tag html. Got: ' + tagHTML
        assert 'style=' in tagHTML, 'Expected style attribute to be present in tag html. Got: ' + tagHTML

        assert tag.style.display == 'block', 'Expected style.display to be "block". Style is: ' + str(
            tag.style)
        assert tag.style.float == 'left', 'Expected style.float to be "left". Style is: ' + str(
            tag.style)

        del tag.attributes['id']

        tagHTML = tag.toHTML()

        assert not tag.id, "Expected id to be empty after deleting attribute. It is: " + repr(
            tag.id)
        assert 'id="abc"' not in tagHTML, 'Expected id attribute to NOT be present in tagHTML after delete. Got: ' + tagHTML

        del tag.attributes['style']

        tagHTML = tag.toHTML()

        assert 'style=' not in tagHTML, 'Expected style attribute to NOT be present in tagHTML after delete. Got: ' + tagHTML
        assert str(
            tag.style
        ) == '', 'Expected str(tag.style) to be empty string after delete of style attribute. It was: ' + repr(
            str(tag.style))
        assert tag.style.display == '', 'Expected display style property to be cleared after delete of style attribute. Style is: ' + str(
            tag.style)
        assert tag.style.float == '', 'Expected float style property to be cleared after delete of style attribute. Style is: ' + str(
            tag.style)

        tag.style = 'font-weight: bold; float: right'

        tagHTML = tag.toHTML()

        assert 'style=' in tagHTML, 'Expected after deleting style, then setting it again style shows up as HTML attr. Got: ' + tagHTML

        assert 'font-weight: bold' in tagHTML, 'Expected after deleting style, then setting it again the properties show up in the HTML "style" attribute. Got: ' + tagHTML

        assert id(tag.getAttribute('style', '')) == id(
            tag.style
        ), 'Expected after deleting style, then setting it again the attribute remains linked.'

        assert tag.style.fontWeight == 'bold', 'Expected after deleting style, then setting it again everything works as expected. Set style to "font-weight: bold; float: left" but on tag.style it is: ' + str(
            tag.style)

        tag.addClass('bold-item')
        tag.addClass('blue-font')

        assert 'bold-item' in tag.classList, 'Did addClass("bold-item") but did not find it in classList. classList is: ' + repr(
            tag.classList)
        assert 'blue-font' in tag.classList, 'Did addClass("blue-font") but did not find it in classList. classList is: ' + repr(
            tag.classList)

        classes = tag.getAttribute('class')

        assert 'bold-item' in classes and 'blue-font' in classes, 'Expected class attribute to contain both classes. Got: ' + str(
            classes)

        # This should call del tag._attributes['class']
        tag.removeAttribute('class')

        assert 'bold-item' not in tag.classList, 'After removing class, expected to not find classes in tag.classList. classList is: ' + repr(
            tag.classList)

        assert len(
            tag.classList
        ) == 0, 'Expected to have no classes in classList after delete. Got %d' % (
            len(tag.classList), )

        assert tag.getAttribute(
            'class'
        ) == '', 'Expected after removing class it would be an empty string'

        assert tag.getAttribute(
            'clazz'
        ) is None, 'Expected default getAttribute on non-set attribute to be None'
Ejemplo n.º 43
0
    def test_nameChangeFields(self):
        '''
            Test that fields with a different dot-access variable are handled properly
        '''

        td = AdvancedTag('td')

        assert td.colspan is None, 'Expected "colspan" to be "colSpan"'

        assert td.colSpan is not None, 'Expected "colSpan" to map to "colspan"'

        td.colSpan = 5

        assert not td.colspan, 'dot access should be colSpan, but colspan worked.'

        assert str(
            td.colSpan) == "5", "dot access on .colSpan should have worked"

        assert str(
            td.getAttribute('colspan')
        ) == "5", "Expected getAttribute to use the all lowercase name"

        tdHTML = str(td)

        assert "colSpan" not in tdHTML, "Expected html attribute to be the lowercased name. Got: " + tdHTML

        assert 'colspan="5"' in tdHTML, 'Expected colspan="5" to be present. Got: ' + tdHTML

        td.setAttribute('colspan', '8')

        tdHTML = str(td)

        assert str(
            td.colSpan
        ) == '8', 'Expected setAttribute("colspan",...) to update .colSpan attribute. Was 5, set to 8, and got: ' + repr(
            td.colSpan)

        assert 'colspan="8"' in tdHTML, 'Expected setAttribute("colspan") to update HTML. Got: ' + tdHTML

        assert td.colSpan == 8, 'Expected colSpan to be an integer value. Got: ' + str(
            type(td.colSpan))

        td = AdvancedTag('td', attrList=[('colspan', '5')])

        assert td.colSpan == 5, 'Expected setting "colspan" in attrList sets colSpan'

        # Now try a binary field

        form = AdvancedTag('form')

        assert form.novalidate is None, 'Expected novalidate on form to have dot-access name of noValidate'
        assert form.noValidate is not None, 'Expected novalidate on form to have dot-access name of noValidate'

        assert form.noValidate is False, 'Expected default for form.noValidate to be False'

        form.noValidate = "yes"

        assert form.noValidate is True, 'Expected noValidate to be converted to a bool. Got: ' + repr(
            form.noValidate)

        formHTML = str(form)

        assert 'novalidate' in formHTML, 'Expected form.noValidate to set "novalidate" property in HTML. Got: ' + formHTML

        form.noValidate = True
        formHTML = str(form)

        assert 'novalidate' in formHTML, 'Expected form.noValidate to set "novalidate" property in HTML. Got: ' + formHTML

        form.noValidate = False
        formHTML = str(form)

        assert 'novalidate' not in formHTML, 'Expected setting form.noValidate to False to remove it from HTML. Got: ' + formHTML