Exemple #1
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')
    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)
    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'

        assert itemsEm.childElementCount == 2, 'Expected childElementCount to equal 2'

        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, ))
    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')
Exemple #5
0
    def test_rowAndColSpan(self):
        '''
            test_rowAndColSpan - test rowSpan and colSpan
        '''

        tdEm = AdvancedTag('td')

        assert tdEm.colspan is None, 'Expected colspan dot-access to be None'
        assert tdEm.colSpan is not None, 'Expected colSpan dot-access to not be None'

        assert tdEm.colSpan == 1, 'Expected default colSpan to be 1 but got: ' + repr(
            tdEm.colSpan)

        tdEm.colSpan = 10
        tdEmHTML = str(tdEm)

        assert tdEm.colSpan == 10, 'Expected to be able to set colSpan to 10, but value returned was: ' + repr(
            tdEm.colSpan)
        assert 'colspan="10"' in tdEmHTML, 'Expected colspan="10" to be in HTML string after setting, but got: ' + tdEmHTML

        tdEm.colSpan = -5
        assert tdEm.colSpan == 1, 'Expected colSpan to be clamped to a minimum of 1, but got: ' + repr(
            tdEm.colSpan)

        tdEm.colSpan = 1000000
        assert tdEm.colSpan == 1000, 'Expected colSpan to be clamped to a maximum of 1000, but got: ' + repr(
            tdEm.colSpan)

        tdEm = AdvancedTag('td')

        assert tdEm.rowspan is None, 'Expected rowspan dot-access to be None'
        assert tdEm.rowSpan is not None, 'Expected rowSpan dot-access to not be None'

        assert tdEm.rowSpan == 1, 'Expected default rowSpan to be 1 but got: ' + repr(
            tdEm.rowSpan)

        tdEm.rowSpan = 10
        tdEmHTML = str(tdEm)

        assert tdEm.rowSpan == 10, 'Expected to be able to set rowSpan to 10, but value returned was: ' + repr(
            tdEm.rowSpan)
        assert 'rowspan="10"' in tdEmHTML, 'Expected rowspan="10" to be in HTML string after setting, but got: ' + tdEmHTML

        tdEm.rowSpan = -5
        assert tdEm.rowSpan == 0, 'Expected rowSpan to be clamped to a minimum of 0, but got: ' + repr(
            tdEm.rowSpan)

        tdEm.rowSpan = 1000000
        assert tdEm.rowSpan == 65534, 'Expected rowSpan to be clamped to a maximum of 65534, but got: ' + repr(
            tdEm.rowSpan)
Exemple #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'
Exemple #7
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)
Exemple #8
0
    def test_trackKind(self):
        '''
            test the "kind" attribute on a track
        '''

        # A copy of the possible values. Use a copy so that we are testing not using the code we are testing for validation of the validation of the code we are testing to validate the code that the validation of the INFINTIEEEE LOOOOP AHHHHHHHHHHHHHH
        TRACK_POSSIBLE_KINDS = ('captions', 'chapters', 'descriptions',
                                'metadata', 'subtitles')

        trackEm = AdvancedTag('track')

        assert trackEm.kind == 'subtitles', 'Expected default value of trackEm.kind to be "subtitles"'

        trackEm.kind = 'blah'

        trackEmHTML = str(trackEm)

        assert trackEm.kind == 'metadata', 'Expected when an "invalid" value is provided for track->kind, that "metadata" is returned, but got: ' + repr(
            trackEm.kind)

        assert 'kind="blah"' in trackEmHTML, 'Expected when an "invalid" value is provided for track->kind, that the value is put into the HTML attribute as-is, but got: ' + str(
            trackEmHTML)

        for possibleKind in TRACK_POSSIBLE_KINDS:

            trackEm.kind = possibleKind

            assert trackEm.kind == possibleKind, 'Expected to be able to set track->kind to "%s", but after doing so got %s as the return.' % (
                possibleKind, repr(trackEm.kind))

        trackEm.kind = ''

        assert trackEm.kind == 'metadata', 'Expected setting kind to an empty string returns "metadata" (the invalid result), but got: ' + repr(
            trackEm.kind)
Exemple #9
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'
Exemple #10
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)
Exemple #11
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)
Exemple #12
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'), )
Exemple #13
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.className = 'one two'
        assert str(tag.className).strip(
        ) == 'one two', 'Expected classname to be "one two", got %s' % (repr(
            str(tag.className).strip()), )
Exemple #14
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)
Exemple #15
0
    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)
    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)
    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'
    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'
Exemple #19
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)
Exemple #20
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)
Exemple #21
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'
Exemple #22
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'
Exemple #23
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'
Exemple #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"
    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'
Exemple #26
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
    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)
Exemple #28
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.'
Exemple #29
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
Exemple #30
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'