Debian Codegraph @

src/css_selectors/tests.py

raw
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3
4
5 __license__ = 'GPL v3'
6 __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
7
8 import argparse
9 import sys
10 import unittest
11
12 from lxml import etree, html
13
14 from css_selectors.errors import ExpressionError, SelectorSyntaxError
15 from css_selectors.parser import parse, tokenize
16 from css_selectors.select import Select
17
18
19 class TestCSSSelectors(unittest.TestCase):
20
21 # Test data {{{
22 HTML_IDS = '''
23 <html id="html"><head>
24 <link id="link-href" href="foo" />
25 <link id="link-nohref" />
26 </head><body>
27 <div id="outer-div">
28 <a id="name-anchor" name="foo"></a>
29 <a id="tag-anchor" rel="tag" href="http://localhost/foo">link</a>
30 <a id="nofollow-anchor" rel="nofollow" href="https://example.org">
31 link</a>
32 <ol id="first-ol" class="a b c">
33 <li id="first-li">content</li>
34 <li id="second-li" lang="En-us">
35 <div id="li-div">
36 </div>
37 </li>
38 <li id="third-li" class="ab c"></li>
39 <li id="fourth-li" class="ab
40 c"></li>
41 <li id="fifth-li"></li>
42 <li id="sixth-li"></li>
43 <li id="seventh-li"> </li>
44 </ol>
45 <p id="paragraph">
46 <b id="p-b">hi</b> <em id="p-em">there</em>
47 <b id="p-b2">guy</b>
48 <input type="checkbox" id="checkbox-unchecked" />
49 <input type="checkbox" id="checkbox-disabled" disabled="" />
50 <input type="text" id="text-checked" checked="checked" />
51 <input type="hidden" />
52 <input type="hidden" disabled="disabled" />
53 <input type="checkbox" id="checkbox-checked" checked="checked" />
54 <input type="checkbox" id="checkbox-disabled-checked"
55 disabled="disabled" checked="checked" />
56 <fieldset id="fieldset" disabled="disabled">
57 <input type="checkbox" id="checkbox-fieldset-disabled" />
58 <input type="hidden" />
59 </fieldset>
60 </p>
61 <ol id="second-ol">
62 </ol>
63 <map name="dummymap">
64 <area shape="circle" coords="200,250,25" href="foo.html" id="area-href" />
65 <area shape="default" id="area-nohref" />
66 </map>
67 </div>
68 <div id="foobar-div" foobar="ab bc
69 cde"><span id="foobar-span"></span></div>
70 </body></html>
71 '''
72 HTML_SHAKESPEARE = '''
73 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
74 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
75 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" debug="true">
76 <head>
77 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
78 </head>
79 <body>
80 <div id="test">
81 <div class="dialog">
82 <h2>As You Like It</h2>
83 <div id="playwright">
84 by William Shakespeare
85 </div>
86 <div class="dialog scene thirdClass" id="scene1">
87 <h3>ACT I, SCENE III. A room in the palace.</h3>
88 <div class="dialog">
89 <div class="direction">Enter CELIA and ROSALIND</div>
90 </div>
91 <div id="speech1" class="character">CELIA</div>
92 <div class="dialog">
93 <div id="scene1.3.1">Why, cousin! why, Rosalind! Cupid have mercy! not a word?</div>
94 </div>
95 <div id="speech2" class="character">ROSALIND</div>
96 <div class="dialog">
97 <div id="scene1.3.2">Not one to throw at a dog.</div>
98 </div>
99 <div id="speech3" class="character">CELIA</div>
100 <div class="dialog">
101 <div id="scene1.3.3">No, thy words are too precious to be cast away upon</div>
102 <div id="scene1.3.4">curs; throw some of them at me; come, lame me with reasons.</div>
103 </div>
104 <div id="speech4" class="character">ROSALIND</div>
105 <div id="speech5" class="character">CELIA</div>
106 <div class="dialog">
107 <div id="scene1.3.8">But is all this for your father?</div>
108 </div>
109 <div class="dialog">
110 <div id="scene1.3.5">Then there were two cousins laid up; when the one</div>
111 <div id="scene1.3.6">should be lamed with reasons and the other mad</div>
112 <div id="scene1.3.7">without any.</div>
113 </div>
114 <div id="speech6" class="character">ROSALIND</div>
115 <div class="dialog">
116 <div id="scene1.3.9">No, some of it is for my child's father. O, how</div>
117 <div id="scene1.3.10">full of briers is this working-day world!</div>
118 </div>
119 <div id="speech7" class="character">CELIA</div>
120 <div class="dialog">
121 <div id="scene1.3.11">They are but burs, cousin, thrown upon thee in</div>
122 <div id="scene1.3.12">holiday foolery: if we walk not in the trodden</div>
123 <div id="scene1.3.13">paths our very petticoats will catch them.</div>
124 </div>
125 <div id="speech8" class="character">ROSALIND</div>
126 <div class="dialog">
127 <div id="scene1.3.14">I could shake them off my coat: these burs are in my heart.</div>
128 </div>
129 <div id="speech9" class="character">CELIA</div>
130 <div class="dialog">
131 <div id="scene1.3.15">Hem them away.</div>
132 </div>
133 <div id="speech10" class="character">ROSALIND</div>
134 <div class="dialog">
135 <div id="scene1.3.16">I would try, if I could cry 'hem' and have him.</div>
136 </div>
137 <div id="speech11" class="character">CELIA</div>
138 <div class="dialog">
139 <div id="scene1.3.17">Come, come, wrestle with thy affections.</div>
140 </div>
141 <div id="speech12" class="character">ROSALIND</div>
142 <div class="dialog">
143 <div id="scene1.3.18">O, they take the part of a better wrestler than myself!</div>
144 </div>
145 <div id="speech13" class="character">CELIA</div>
146 <div class="dialog">
147 <div id="scene1.3.19">O, a good wish upon you! you will try in time, in</div>
148 <div id="scene1.3.20">despite of a fall. But, turning these jests out of</div>
149 <div id="scene1.3.21">service, let us talk in good earnest: is it</div>
150 <div id="scene1.3.22">possible, on such a sudden, you should fall into so</div>
151 <div id="scene1.3.23">strong a liking with old Sir Rowland's youngest son?</div>
152 </div>
153 <div id="speech14" class="character">ROSALIND</div>
154 <div class="dialog">
155 <div id="scene1.3.24">The duke my father loved his father dearly.</div>
156 </div>
157 <div id="speech15" class="character">CELIA</div>
158 <div class="dialog">
159 <div id="scene1.3.25">Doth it therefore ensue that you should love his son</div>
160 <div id="scene1.3.26">dearly? By this kind of chase, I should hate him,</div>
161 <div id="scene1.3.27">for my father hated his father dearly; yet I hate</div>
162 <div id="scene1.3.28">not Orlando.</div>
163 </div>
164 <div id="speech16" class="character">ROSALIND</div>
165 <div title="wtf" class="dialog">
166 <div id="scene1.3.29">No, faith, hate him not, for my sake.</div>
167 </div>
168 <div id="speech17" class="character">CELIA</div>
169 <div class="dialog">
170 <div id="scene1.3.30">Why should I not? doth he not deserve well?</div>
171 </div>
172 <div id="speech18" class="character">ROSALIND</div>
173 <div class="dialog">
174 <div id="scene1.3.31">Let me love him for that, and do you love him</div>
175 <div id="scene1.3.32">because I do. Look, here comes the duke.</div>
176 </div>
177 <div id="speech19" class="character">CELIA</div>
178 <div class="dialog">
179 <div id="scene1.3.33">With his eyes full of anger.</div>
180 <div class="direction">Enter DUKE FREDERICK, with Lords</div>
181 </div>
182 <div id="speech20" class="character">DUKE FREDERICK</div>
183 <div class="dialog">
184 <div id="scene1.3.34">Mistress, dispatch you with your safest haste</div>
185 <div id="scene1.3.35">And get you from our court.</div>
186 </div>
187 <div id="speech21" class="character">ROSALIND</div>
188 <div class="dialog">
189 <div id="scene1.3.36">Me, uncle?</div>
190 </div>
191 <div id="speech22" class="character">DUKE FREDERICK</div>
192 <div class="dialog">
193 <div id="scene1.3.37">You, cousin</div>
194 <div id="scene1.3.38">Within these ten days if that thou be'st found</div>
195 <div id="scene1.3.39">So near our public court as twenty miles,</div>
196 <div id="scene1.3.40">Thou diest for it.</div>
197 </div>
198 <div id="speech23" class="character">ROSALIND</div>
199 <div class="dialog">
200 <div id="scene1.3.41"> I do beseech your grace,</div>
201 <div id="scene1.3.42">Let me the knowledge of my fault bear with me:</div>
202 <div id="scene1.3.43">If with myself I hold intelligence</div>
203 <div id="scene1.3.44">Or have acquaintance with mine own desires,</div>
204 <div id="scene1.3.45">If that I do not dream or be not frantic,--</div>
205 <div id="scene1.3.46">As I do trust I am not--then, dear uncle,</div>
206 <div id="scene1.3.47">Never so much as in a thought unborn</div>
207 <div id="scene1.3.48">Did I offend your highness.</div>
208 </div>
209 <div id="speech24" class="character">DUKE FREDERICK</div>
210 <div class="dialog">
211 <div id="scene1.3.49">Thus do all traitors:</div>
212 <div id="scene1.3.50">If their purgation did consist in words,</div>
213 <div id="scene1.3.51">They are as innocent as grace itself:</div>
214 <div id="scene1.3.52">Let it suffice thee that I trust thee not.</div>
215 </div>
216 <div id="speech25" class="character">ROSALIND</div>
217 <div class="dialog">
218 <div id="scene1.3.53">Yet your mistrust cannot make me a traitor:</div>
219 <div id="scene1.3.54">Tell me whereon the likelihood depends.</div>
220 </div>
221 <div id="speech26" class="character">DUKE FREDERICK</div>
222 <div class="dialog">
223 <div id="scene1.3.55">Thou art thy father's daughter; there's enough.</div>
224 </div>
225 <div id="speech27" class="character">ROSALIND</div>
226 <div class="dialog">
227 <div id="scene1.3.56">So was I when your highness took his dukedom;</div>
228 <div id="scene1.3.57">So was I when your highness banish'd him:</div>
229 <div id="scene1.3.58">Treason is not inherited, my lord;</div>
230 <div id="scene1.3.59">Or, if we did derive it from our friends,</div>
231 <div id="scene1.3.60">What's that to me? my father was no traitor:</div>
232 <div id="scene1.3.61">Then, good my liege, mistake me not so much</div>
233 <div id="scene1.3.62">To think my poverty is treacherous.</div>
234 </div>
235 <div id="speech28" class="character">CELIA</div>
236 <div class="dialog">
237 <div id="scene1.3.63">Dear sovereign, hear me speak.</div>
238 </div>
239 <div id="speech29" class="character">DUKE FREDERICK</div>
240 <div class="dialog">
241 <div id="scene1.3.64">Ay, Celia; we stay'd her for your sake,</div>
242 <div id="scene1.3.65">Else had she with her father ranged along.</div>
243 </div>
244 <div id="speech30" class="character">CELIA</div>
245 <div class="dialog">
246 <div id="scene1.3.66">I did not then entreat to have her stay;</div>
247 <div id="scene1.3.67">It was your pleasure and your own remorse:</div>
248 <div id="scene1.3.68">I was too young that time to value her;</div>
249 <div id="scene1.3.69">But now I know her: if she be a traitor,</div>
250 <div id="scene1.3.70">Why so am I; we still have slept together,</div>
251 <div id="scene1.3.71">Rose at an instant, learn'd, play'd, eat together,</div>
252 <div id="scene1.3.72">And wheresoever we went, like Juno's swans,</div>
253 <div id="scene1.3.73">Still we went coupled and inseparable.</div>
254 </div>
255 <div id="speech31" class="character">DUKE FREDERICK</div>
256 <div class="dialog">
257 <div id="scene1.3.74">She is too subtle for thee; and her smoothness,</div>
258 <div id="scene1.3.75">Her very silence and her patience</div>
259 <div id="scene1.3.76">Speak to the people, and they pity her.</div>
260 <div id="scene1.3.77">Thou art a fool: she robs thee of thy name;</div>
261 <div id="scene1.3.78">And thou wilt show more bright and seem more virtuous</div>
262 <div id="scene1.3.79">When she is gone. Then open not thy lips:</div>
263 <div id="scene1.3.80">Firm and irrevocable is my doom</div>
264 <div id="scene1.3.81">Which I have pass'd upon her; she is banish'd.</div>
265 </div>
266 <div id="speech32" class="character">CELIA</div>
267 <div class="dialog">
268 <div id="scene1.3.82">Pronounce that sentence then on me, my liege:</div>
269 <div id="scene1.3.83">I cannot live out of her company.</div>
270 </div>
271 <div id="speech33" class="character">DUKE FREDERICK</div>
272 <div class="dialog">
273 <div id="scene1.3.84">You are a fool. You, niece, provide yourself:</div>
274 <div id="scene1.3.85">If you outstay the time, upon mine honour,</div>
275 <div id="scene1.3.86">And in the greatness of my word, you die.</div>
276 <div class="direction">Exeunt DUKE FREDERICK and Lords</div>
277 </div>
278 <div id="speech34" class="character">CELIA</div>
279 <div class="dialog">
280 <div id="scene1.3.87">O my poor Rosalind, whither wilt thou go?</div>
281 <div id="scene1.3.88">Wilt thou change fathers? I will give thee mine.</div>
282 <div id="scene1.3.89">I charge thee, be not thou more grieved than I am.</div>
283 </div>
284 <div id="speech35" class="character">ROSALIND</div>
285 <div class="dialog">
286 <div id="scene1.3.90">I have more cause.</div>
287 </div>
288 <div id="speech36" class="character">CELIA</div>
289 <div class="dialog">
290 <div id="scene1.3.91"> Thou hast not, cousin;</div>
291 <div id="scene1.3.92">Prithee be cheerful: know'st thou not, the duke</div>
292 <div id="scene1.3.93">Hath banish'd me, his daughter?</div>
293 </div>
294 <div id="speech37" class="character">ROSALIND</div>
295 <div class="dialog">
296 <div id="scene1.3.94">That he hath not.</div>
297 </div>
298 <div id="speech38" class="character">CELIA</div>
299 <div class="dialog">
300 <div id="scene1.3.95">No, hath not? Rosalind lacks then the love</div>
301 <div id="scene1.3.96">Which teacheth thee that thou and I am one:</div>
302 <div id="scene1.3.97">Shall we be sunder'd? shall we part, sweet girl?</div>
303 <div id="scene1.3.98">No: let my father seek another heir.</div>
304 <div id="scene1.3.99">Therefore devise with me how we may fly,</div>
305 <div id="scene1.3.100">Whither to go and what to bear with us;</div>
306 <div id="scene1.3.101">And do not seek to take your change upon you,</div>
307 <div id="scene1.3.102">To bear your griefs yourself and leave me out;</div>
308 <div id="scene1.3.103">For, by this heaven, now at our sorrows pale,</div>
309 <div id="scene1.3.104">Say what thou canst, I'll go along with thee.</div>
310 </div>
311 <div id="speech39" class="character">ROSALIND</div>
312 <div class="dialog">
313 <div id="scene1.3.105">Why, whither shall we go?</div>
314 </div>
315 <div id="speech40" class="character">CELIA</div>
316 <div class="dialog">
317 <div id="scene1.3.106">To seek my uncle in the forest of Arden.</div>
318 </div>
319 <div id="speech41" class="character">ROSALIND</div>
320 <div class="dialog">
321 <div id="scene1.3.107">Alas, what danger will it be to us,</div>
322 <div id="scene1.3.108">Maids as we are, to travel forth so far!</div>
323 <div id="scene1.3.109">Beauty provoketh thieves sooner than gold.</div>
324 </div>
325 <div id="speech42" class="character">CELIA</div>
326 <div class="dialog">
327 <div id="scene1.3.110">I'll put myself in poor and mean attire</div>
328 <div id="scene1.3.111">And with a kind of umber smirch my face;</div>
329 <div id="scene1.3.112">The like do you: so shall we pass along</div>
330 <div id="scene1.3.113">And never stir assailants.</div>
331 </div>
332 <div id="speech43" class="character">ROSALIND</div>
333 <div class="dialog">
334 <div id="scene1.3.114">Were it not better,</div>
335 <div id="scene1.3.115">Because that I am more than common tall,</div>
336 <div id="scene1.3.116">That I did suit me all points like a man?</div>
337 <div id="scene1.3.117">A gallant curtle-axe upon my thigh,</div>
338 <div id="scene1.3.118">A boar-spear in my hand; and--in my heart</div>
339 <div id="scene1.3.119">Lie there what hidden woman's fear there will--</div>
340 <div id="scene1.3.120">We'll have a swashing and a martial outside,</div>
341 <div id="scene1.3.121">As many other mannish cowards have</div>
342 <div id="scene1.3.122">That do outface it with their semblances.</div>
343 </div>
344 <div id="speech44" class="character">CELIA</div>
345 <div class="dialog">
346 <div id="scene1.3.123">What shall I call thee when thou art a man?</div>
347 </div>
348 <div id="speech45" class="character">ROSALIND</div>
349 <div class="dialog">
350 <div id="scene1.3.124">I'll have no worse a name than Jove's own page;</div>
351 <div id="scene1.3.125">And therefore look you call me Ganymede.</div>
352 <div id="scene1.3.126">But what will you be call'd?</div>
353 </div>
354 <div id="speech46" class="character">CELIA</div>
355 <div class="dialog">
356 <div id="scene1.3.127">Something that hath a reference to my state</div>
357 <div id="scene1.3.128">No longer Celia, but Aliena.</div>
358 </div>
359 <div id="speech47" class="character">ROSALIND</div>
360 <div class="dialog">
361 <div id="scene1.3.129">But, cousin, what if we assay'd to steal</div>
362 <div id="scene1.3.130">The clownish fool out of your father's court?</div>
363 <div id="scene1.3.131">Would he not be a comfort to our travel?</div>
364 </div>
365 <div id="speech48" class="character">CELIA</div>
366 <div class="dialog">
367 <div id="scene1.3.132">He'll go along o'er the wide world with me;</div>
368 <div id="scene1.3.133">Leave me alone to woo him. Let's away,</div>
369 <div id="scene1.3.134">And get our jewels and our wealth together,</div>
370 <div id="scene1.3.135">Devise the fittest time and safest way</div>
371 <div id="scene1.3.136">To hide us from pursuit that will be made</div>
372 <div id="scene1.3.137">After my flight. Now go we in content</div>
373 <div id="scene1.3.138">To liberty and not to banishment.</div>
374 <div class="direction">Exeunt</div>
375 </div>
376 </div>
377 </div>
378 </div>
379 </body>
380 </html>
381 '''
382
383
384 # }}}
385
386 ae = unittest.TestCase.assertEqual
387
388 def test_tokenizer(self): # {{{
389 tokens = [
390 type('')(item) for item in tokenize(
391 r'E\ é > f [a~="y\"x"]:nth(/* fu /]* */-3.7)')]
392 self.ae(tokens, [
393 "<IDENT 'E é' at 0>",
394 "<S ' ' at 4>",
395 "<DELIM '>' at 5>",
396 "<S ' ' at 6>",
397 # the no-break space is not whitespace in CSS
398 "<IDENT 'f ' at 7>", # f\xa0
399 "<DELIM '[' at 9>",
400 "<IDENT 'a' at 10>",
401 "<DELIM '~' at 11>",
402 "<DELIM '=' at 12>",
403 "<STRING 'y\"x' at 13>",
404 "<DELIM ']' at 19>",
405 "<DELIM ':' at 20>",
406 "<IDENT 'nth' at 21>",
407 "<DELIM '(' at 24>",
408 "<NUMBER '-3.7' at 37>",
409 "<DELIM ')' at 41>",
410 "<EOF at 42>",
411 ])
412 # }}}
413
414 def test_parser(self): # {{{
415 def repr_parse(css):
416 selectors = parse(css)
417 for selector in selectors:
418 assert selector.pseudo_element is None
419 return [repr(selector.parsed_tree).replace("(u'", "('")
420 for selector in selectors]
421
422 def parse_many(first, *others):
423 result = repr_parse(first)
424 for other in others:
425 assert repr_parse(other) == result
426 return result
427
428 assert parse_many('*') == ['Element[*]']
429 assert parse_many('*|*') == ['Element[*]']
430 assert parse_many('*|foo') == ['Element[foo]']
431 assert parse_many('foo|*') == ['Element[foo|*]']
432 assert parse_many('foo|bar') == ['Element[foo|bar]']
433 # This will never match, but it is valid:
434 assert parse_many('#foo#bar') == ['Hash[Hash[Element[*]#foo]#bar]']
435 assert parse_many(
436 'div>.foo',
437 'div> .foo',
438 'div >.foo',
439 'div > .foo',
440 'div \n> \t \t .foo', 'div\r>\n\n\n.foo', 'div\f>\f.foo'
441 ) == ['CombinedSelector[Element[div] > Class[Element[*].foo]]']
442 assert parse_many('td.foo,.bar',
443 'td.foo, .bar',
444 'td.foo\t\r\n\f ,\t\r\n\f .bar'
445 ) == [
446 'Class[Element[td].foo]',
447 'Class[Element[*].bar]'
448 ]
449 assert parse_many('div, td.foo, div.bar span') == [
450 'Element[div]',
451 'Class[Element[td].foo]',
452 'CombinedSelector[Class[Element[div].bar] '
453 '<followed> Element[span]]']
454 assert parse_many('div > p') == [
455 'CombinedSelector[Element[div] > Element[p]]']
456 assert parse_many('td:first') == [
457 'Pseudo[Element[td]:first]']
458 assert parse_many('td:first') == [
459 'Pseudo[Element[td]:first]']
460 assert parse_many('td :first') == [
461 'CombinedSelector[Element[td] '
462 '<followed> Pseudo[Element[*]:first]]']
463 assert parse_many('td :first') == [
464 'CombinedSelector[Element[td] '
465 '<followed> Pseudo[Element[*]:first]]']
466 assert parse_many('a[name]', 'a[ name\t]') == [
467 'Attrib[Element[a][name]]']
468 assert parse_many('a [name]') == [
469 'CombinedSelector[Element[a] <followed> Attrib[Element[*][name]]]']
470 self.ae(parse_many('a[rel="include"]', 'a[rel = include]'), [
471 "Attrib[Element[a][rel = 'include']]"])
472 assert parse_many("a[hreflang |= 'en']", "a[hreflang|=en]") == [
473 "Attrib[Element[a][hreflang |= 'en']]"]
474 self.ae(parse_many('div:nth-child(10)'), [
475 "Function[Element[div]:nth-child(['10'])]"])
476 assert parse_many(':nth-child(2n+2)') == [
477 "Function[Element[*]:nth-child(['2', 'n', '+2'])]"]
478 assert parse_many('div:nth-of-type(10)') == [
479 "Function[Element[div]:nth-of-type(['10'])]"]
480 assert parse_many('div div:nth-of-type(10) .aclass') == [
481 'CombinedSelector[CombinedSelector[Element[div] <followed> '
482 "Function[Element[div]:nth-of-type(['10'])]] "
483 '<followed> Class[Element[*].aclass]]']
484 assert parse_many('label:only') == [
485 'Pseudo[Element[label]:only]']
486 assert parse_many('a:lang(fr)') == [
487 "Function[Element[a]:lang(['fr'])]"]
488 assert parse_many('div:contains("foo")') == [
489 "Function[Element[div]:contains(['foo'])]"]
490 assert parse_many('div#foobar') == [
491 'Hash[Element[div]#foobar]']
492 assert parse_many('div:not(div.foo)') == [
493 'Negation[Element[div]:not(Class[Element[div].foo])]']
494 assert parse_many('td ~ th') == [
495 'CombinedSelector[Element[td] ~ Element[th]]']
496 # }}}
497
498 def test_pseudo_elements(self): # {{{
499 def parse_pseudo(css):
500 result = []
501 for selector in parse(css):
502 pseudo = selector.pseudo_element
503 pseudo = type('')(pseudo) if pseudo else pseudo
504 # No Symbol here
505 assert pseudo is None or isinstance(pseudo, type(''))
506 selector = repr(selector.parsed_tree).replace("(u'", "('")
507 result.append((selector, pseudo))
508 return result
509
510 def parse_one(css):
511 result = parse_pseudo(css)
512 assert len(result) == 1
513 return result[0]
514
515 self.ae(parse_one('foo'), ('Element[foo]', None))
516 self.ae(parse_one('*'), ('Element[*]', None))
517 self.ae(parse_one(':empty'), ('Pseudo[Element[*]:empty]', None))
518
519 # Special cases for CSS 2.1 pseudo-elements
520 self.ae(parse_one(':BEfore'), ('Element[*]', 'before'))
521 self.ae(parse_one(':aftER'), ('Element[*]', 'after'))
522 self.ae(parse_one(':First-Line'), ('Element[*]', 'first-line'))
523 self.ae(parse_one(':First-Letter'), ('Element[*]', 'first-letter'))
524
525 self.ae(parse_one('::befoRE'), ('Element[*]', 'before'))
526 self.ae(parse_one('::AFter'), ('Element[*]', 'after'))
527 self.ae(parse_one('::firsT-linE'), ('Element[*]', 'first-line'))
528 self.ae(parse_one('::firsT-letteR'), ('Element[*]', 'first-letter'))
529
530 self.ae(parse_one('::text-content'), ('Element[*]', 'text-content'))
531 self.ae(parse_one('::attr(name)'), (
532 "Element[*]", "FunctionalPseudoElement[::attr(['name'])]"))
533
534 self.ae(parse_one('::Selection'), ('Element[*]', 'selection'))
535 self.ae(parse_one('foo:after'), ('Element[foo]', 'after'))
536 self.ae(parse_one('foo::selection'), ('Element[foo]', 'selection'))
537 self.ae(parse_one('lorem#ipsum ~ a#b.c[href]:empty::selection'), (
538 'CombinedSelector[Hash[Element[lorem]#ipsum] ~ '
539 'Pseudo[Attrib[Class[Hash[Element[a]#b].c][href]]:empty]]',
540 'selection'))
541
542 parse_pseudo('foo:before, bar, baz:after') == [
543 ('Element[foo]', 'before'),
544 ('Element[bar]', None),
545 ('Element[baz]', 'after')]
546 # }}}
547
548 def test_specificity(self): # {{{
549 def specificity(css):
550 selectors = parse(css)
551 assert len(selectors) == 1
552 return selectors[0].specificity()
553
554 assert specificity('*') == (0, 0, 0)
555 assert specificity(' foo') == (0, 0, 1)
556 assert specificity(':empty ') == (0, 1, 0)
557 assert specificity(':before') == (0, 0, 1)
558 assert specificity('*:before') == (0, 0, 1)
559 assert specificity(':nth-child(2)') == (0, 1, 0)
560 assert specificity('.bar') == (0, 1, 0)
561 assert specificity('[baz]') == (0, 1, 0)
562 assert specificity('[baz="4"]') == (0, 1, 0)
563 assert specificity('[baz^="4"]') == (0, 1, 0)
564 assert specificity('#lipsum') == (1, 0, 0)
565
566 assert specificity(':not(*)') == (0, 0, 0)
567 assert specificity(':not(foo)') == (0, 0, 1)
568 assert specificity(':not(.foo)') == (0, 1, 0)
569 assert specificity(':not([foo])') == (0, 1, 0)
570 assert specificity(':not(:empty)') == (0, 1, 0)
571 assert specificity(':not(#foo)') == (1, 0, 0)
572
573 assert specificity('foo:empty') == (0, 1, 1)
574 assert specificity('foo:before') == (0, 0, 2)
575 assert specificity('foo::before') == (0, 0, 2)
576 assert specificity('foo:empty::before') == (0, 1, 2)
577
578 assert specificity('#lorem + foo#ipsum:first-child > bar:first-line'
579 ) == (2, 1, 3)
580 # }}}
581
582 def test_parse_errors(self): # {{{
583 def get_error(css):
584 try:
585 parse(css)
586 except SelectorSyntaxError:
587 # Py2, Py3, ...
588 return str(sys.exc_info()[1]).replace("(u'", "('")
589
590 self.ae(get_error('attributes(href)/html/body/a'), (
591 "Expected selector, got <DELIM '(' at 10>"))
592 assert get_error('attributes(href)') == (
593 "Expected selector, got <DELIM '(' at 10>")
594 assert get_error('html/body/a') == (
595 "Expected selector, got <DELIM '/' at 4>")
596 assert get_error(' ') == (
597 "Expected selector, got <EOF at 1>")
598 assert get_error('div, ') == (
599 "Expected selector, got <EOF at 5>")
600 assert get_error(' , div') == (
601 "Expected selector, got <DELIM ',' at 1>")
602 assert get_error('p, , div') == (
603 "Expected selector, got <DELIM ',' at 3>")
604 assert get_error('div > ') == (
605 "Expected selector, got <EOF at 6>")
606 assert get_error(' > div') == (
607 "Expected selector, got <DELIM '>' at 2>")
608 assert get_error('foo|#bar') == (
609 "Expected ident or '*', got <HASH 'bar' at 4>")
610 assert get_error('#.foo') == (
611 "Expected selector, got <DELIM '#' at 0>")
612 assert get_error('.#foo') == (
613 "Expected ident, got <HASH 'foo' at 1>")
614 assert get_error(':#foo') == (
615 "Expected ident, got <HASH 'foo' at 1>")
616 assert get_error('[*]') == (
617 "Expected '|', got <DELIM ']' at 2>")
618 assert get_error('[foo|]') == (
619 "Expected ident, got <DELIM ']' at 5>")
620 assert get_error('[#]') == (
621 "Expected ident or '*', got <DELIM '#' at 1>")
622 assert get_error('[foo=#]') == (
623 "Expected string or ident, got <DELIM '#' at 5>")
624 assert get_error('[href]a') == (
625 "Expected selector, got <IDENT 'a' at 6>")
626 assert get_error('[rel=stylesheet]') is None
627 assert get_error('[rel:stylesheet]') == (
628 "Operator expected, got <DELIM ':' at 4>")
629 assert get_error('[rel=stylesheet') == (
630 "Expected ']', got <EOF at 15>")
631 assert get_error(':lang(fr)') is None
632 assert get_error(':lang(fr') == (
633 "Expected an argument, got <EOF at 8>")
634 assert get_error(':contains("foo') == (
635 "Unclosed string at 10")
636 assert get_error('foo!') == (
637 "Expected selector, got <DELIM '!' at 3>")
638
639 # Mis-placed pseudo-elements
640 assert get_error('a:before:empty') == (
641 "Got pseudo-element ::before not at the end of a selector")
642 assert get_error('li:before a') == (
643 "Got pseudo-element ::before not at the end of a selector")
644 assert get_error(':not(:before)') == (
645 "Got pseudo-element ::before inside :not() at 12")
646 assert get_error(':not(:not(a))') == (
647 "Got nested :not()")
648 # }}}
649
650 def test_select(self): # {{{
651 document = etree.fromstring(self.HTML_IDS, parser=etree.XMLParser(recover=True, no_network=True, resolve_entities=False))
652 select = Select(document)
653
654 def select_ids(selector):
655 for elem in select(selector):
656 yield elem.get('id')
657
658 def pcss(main, *selectors, **kwargs):
659 result = list(select_ids(main))
660 for selector in selectors:
661 self.ae(list(select_ids(selector)), result)
662 return result
663 all_ids = pcss('*')
664 self.ae(all_ids[:6], [
665 'html', None, 'link-href', 'link-nohref', None, 'outer-div'])
666 self.ae(all_ids[-1:], ['foobar-span'])
667 self.ae(pcss('div'), ['outer-div', 'li-div', 'foobar-div'])
668 self.ae(pcss('DIV'), [
669 'outer-div', 'li-div', 'foobar-div']) # case-insensitive in HTML
670 self.ae(pcss('div div'), ['li-div'])
671 self.ae(pcss('div, div div'), ['outer-div', 'li-div', 'foobar-div'])
672 self.ae(pcss('a[name]'), ['name-anchor'])
673 self.ae(pcss('a[NAme]'), ['name-anchor']) # case-insensitive in HTML:
674 self.ae(pcss('a[rel]'), ['tag-anchor', 'nofollow-anchor'])
675 self.ae(pcss('a[rel="tag"]'), ['tag-anchor'])
676 self.ae(pcss('a[href*="localhost"]'), ['tag-anchor'])
677 self.ae(pcss('a[href*=""]'), [])
678 self.ae(pcss('a[href^="http"]'), ['tag-anchor', 'nofollow-anchor'])
679 self.ae(pcss('a[href^="http:"]'), ['tag-anchor'])
680 self.ae(pcss('a[href^=""]'), [])
681 self.ae(pcss('a[href$="org"]'), ['nofollow-anchor'])
682 self.ae(pcss('a[href$=""]'), [])
683 self.ae(pcss('div[foobar~="bc"]', 'div[foobar~="cde"]', skip_webkit=True), ['foobar-div'])
684 self.ae(pcss('[foobar~="ab bc"]', '[foobar~=""]', '[foobar~=" \t"]'), [])
685 self.ae(pcss('div[foobar~="cd"]'), [])
686 self.ae(pcss('*[lang|="En"]', '[lang|="En-us"]'), ['second-li'])
687 # Attribute values are case sensitive
688 self.ae(pcss('*[lang|="en"]', '[lang|="en-US"]', skip_webkit=True), [])
689 self.ae(pcss('*[lang|="e"]'), [])
690 self.ae(pcss(':lang("EN")', '*:lang(en-US)', skip_webkit=True), ['second-li', 'li-div'])
691 self.ae(pcss(':lang("e")'), [])
692 self.ae(pcss('li:nth-child(1)', 'li:first-child'), ['first-li'])
693 self.ae(pcss('li:nth-child(3)', '#first-li ~ :nth-child(3)'), ['third-li'])
694 self.ae(pcss('li:nth-child(10)'), [])
695 self.ae(pcss('li:nth-child(2n)', 'li:nth-child(even)', 'li:nth-child(2n+0)'), ['second-li', 'fourth-li', 'sixth-li'])
696 self.ae(pcss('li:nth-child(+2n+1)', 'li:nth-child(odd)'), ['first-li', 'third-li', 'fifth-li', 'seventh-li'])
697 self.ae(pcss('li:nth-child(2n+4)'), ['fourth-li', 'sixth-li'])
698 self.ae(pcss('li:nth-child(3n+1)'), ['first-li', 'fourth-li', 'seventh-li'])
699 self.ae(pcss('li:nth-last-child(0)'), [])
700 self.ae(pcss('li:nth-last-child(1)', 'li:last-child'), ['seventh-li'])
701 self.ae(pcss('li:nth-last-child(2n)', 'li:nth-last-child(even)'), ['second-li', 'fourth-li', 'sixth-li'])
702 self.ae(pcss('li:nth-last-child(2n+2)'), ['second-li', 'fourth-li', 'sixth-li'])
703 self.ae(pcss('ol:first-of-type'), ['first-ol'])
704 self.ae(pcss('ol:nth-child(1)'), [])
705 self.ae(pcss('ol:nth-of-type(2)'), ['second-ol'])
706 self.ae(pcss('ol:nth-last-of-type(1)'), ['second-ol'])
707 self.ae(pcss('span:only-child'), ['foobar-span'])
708 self.ae(pcss('li div:only-child'), ['li-div'])
709 self.ae(pcss('div *:only-child'), ['li-div', 'foobar-span'])
710 self.ae(pcss('p *:only-of-type', skip_webkit=True), ['p-em', 'fieldset'])
711 self.ae(pcss('p:only-of-type', skip_webkit=True), ['paragraph'])
712 self.ae(pcss('a:empty', 'a:EMpty'), ['name-anchor'])
713 self.ae(pcss('li:empty'), ['third-li', 'fourth-li', 'fifth-li', 'sixth-li'])
714 self.ae(pcss(':root', 'html:root', 'li:root'), ['html'])
715 self.ae(pcss('* :root', 'p *:root'), [])
716 self.ae(pcss('.a', '.b', '*.a', 'ol.a'), ['first-ol'])
717 self.ae(pcss('.c', '*.c'), ['first-ol', 'third-li', 'fourth-li'])
718 self.ae(pcss('ol *.c', 'ol li.c', 'li ~ li.c', 'ol > li.c'), [
719 'third-li', 'fourth-li'])
720 self.ae(pcss('#first-li', 'li#first-li', '*#first-li'), ['first-li'])
721 self.ae(pcss('li div', 'li > div', 'div div'), ['li-div'])
722 self.ae(pcss('div > div'), [])
723 self.ae(pcss('div>.c', 'div > .c'), ['first-ol'])
724 self.ae(pcss('div + div'), ['foobar-div'])
725 self.ae(pcss('a ~ a'), ['tag-anchor', 'nofollow-anchor'])
726 self.ae(pcss('a[rel="tag"] ~ a'), ['nofollow-anchor'])
727 self.ae(pcss('ol#first-ol li:last-child'), ['seventh-li'])
728 self.ae(pcss('ol#first-ol *:last-child'), ['li-div', 'seventh-li'])
729 self.ae(pcss('#outer-div:first-child'), ['outer-div'])
730 self.ae(pcss('#outer-div :first-child'), [
731 'name-anchor', 'first-li', 'li-div', 'p-b',
732 'checkbox-fieldset-disabled', 'area-href'])
733 self.ae(pcss('a[href]'), ['tag-anchor', 'nofollow-anchor'])
734 self.ae(pcss(':not(*)'), [])
735 self.ae(pcss('a:not([href])'), ['name-anchor'])
736 self.ae(pcss('ol :Not(li[class])', skip_webkit=True), [
737 'first-li', 'second-li', 'li-div',
738 'fifth-li', 'sixth-li', 'seventh-li'])
739 self.ae(pcss(r'di\a0 v', r'div\['), [])
740 self.ae(pcss(r'[h\a0 ref]', r'[h\]ref]'), [])
741
742 self.assertRaises(ExpressionError, lambda : tuple(select('body:nth-child')))
743
744 select = Select(document, ignore_inappropriate_pseudo_classes=True)
745 self.assertGreater(len(tuple(select('p:hover'))), 0)
746
747 def test_select_shakespeare(self):
748 document = html.document_fromstring(self.HTML_SHAKESPEARE)
749 select = Select(document)
750 def count(s):
751 return sum(1 for r in select(s))
752
753 # Data borrowed from http://mootools.net/slickspeed/
754
755 # Changed from original; probably because I'm only
756 self.ae(count('*'), 249)
757 assert count('div:only-child') == 22 # ?
758 assert count('div:nth-child(even)') == 106
759 assert count('div:nth-child(2n)') == 106
760 assert count('div:nth-child(odd)') == 137
761 assert count('div:nth-child(2n+1)') == 137
762 assert count('div:nth-child(n)') == 243
763 assert count('div:last-child') == 53
764 assert count('div:first-child') == 51
765 assert count('div > div') == 242
766 assert count('div + div') == 190
767 assert count('div ~ div') == 190
768 assert count('body') == 1
769 assert count('body div') == 243
770 assert count('div') == 243
771 assert count('div div') == 242
772 assert count('div div div') == 241
773 assert count('div, div, div') == 243
774 assert count('div, a, span') == 243
775 assert count('.dialog') == 51
776 assert count('div.dialog') == 51
777 assert count('div .dialog') == 51
778 assert count('div.character, div.dialog') == 99
779 assert count('div.direction.dialog') == 0
780 assert count('div.dialog.direction') == 0
781 assert count('div.dialog.scene') == 1
782 assert count('div.scene.scene') == 1
783 assert count('div.scene .scene') == 0
784 assert count('div.direction .dialog ') == 0
785 assert count('div .dialog .direction') == 4
786 assert count('div.dialog .dialog .direction') == 4
787 assert count('#speech5') == 1
788 assert count('div#speech5') == 1
789 assert count('div #speech5') == 1
790 assert count('div.scene div.dialog') == 49
791 assert count('div#scene1 div.dialog div') == 142
792 assert count('#scene1 #speech1') == 1
793 assert count('div[class]') == 103
794 assert count('div[class=dialog]') == 50
795 assert count('div[class^=dia]') == 51
796 assert count('div[class$=log]') == 50
797 assert count('div[class*=sce]') == 1
798 assert count('div[class|=dialog]') == 50 # ? Seems right
799 assert count('div[class~=dialog]') == 51 # ? Seems right
800
801 # }}}
802
803
804 # Run tests {{{
805 def find_tests():
806 return unittest.defaultTestLoader.loadTestsFromTestCase(TestCSSSelectors)
807
808
809 def run_tests(find_tests=find_tests, for_build=False):
810 if not for_build:
811 parser = argparse.ArgumentParser()
812 parser.add_argument('name', nargs='?', default=None,
813 help='The name of the test to run')
814 args = parser.parse_args()
815 if not for_build and args.name and args.name.startswith('.'):
816 tests = find_tests()
817 q = args.name[1:]
818 if not q.startswith('test_'):
819 q = 'test_' + q
820 ans = None
821 try:
822 for test in tests:
823 if test._testMethodName == q:
824 ans = test
825 raise StopIteration()
826 except StopIteration:
827 pass
828 if ans is None:
829 print('No test named %s found' % args.name)
830 raise SystemExit(1)
831 tests = ans
832 else:
833 tests = unittest.defaultTestLoader.loadTestsFromName(args.name) if not for_build and args.name else find_tests()
834 r = unittest.TextTestRunner
835 if for_build:
836 r = r(verbosity=0, buffer=True, failfast=True)
837 else:
838 r = r(verbosity=4)
839 result = r.run(tests)
840 if for_build and result.errors or result.failures:
841 raise SystemExit(1)
842
843
844 if __name__ == '__main__':
845 run_tests()
846 # }}}