Esempio n. 1
0
def test_shortcircuit():
    assert glom(False, Fill(M | "default")) == "default"
    assert glom(True, Fill(M | "default")) == True
    assert glom(True, Fill(M & "default")) == "default"
    with pytest.raises(MatchError):
        glom(False, Fill(M & "default"))
    assert glom(False, ~M) == False
    assert glom(True, Fill(~M | "default")) == "default"
Esempio n. 2
0
def test_ref():
    assert glom([[[]]], Ref('item', [Ref('item')])) == [[[]]]
    with pytest.raises(
            Exception
    ):  # check that it recurses downards and dies on int iteration
        glom([[[1]]], Ref('item', [Ref('item')]))
    assert repr(Ref('item',
                    (T[1], Ref('item')))) == "Ref('item', (T[1], Ref('item')))"

    etree2dicts = Ref(
        'ElementTree', {
            "tag": "tag",
            "text": "text",
            "attrib": "attrib",
            "children": (iter, [Ref('ElementTree')])
        })
    etree2tuples = Fill(
        Ref('ElementTree', (T.tag, Iter(Ref('ElementTree')).all())))
    etree = ElementTree.fromstring('''
    <html>
      <head>
        <title>the title</title>
      </head>
      <body id="the-body">
        <p>A paragraph</p>
      </body>
    </html>''')
    glom(etree, etree2dicts)
    glom(etree, etree2tuples)
Esempio n. 3
0
def test():
    assert glom('abc', Fill((T[0], {T[1]: T[2]}))) == ('a', {'b': 'c'})
    assert glom('123',
                Fill({T[0],
                      frozenset([T[1],
                                 T[2]])})) == {'1', frozenset(['2', '3'])}
    assert glom('xyz', Fill([T[0], T[1], T[2]]))
    assert glom('abc', Fill(lambda t: t.upper())) == 'ABC'
    assert glom('a', Fill(1)) == 1
    assert Fill((T, T, T)).fill(1) == (1, 1, 1)

    target = {'data': [0, 2, 4]}
    assert glom(target, Fill((T['data'][-1], Auto('data.-2')))) == (4, 2)

    assert repr(Auto()) == 'Auto()'
    assert repr(Auto(T)) == 'Auto(T)'

    assert repr(Fill()) == 'Fill()'
    assert repr(Fill(T)) == 'Fill(T)'

    assert repr(Fill(len)) == 'Fill(len)'
Esempio n. 4
0
def test_pattern_matching():
    pattern_matcher = Or(And(Match(1), Val('one')), And(Match(2), Val('two')),
                         And(Match(float), Val('float')))
    assert glom(1, pattern_matcher) == 'one'
    assert glom(1.1, pattern_matcher) == 'float'

    # obligatory fibonacci

    fib = (M > 2) & (lambda n: glom(n - 1, fib) + glom(n - 2, fib)) | T

    assert glom(5, fib) == 8

    factorial = (lambda t: t + 1,
                 Ref('fact', (lambda t: t - 1, (M == 0) & Fill(1) |
                              (S(r=Ref('fact')), S, lambda s: s['r'] * s[T]))))

    assert glom(4, factorial) == 4 * 3 * 2