Package lxml :: Package tests :: Module test_css

[hide private]
[frames] | no frames]

# Source Code for Module lxml.tests.test_css

     1  import unittest
     2
     3  import lxml.html
     4
     5  from lxml.tests.common_imports import doctest, HelperTestCase, skipif
     6
     7  try:
     8      import cssselect
     9  except ImportError:
    10      cssselect = None
    11
    12
    13  HTML = '''
    14  <div>
    15    <a href="foo">link</a>
    16    <a>anchor</a>
    17  </div>
    18  '''
    19
    20
    21 -class CSSTestCase(HelperTestCase):
    22
    23      pytestmark = skipif('cssselect is None')
    24
    25 -    def test_cssselect(self):
    26          div, = lxml.html.fromstring(HTML).xpath('//div')
    27
    28          def count(selector, expected_count, **kwargs):
    29              result = div.cssselect(selector, **kwargs)
    30              self.assertEqual(len(result), expected_count)
    31
    32          count('div', 1)
    33          count('a', 2)
    34          count('em', 0)
    35          # Element names are case-insensitive in HTML
    36          count('DIV', 1)
    37          # ... but not in XHTML or XML
    38          count('DIV', 0, translator='xhtml')
    39          count('DIV', 0, translator='xml')
    40
    41          # :contains() is case-insensitive in lxml
    42          count(':contains("link")', 2)  # div, a
    43          count(':contains("LInk")', 2)
    44          # Whatever the document language
    45          count(':contains("LInk")', 2, translator='xhtml')
    46          count(':contains("LInk")', 2, translator='xml')
    47          # ... but not in upstream cssselect
    48          import cssselect
    49          count(':contains("link")', 2, translator=cssselect.HTMLTranslator())
    50          count(':contains("LInk")', 0, translator=cssselect.HTMLTranslator())
    51
    52
    53 -def test_suite():
    54      suite = unittest.TestSuite()
    55      try:
    56          import cssselect
    57      except ImportError:
    58          # no 'cssselect' installed
    59          print("Skipping tests in lxml.cssselect - external cssselect package is not installed")
    60          return suite
    61
    62      import lxml.cssselect
    63      suite.addTests(doctest.DocTestSuite(lxml.cssselect))
    64      suite.addTests([unittest.makeSuite(CSSTestCase)])
    65      return suite
    66