1 import unittest, sys
2 from lxml.tests.common_imports import doctest, HelperTestCase
3 from lxml import html
4 from lxml import cssselect
5 import os
6
7 doc_fn = os.path.join(os.path.dirname(__file__),
8 'css_shakespear.html')
9
10
11
13
14 selectors = [
15
16
17 ('*', 246),
18 ('div:only-child', 22),
19
20
21
22 ('div:contains(CELIA)', 30),
23 ('div:nth-child(even)', 106),
24 ('div:nth-child(2n)', 106),
25 ('div:nth-child(odd)', 137),
26 ('div:nth-child(2n+1)', 137),
27 ('div:nth-child(n)', 243),
28 ('div:last-child', 53),
29 ('div:first-child', 51),
30 ('div > div', 242),
31 ('div + div', 190),
32 ('div ~ div', 190),
33 ('body', 1),
34 ('body div', 243),
35 ('div', 243),
36 ('div div', 242),
37 ('div div div', 241),
38 ('div, div, div', 243),
39 ('div, a, span', 243),
40 ('.dialog', 51),
41 ('div.dialog', 51),
42 ('div .dialog', 51),
43 ('div.character, div.dialog', 99),
44 ('div.direction.dialog', 0),
45 ('div.dialog.direction', 0),
46 ('div.dialog.scene', 1),
47 ('div.scene.scene', 1),
48 ('div.scene .scene', 0),
49 ('div.direction .dialog ', 0),
50 ('div .dialog .direction', 4),
51 ('div.dialog .dialog .direction', 4),
52 ('#speech5', 1),
53 ('div#speech5', 1),
54 ('div #speech5', 1),
55 ('div.scene div.dialog', 49),
56 ('div#scene1 div.dialog div', 142),
57 ('#scene1 #speech1', 1),
58 ('div[class]', 103),
59 ('div[class=dialog]', 50),
60 ('div[class^=dia]', 51),
61 ('div[class$=log]', 50),
62 ('div[class*=sce]', 1),
63 ('div[class|=dialog]', 50),
64 ('div[class!=madeup]', 243),
65 ('div[class~=dialog]', 51),
66 ]
67
71
73 for i in range(len(cls.selectors)):
74 yield cls(i)
75 all = classmethod(all)
76
78 f = open(doc_fn, 'rb')
79 c = f.read()
80 f.close()
81 doc = html.document_fromstring(c)
82 body = doc.xpath('//body')[0]
83 bad = []
84 selector, count = self.selectors[self.index]
85 xpath = cssselect.css_to_xpath(cssselect.parse(selector))
86 try:
87 results = body.xpath(xpath)
88 except Exception, e:
89 e.args = ("%s for xpath %r" % (e, xpath))
90 raise
91 found = {}
92 for item in results:
93 if item in found:
94 assert 0, (
95 "Element shows up multiple times: %r" % item)
96 found[item] = None
97 if isinstance(results, basestring):
98 assert 0, (
99 "Got string result (%r), not element, for xpath %r"
100 % (results[:20], str(xpath)))
101 if len(results) != count:
102
103
104 assert 0, (
105 "Did not get expected results (%s) instead %s for xpath %r"
106 % (count, len(results), str(xpath)))
107
110
112 found = {}
113 result = []
114 for item in s:
115 if item in found:
116 continue
117 found[item] = None
118 result.append(s)
119 return result
120
122 suite = unittest.TestSuite()
123 if sys.version_info >= (2,4):
124 suite.addTests([doctest.DocFileSuite('test_css_select.txt')])
125 suite.addTests([doctest.DocFileSuite('test_css.txt')])
126 suite.addTests(list(CSSTestCase.all()))
127 return suite
128