File: utils.py

package info (click to toggle)
python-crispy-bootstrap5 2024.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 664 kB
  • sloc: python: 1,949; sh: 6; makefile: 3
file content (44 lines) | stat: -rw-r--r-- 1,357 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import os
from pathlib import Path

from crispy_forms.utils import render_crispy_form
from django.test.html import Element, parse_html

TEST_DIR = os.path.dirname(os.path.abspath(__file__))


def contains_partial(haystack, needle, ignore_needle_children=False):
    """Search for a html element with at least the corresponding elements
    (other elements may be present in the matched element from the haystack)
    """
    if not isinstance(haystack, Element):
        haystack = parse_html(haystack)
    if not isinstance(needle, Element):
        needle = parse_html(needle)

    if len(needle.children) > 0 and not ignore_needle_children:
        raise NotImplementedError(
            "contains_partial does not check needle's children:%s"
            % str(needle.children)
        )

    if needle.name == haystack.name and set(needle.attributes).issubset(
        haystack.attributes
    ):
        return True
    return any(
        contains_partial(child, needle, ignore_needle_children=ignore_needle_children)
        for child in haystack.children
        if isinstance(child, Element)
    )


def parse_expected(expected_file):
    test_file = Path(TEST_DIR) / "results" / expected_file
    with open(test_file) as f:
        return parse_html(f.read())


def parse_form(form):
    html = render_crispy_form(form)
    return parse_html(html)