1 import unittest
2 from lxml.tests.common_imports import doctest
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 ('#speech5', 1),
45 ('div#speech5', 1),
46 ('div #speech5', 1),
47 ('div.scene div.dialog', 49),
48 ('div#scene1 div.dialog div', 142),
49 ('#scene1 #speech1', 1),
50 ('div[class]', 103),
51 ('div[class=dialog]', 50),
52 ('div[class^=dia]', 51),
53 ('div[class$=log]', 50),
54 ('div[class*=sce]', 1),
55 ('div[class|=dialog]', 50),
56 ('div[class!=madeup]', 243),
57 ('div[class~=dialog]', 51),
58 ]
59
63
64 @classmethod
66 for i in range(len(cls.selectors)):
67 yield cls(i)
68
70 f = open(doc_fn, 'rb')
71 c = f.read()
72 f.close()
73 doc = html.document_fromstring(c)
74 body = doc.xpath('//body')[0]
75 bad = []
76 selector, count = self.selectors[self.index]
77 xpath = cssselect.css_to_xpath(cssselect.parse(selector))
78 try:
79 results = body.xpath(xpath)
80 except Exception, e:
81 e.args = ("%s for xpath %r" % (e, xpath))
82 raise
83 found = {}
84 for item in results:
85 if item in found:
86 assert 0, (
87 "Element shows up multiple times: %r" % item)
88 found[item] = None
89 if isinstance(results, basestring):
90 assert 0, (
91 "Got string result (%r), not element, for xpath %r"
92 % (results[:20], str(xpath)))
93 if len(results) != count:
94
95
96 assert 0, (
97 "Did not get expected results (%s) instead %s for xpath %r"
98 % (count, len(results), str(xpath)))
99
102
104 found = {}
105 result = []
106 for item in s:
107 if item in found:
108 continue
109 found[item] = None
110 result.append(s)
111 return result
112
114 suite = unittest.TestSuite()
115 for fn in 'test_css.txt', 'test_css_select.txt':
116 suite.addTests([doctest.DocFileSuite(fn)])
117 suite.addTests(list(CSSTestCase.all()))
118 return suite
119