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
22
23 pytestmark = skipif('cssselect is None')
24
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
36 count('DIV', 1)
37
38 count('DIV', 0, translator='xhtml')
39 count('DIV', 0, translator='xml')
40
41
42 count(':contains("link")', 2)
43 count(':contains("LInk")', 2)
44
45 count(':contains("LInk")', 2, translator='xhtml')
46 count(':contains("LInk")', 2, translator='xml')
47
48 import cssselect
49 count(':contains("link")', 2, translator=cssselect.HTMLTranslator())
50 count(':contains("LInk")', 0, translator=cssselect.HTMLTranslator())
51
52
54 suite = unittest.TestSuite()
55 try:
56 import cssselect
57 except ImportError:
58
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