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