<commit_before>#!/usr/bin/env python
# coding=utf-8

"""
test_pureyaml
----------------------------------

Tests for `pureyaml` module.
"""
from textwrap import dedent

from pytest import mark

from pureyaml.nodes import *  # noqa
from pureyaml.pureyaml import YAMLParser

skipif = mark.skipif
parser = YAMLParser(debug=True)

def test_basic_single_doc():
    text = dedent("""
        ---
        Hello World
        ...
    """)[1:]

    nodes = parser.parsedebug(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_doc_with_no_end_of_doc_indicator():
    text = dedent("""
        ---
        Hello World
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_2_docs():
    text = dedent("""
        ---
        Hello World
        ...
        ---
        Foo Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')), Doc(Str('Foo Bar')))

    assert nodes == expected

def test_3_docs():
    text = dedent("""
        ---
        Hello World
        ...
        ---
        Foo Bar
        ...
        ---
        More Docs
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(  # :off
        Doc(Str('Hello World')),
        Doc(Str('Foo Bar')),
        Doc(Str('More Docs'))
    )  # :on

    assert nodes == expected

def test_3_docs_no_end_of_doc_indicators():
    text = dedent("""
        ---
        Hello World
        ---
        Foo Bar
        ---
        More Docs
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(  # :off
        Doc(Str('Hello World')),
        Doc(Str('Foo Bar')),
        Doc(Str('More Docs'))
    )  # :on

    assert nodes == expected

def test_implicit_doc():
    text = dedent("""
        Hello World
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_scalar_int():
    text = dedent("""
        ---
        123
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))
    assert nodes == expected

def test_1_item_sequence():
    text = dedent("""
        ---
        - Hello World
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(Str('Hello World', ))))

    assert nodes == expected

def test_2_item_sequence():
    text = dedent("""
        ---
        - Hello World
        - Foo Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Hello World'),
        Str('Foo Bar'),
    )))  # :on

    assert nodes == expected

def test_3_item_sequence():
    text = dedent("""
        ---
        - Hello World
        - Foo Bar
        - More Sequence Items
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Hello World'),
        Str('Foo Bar'),
        Str('More Sequence Items'),
    )))  # :on

    assert nodes == expected

def test_1_item_map():
    text = dedent("""
        ---
        Hello: World
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
    )))  # :on

    assert nodes == expected

def test_2_item_map():
    text = dedent("""
        ---
        Hello: World
        Foo: Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
        (Str('Foo'), Str('Bar')),
    )))  # :on

    assert nodes == expected

def test_3_item_map():
    text = dedent("""
        ---
        Hello: World
        Foo: Bar
        More: Map Items
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
        (Str('Foo'), Str('Bar')),
        (Str('More'), Str('Map Items')),
    )))  # :on

    assert nodes == expected

def test_casting_implicit_int():
    text = dedent("""
        123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))

    assert nodes == expected

def test_casting_doublequoted_string():
    text = dedent("""
        "123"
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('123')))
    assert nodes == expected

def test_casting_doublequoted_string_with_escaped_char():
    text = dedent(r"""
        "She said, \"I Like turtles\" and she meant it!"
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('She said, \\"I Like turtles\\" and she meant it!')))

    assert nodes == expected

def test_casting_singlequoted_string():
    text = dedent("""
        '123'
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('123')))

    assert nodes == expected

def test_casting_singlequoted_string_with_escaped_char():
    text = dedent(r"""
        'She said, \'I Like turtles\' and she meant it!'
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str("She said, \\'I Like turtles\\' and she meant it!")))

    assert nodes == expected

def test_casting_implicit_float():
    text = dedent("""
        123.0
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(123.0)))

    assert nodes == expected

def test_casting_implicit_float_no_leading_digit():
    text = dedent("""
        .123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(.123)))

    assert nodes == expected

def test_casting_explicit_float():
    text = dedent("""
        !!float 123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(123)))

    assert nodes == expected

def test_casting_explicit_str():
    text = dedent("""
        !!str 123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str(123)))

    assert nodes == expected

def test_casting_implicit_bool_true():
    text = dedent("""
        Yes
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Bool(True)))

    assert nodes == expected

def test_casting_implicit_bool_false():
    text = dedent("""
        No
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Bool(False)))

    assert nodes == expected

def test_casting_explicit_str_from_bool():
    text = dedent("""
        !!str Yes
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Yes')))

    assert nodes == expected

def test_uses_context_for_disambiguated_str():
    text = dedent("""
        Yes we have No bananas
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Yes we have No bananas')))

    assert nodes == expected

def test_ignore_comment():
    text = dedent("""
        123 # an integer
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))

    assert nodes == expected

def test_map_with_scalars_and_comments():
    text = dedent("""
        ---
        a: 123                     # an integer
        b: "123"                   # a string, disambiguated by quotes
        c: 123.0                   # a float
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('a'), Int(123)),
        (Str('b'), Str(123)),
        (Str('c'), Float(123))
    )))  # :on

    assert nodes == expected

def test_different_map_with_bools_and_comments():
    text = dedent("""
        ---
        f: !!str Yes               # a string via explicit type
        g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('f'), Str('Yes')),
        (Str('g'), Bool('Yes')),
    )))  # :on

    assert nodes == expected

def test_longer_map_with_scalars_and_comments():
    text = dedent("""
        ---
        a: 123                     # an integer
        b: "123"                   # a string, disambiguated by quotes
        c: 123.0                   # a float
        d: !!float 123             # also a float via explicit data type prefixed by (!!)
        e: !!str 123               # a string, disambiguated by explicit type
        f: !!str Yes               # a string via explicit type
        g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
        h: Yes we have No bananas  # a string, "Yes" and "No" disambiguated by context.
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('a'), Int(123)),
        (Str('b'), Str(123)),
        (Str('c'), Float(123)),
        (Str('d'), Float(123)),
        (Str('e'), Str(123)),
        (Str('f'), Str('Yes')),
        (Str('g'), Bool('Yes')),
        (Str('h'), Str('Yes we have No bananas')),

    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_scalar_item():
    text = dedent("""
        ---
            123
        ...
    """)[1:]
    nodes = parser.parse(text)
    expected = Docs(Doc(Int('123')))

    assert nodes == expected

def test_unnecessary_indent_1_item():
    text = dedent("""
        ---
            - Casablanca
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
    )))  # :on
    assert nodes == expected

def test_unnecessary_indent_1_item_with_comment():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
    )))  # :on
    assert nodes == expected

def test_unnecessary_indent_2_items():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_3_items():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
            - The Man Who Wasnt There
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
        Str('The Man Who Wasnt There'),
    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_3_items_with_dedent():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
            - The Man Who Wasnt There
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
        Str('The Man Who Wasnt There'),
    )))  # :on

    assert nodes == expected

def test_scalar_types():
    # TODO uncomment lines
    text = dedent("""
        ---
        A null: null
        # Also a null: # Empty
        # Not a null: ""
        Booleans a: true
        Booleans b: True
        Booleans c: false
        Booleans d: FALSE
        Booleans e: Yes
        Booleans f: YES
        Booleans g: No
        Booleans h: no
        Integers a: 0
        Integers b: 0o7
        Integers c: 0x3A
        # Integers d: -19
        Floats a: 0.
        # Floats b: -0.0
        Floats c: .5
        Floats d: +12e03
        # Floats d: -2E+05
        Also floats a: .inf
        # Also floats b: -.Inf
        Also floats c: +.INF
        Also floats d: .NAN
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('A null'), Null('null')),
        # (Str('Also a null'), Null(None)),
        # (Str('Not a null'), Str('')),
        (Str('Booleans a'), Bool('true')),
        (Str('Booleans b'), Bool('True')),
        (Str('Booleans c'), Bool('false')),
        (Str('Booleans d'), Bool('False')),
        (Str('Booleans e'), Bool('Yes')),
        (Str('Booleans f'), Bool('YES')),
        (Str('Booleans g'), Bool('No')),
        (Str('Booleans h'), Bool('no')),
        (Str('Integers a'), Int(0)),
        (Str('Integers b'), Int(0o7)),
        (Str('Integers c'), Int(0x3A)),
        # (Str('Integers d'), Int(-19)),
        (Str('Floats a'), Float(0.)),
        # (Str('Floats b'), Float(-0.0)),
        (Str('Floats c'), Float(.5)),
        (Str('Floats d'), Float(+12e03)),
        # (Str('Floats e'), Float(-2E+05)),
        (Str('Also floats a'), Float('.inf')),
        # (Str('Also floats b'), Float('-.Inf')),
        (Str('Also floats c'), Float('+.INF')),
        (Str('Also floats d'), Float('.nan')),
    )))  # :on

    def diff():
        actual_map, expected_map = nodes.value[0].value[0].value, expected.value[0].value[0].value
        for (a_k, a_v), (e_k, e_v) in zip(actual_map, expected_map):

            if a_k.value != e_k.value:
                print('Keys mismatched')
                print('%s:%s' % (a_k, e_k))
                print('%s:%s' % (a_k.value, e_k.value))
            if a_v.value != e_v.value:
                print('Values mismatched')
                print('%s:%s' % (a_v, e_v))
                print('%s:%s' % (a_v.value, e_v.value))

    assert nodes == expected, diff()

@skipif
def test_unnecessary_indent_3_with_edge_items():
    # edges: numbers and text, bool 'No' and text, single quote
    text = dedent("""
        --- # Favorite movies
            - 21 Jump Street
            - se7en
            - North by Northwest
            - The Man Who Wasn't There
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('North by Northwest'),
        Str('The Man Who Wasn\'t There'),
    )))  # :on

    assert nodes == expected

# @skipif
def test_scalar_literal_1_line():
    text = dedent("""
        |
          literal
    """)[1:]

    nodes = parser.parsedebug(text)
    expected = Docs(Doc(Str('literal')))

    assert nodes == expected

# @skipif
def test_scalar_literal_ascii_art():
    text = dedent("""
        --- |
          \//||\/||
          // ||  ||__
    """)[1:]

    nodes = parser.parsedebug(text)
    expected = Docs(Doc(Str('\//||\/||\n// ||  ||__')))

    assert nodes == expected
<commit_msg>cleanup<commit_after>#!/usr/bin/env python
# coding=utf-8

"""
test_pureyaml
----------------------------------

Tests for `pureyaml` module.
"""
from textwrap import dedent

from pytest import mark

from pureyaml.nodes import *  # noqa
from pureyaml.pureyaml import YAMLParser

skipif = mark.skipif
parser = YAMLParser(debug=True)

def test_basic_single_doc():
    text = dedent("""
        ---
        Hello World
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_doc_with_no_end_of_doc_indicator():
    text = dedent("""
        ---
        Hello World
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_2_docs():
    text = dedent("""
        ---
        Hello World
        ...
        ---
        Foo Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')), Doc(Str('Foo Bar')))

    assert nodes == expected

def test_3_docs():
    text = dedent("""
        ---
        Hello World
        ...
        ---
        Foo Bar
        ...
        ---
        More Docs
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(  # :off
        Doc(Str('Hello World')),
        Doc(Str('Foo Bar')),
        Doc(Str('More Docs'))
    )  # :on

    assert nodes == expected

def test_3_docs_no_end_of_doc_indicators():
    text = dedent("""
        ---
        Hello World
        ---
        Foo Bar
        ---
        More Docs
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(  # :off
        Doc(Str('Hello World')),
        Doc(Str('Foo Bar')),
        Doc(Str('More Docs'))
    )  # :on

    assert nodes == expected

def test_implicit_doc():
    text = dedent("""
        Hello World
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Hello World')))

    assert nodes == expected

def test_scalar_int():
    text = dedent("""
        ---
        123
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))
    assert nodes == expected

def test_1_item_sequence():
    text = dedent("""
        ---
        - Hello World
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(Str('Hello World', ))))

    assert nodes == expected

def test_2_item_sequence():
    text = dedent("""
        ---
        - Hello World
        - Foo Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Hello World'),
        Str('Foo Bar'),
    )))  # :on

    assert nodes == expected

def test_3_item_sequence():
    text = dedent("""
        ---
        - Hello World
        - Foo Bar
        - More Sequence Items
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Hello World'),
        Str('Foo Bar'),
        Str('More Sequence Items'),
    )))  # :on

    assert nodes == expected

def test_1_item_map():
    text = dedent("""
        ---
        Hello: World
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
    )))  # :on

    assert nodes == expected

def test_2_item_map():
    text = dedent("""
        ---
        Hello: World
        Foo: Bar
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
        (Str('Foo'), Str('Bar')),
    )))  # :on

    assert nodes == expected

def test_3_item_map():
    text = dedent("""
        ---
        Hello: World
        Foo: Bar
        More: Map Items
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('Hello'), Str('World')),
        (Str('Foo'), Str('Bar')),
        (Str('More'), Str('Map Items')),
    )))  # :on

    assert nodes == expected

def test_casting_implicit_int():
    text = dedent("""
        123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))

    assert nodes == expected

def test_casting_doublequoted_string():
    text = dedent("""
        "123"
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('123')))
    assert nodes == expected

def test_casting_doublequoted_string_with_escaped_char():
    text = dedent(r"""
        "She said, \"I Like turtles\" and she meant it!"
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('She said, \\"I Like turtles\\" and she meant it!')))

    assert nodes == expected

def test_casting_singlequoted_string():
    text = dedent("""
        '123'
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('123')))

    assert nodes == expected

def test_casting_singlequoted_string_with_escaped_char():
    text = dedent(r"""
        'She said, \'I Like turtles\' and she meant it!'
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str("She said, \\'I Like turtles\\' and she meant it!")))

    assert nodes == expected

def test_casting_implicit_float():
    text = dedent("""
        123.0
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(123.0)))

    assert nodes == expected

def test_casting_implicit_float_no_leading_digit():
    text = dedent("""
        .123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(.123)))

    assert nodes == expected

def test_casting_explicit_float():
    text = dedent("""
        !!float 123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Float(123)))

    assert nodes == expected

def test_casting_explicit_str():
    text = dedent("""
        !!str 123
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str(123)))

    assert nodes == expected

def test_casting_implicit_bool_true():
    text = dedent("""
        Yes
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Bool(True)))

    assert nodes == expected

def test_casting_implicit_bool_false():
    text = dedent("""
        No
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Bool(False)))

    assert nodes == expected

def test_casting_explicit_str_from_bool():
    text = dedent("""
        !!str Yes
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Yes')))

    assert nodes == expected

def test_uses_context_for_disambiguated_str():
    text = dedent("""
        Yes we have No bananas
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('Yes we have No bananas')))

    assert nodes == expected

def test_ignore_comment():
    text = dedent("""
        123 # an integer
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Int(123)))

    assert nodes == expected

def test_map_with_scalars_and_comments():
    text = dedent("""
        ---
        a: 123                     # an integer
        b: "123"                   # a string, disambiguated by quotes
        c: 123.0                   # a float
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('a'), Int(123)),
        (Str('b'), Str(123)),
        (Str('c'), Float(123))
    )))  # :on

    assert nodes == expected

def test_different_map_with_bools_and_comments():
    text = dedent("""
        ---
        f: !!str Yes               # a string via explicit type
        g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('f'), Str('Yes')),
        (Str('g'), Bool('Yes')),
    )))  # :on

    assert nodes == expected

def test_longer_map_with_scalars_and_comments():
    text = dedent("""
        ---
        a: 123                     # an integer
        b: "123"                   # a string, disambiguated by quotes
        c: 123.0                   # a float
        d: !!float 123             # also a float via explicit data type prefixed by (!!)
        e: !!str 123               # a string, disambiguated by explicit type
        f: !!str Yes               # a string via explicit type
        g: Yes                     # a boolean True (yaml1.1), string "Yes" (yaml1.2)
        h: Yes we have No bananas  # a string, "Yes" and "No" disambiguated by context.
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('a'), Int(123)),
        (Str('b'), Str(123)),
        (Str('c'), Float(123)),
        (Str('d'), Float(123)),
        (Str('e'), Str(123)),
        (Str('f'), Str('Yes')),
        (Str('g'), Bool('Yes')),
        (Str('h'), Str('Yes we have No bananas')),

    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_scalar_item():
    text = dedent("""
        ---
            123
        ...
    """)[1:]
    nodes = parser.parse(text)
    expected = Docs(Doc(Int('123')))

    assert nodes == expected

def test_unnecessary_indent_1_item():
    text = dedent("""
        ---
            - Casablanca
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
    )))  # :on
    assert nodes == expected

def test_unnecessary_indent_1_item_with_comment():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
    )))  # :on
    assert nodes == expected

def test_unnecessary_indent_2_items():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_3_items():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
            - The Man Who Wasnt There
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
        Str('The Man Who Wasnt There'),
    )))  # :on

    assert nodes == expected

def test_unnecessary_indent_3_items_with_dedent():
    text = dedent("""
        --- # Favorite movies
            - Casablanca
            - South by Southwest
            - The Man Who Wasnt There
        ...
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('South by Southwest'),
        Str('The Man Who Wasnt There'),
    )))  # :on

    assert nodes == expected

def test_scalar_types():
    # TODO uncomment lines
    text = dedent("""
        ---
        A null: null
        # Also a null: # Empty
        # Not a null: ""
        Booleans a: true
        Booleans b: True
        Booleans c: false
        Booleans d: FALSE
        Booleans e: Yes
        Booleans f: YES
        Booleans g: No
        Booleans h: no
        Integers a: 0
        Integers b: 0o7
        Integers c: 0x3A
        # Integers d: -19
        Floats a: 0.
        # Floats b: -0.0
        Floats c: .5
        Floats d: +12e03
        # Floats d: -2E+05
        Also floats a: .inf
        # Also floats b: -.Inf
        Also floats c: +.INF
        Also floats d: .NAN
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Map(  # :off
        (Str('A null'), Null('null')),
        # (Str('Also a null'), Null(None)),
        # (Str('Not a null'), Str('')),
        (Str('Booleans a'), Bool('true')),
        (Str('Booleans b'), Bool('True')),
        (Str('Booleans c'), Bool('false')),
        (Str('Booleans d'), Bool('False')),
        (Str('Booleans e'), Bool('Yes')),
        (Str('Booleans f'), Bool('YES')),
        (Str('Booleans g'), Bool('No')),
        (Str('Booleans h'), Bool('no')),
        (Str('Integers a'), Int(0)),
        (Str('Integers b'), Int(0o7)),
        (Str('Integers c'), Int(0x3A)),
        # (Str('Integers d'), Int(-19)),
        (Str('Floats a'), Float(0.)),
        # (Str('Floats b'), Float(-0.0)),
        (Str('Floats c'), Float(.5)),
        (Str('Floats d'), Float(+12e03)),
        # (Str('Floats e'), Float(-2E+05)),
        (Str('Also floats a'), Float('.inf')),
        # (Str('Also floats b'), Float('-.Inf')),
        (Str('Also floats c'), Float('+.INF')),
        (Str('Also floats d'), Float('.nan')),
    )))  # :on

    def diff():
        actual_map, expected_map = nodes.value[0].value[0].value, expected.value[0].value[0].value
        for (a_k, a_v), (e_k, e_v) in zip(actual_map, expected_map):

            if a_k.value != e_k.value:
                print('Keys mismatched')
                print('%s:%s' % (a_k, e_k))
                print('%s:%s' % (a_k.value, e_k.value))
            if a_v.value != e_v.value:
                print('Values mismatched')
                print('%s:%s' % (a_v, e_v))
                print('%s:%s' % (a_v.value, e_v.value))

    assert nodes == expected, diff()

@skipif
def test_unnecessary_indent_3_with_edge_items():
    # edges: numbers and text, bool 'No' and text, single quote
    text = dedent("""
        --- # Favorite movies
            - 21 Jump Street
            - se7en
            - North by Northwest
            - The Man Who Wasn't There
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Sequence(  # :off
        Str('Casablanca'),
        Str('North by Northwest'),
        Str('The Man Who Wasn\'t There'),
    )))  # :on

    assert nodes == expected

# @skipif
def test_scalar_literal_1_line():
    text = dedent("""
        |
          literal
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('literal')))

    assert nodes == expected

# @skipif
def test_scalar_literal_ascii_art():
    text = dedent("""
        --- |
          \//||\/||
          // ||  ||__
    """)[1:]

    nodes = parser.parse(text)
    expected = Docs(Doc(Str('\//||\/||\n// ||  ||__')))

    assert nodes == expected
<|endoftext|>


<commit_before>from .stims import Stim
from .extractors import Extractor, get_extractor
from .io import load_stims

def extract(stims, extractors, format='df'):
    """ Feature extraction, the lazy way. Pass a list of stimuli and a list of
    extractors, then go have a drink.
    Args:
        stims (list): A list of stims to process. Each element can be either
            a string (a single filename, or a directory containing stims),
            or a Stim object.
        extractors (list): A list of extractors to apply to each Stim. Each
            element can be either a case-insensitive string giving the name of
            the desired extractor (which will be matched against all currently
                available extractors), or an Extractor object.
        format (str): The format to return the data in.
    Returns:
        A list of Timelines--one per stimulus in the original list (in the same
            order).
    """
    _stims = []
    for s in stims:
        if isinstance(s, Stim):
            _stims.append(s)
        else:
            _stims.extend(load_stims(s))

    extractors = [a if isinstance(a, Extractor) else get_extractor(a)
                  for a in extractors]

    return [s.extract(extractors) for s in _stims]
<commit_msg>fix import<commit_after>from .stimuli import Stim
from .extractors import Extractor, get_extractor
from .io import load_stims

def extract(stims, extractors, format='df'):
    """ Feature extraction, the lazy way. Pass a list of stimuli and a list of
    extractors, then go have a drink.
    Args:
        stims (list): A list of stims to process. Each element can be either
            a string (a single filename, or a directory containing stims),
            or a Stim object.
        extractors (list): A list of extractors to apply to each Stim. Each
            element can be either a case-insensitive string giving the name of
            the desired extractor (which will be matched against all currently
                available extractors), or an Extractor object.
        format (str): The format to return the data in.
    Returns:
        A list of Timelines--one per stimulus in the original list (in the same
            order).
    """
    _stims = []
    for s in stims:
        if isinstance(s, Stim):
            _stims.append(s)
        else:
            _stims.extend(load_stims(s))

    extractors = [a if isinstance(a, Extractor) else get_extractor(a)
                  for a in extractors]

    return [s.extract(extractors) for s in _stims]
<|endoftext|>


<commit_before><commit_msg>Use hashlib if available.<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env python3
#
# linearize-hashes.py:  List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#

from http.client import HttpConnection
import json
import re
import base64
import sys
import os
import os.path

settings = {}

def hex_switchEndian(s):
    """ Switches the endianness of a hex string (in pairs of hex chars) """
    pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
    return b''.join(pairList[::-1]).decode()

class BitcoinRPC:
    def __init__(self, host, port, username, password):
        authpair = "%s:%s" % (username, password)
        authpair = authpair.encode('utf-8')
        self.authhdr = b"Basic " + base64.b64encode(authpair)
        self.conn = HttpConnection(host, port=port, timeout=30)

    def execute(self, obj):
        try:
            self.conn.request('POST', '/', json.dumps(obj),
                { 'Authorization' : self.authhdr,
                  'Content-type' : 'application/json' })
        except ConnectionRefusedError:
            print('RPC connection refused. Check RPC settings and the server status.',
                  file=sys.stderr)
            return None

        resp = self.conn.getresponse()
        if resp is None:
            print("JSON-RPC: no response", file=sys.stderr)
            return None

        body = resp.read().decode('utf-8')
        resp_obj = json.loads(body)
        return resp_obj

    @staticmethod
    def build_request(idx, method, params):
        obj = { 'version' : '1.1',
            'method' : method,
            'id' : idx }
        if params is None:
            obj['params'] = []
        else:
            obj['params'] = params
        return obj

    @staticmethod
    def response_is_error(resp_obj):
        return 'error' in resp_obj and resp_obj['error'] is not None

def get_block_hashes(settings, max_blocks_per_call=10000):
    rpc = BitcoinRPC(settings['host'], settings['port'],
             settings['rpcuser'], settings['rpcpassword'])

    height = settings['min_height']
    while height < settings['max_height']+1:
        num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
        batch = []
        for x in range(num_blocks):
            batch.append(rpc.build_request(x, 'getblockhash', [height + x]))

        reply = rpc.execute(batch)
        if reply is None:
            print('Cannot continue. Program will halt.')
            return None

        for x,resp_obj in enumerate(reply):
            if rpc.response_is_error(resp_obj):
                print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)
                sys.exit(1)
            assert(resp_obj['id'] == x) # assume replies are in-sequence
            if settings['rev_hash_bytes'] == 'true':
                resp_obj['result'] = hex_switchEndian(resp_obj['result'])
            print(resp_obj['result'])

        height += num_blocks

def get_rpc_cookie():
    # Open the cookie file
    with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r', encoding="ascii") as f:
        combined = f.readline()
        combined_split = combined.split(":")
        settings['rpcuser'] = combined_split[0]
        settings['rpcpassword'] = combined_split[1]

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: linearize-hashes.py CONFIG-FILE")
        sys.exit(1)

    f = open(sys.argv[1], encoding="utf8")
    for line in f:
        # skip comment lines
        m = re.search('^\s*#', line)
        if m:
            continue

        # parse key=value lines
        m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
        if m is None:
            continue
        settings[m.group(1)] = m.group(2)
    f.close()

    if 'host' not in settings:
        settings['host'] = '127.0.0.1'
    if 'port' not in settings:
        settings['port'] = 8332
    if 'min_height' not in settings:
        settings['min_height'] = 0
    if 'max_height' not in settings:
        settings['max_height'] = 313000
    if 'rev_hash_bytes' not in settings:
        settings['rev_hash_bytes'] = 'false'

    use_userpass = True
    use_datadir = False
    if 'rpcuser' not in settings or 'rpcpassword' not in settings:
        use_userpass = False
    if 'datadir' in settings and not use_userpass:
        use_datadir = True
    if not use_userpass and not use_datadir:
        print("Missing datadir or username and/or password in cfg file", file=sys.stderr)
        sys.exit(1)

    settings['port'] = int(settings['port'])
    settings['min_height'] = int(settings['min_height'])
    settings['max_height'] = int(settings['max_height'])

    # Force hash byte format setting to be lowercase to make comparisons easier.
    settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()

    # Get the rpc user and pass from the cookie if the datadir is set
    if use_datadir:
        get_rpc_cookie()

    get_block_hashes(settings)
<commit_msg>Update linearize-hashes.py<commit_after>#!/usr/bin/env python3
#
# linearize-hashes.py:  List blocks in a linear, no-fork version of the chain.
#
# Copyright (c) 2013-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#

from http.client import HTTPConnection
import json
import re
import base64
import sys
import os
import os.path

settings = {}

def hex_switchEndian(s):
    """ Switches the endianness of a hex string (in pairs of hex chars) """
    pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)]
    return b''.join(pairList[::-1]).decode()

class BitcoinRPC:
    def __init__(self, host, port, username, password):
        authpair = "%s:%s" % (username, password)
        authpair = authpair.encode('utf-8')
        self.authhdr = b"Basic " + base64.b64encode(authpair)
        self.conn = HTTPConnection(host, port=port, timeout=30)

    def execute(self, obj):
        try:
            self.conn.request('POST', '/', json.dumps(obj),
                { 'Authorization' : self.authhdr,
                  'Content-type' : 'application/json' })
        except ConnectionRefusedError:
            print('RPC connection refused. Check RPC settings and the server status.',
                  file=sys.stderr)
            return None

        resp = self.conn.getresponse()
        if resp is None:
            print("JSON-RPC: no response", file=sys.stderr)
            return None

        body = resp.read().decode('utf-8')
        resp_obj = json.loads(body)
        return resp_obj

    @staticmethod
    def build_request(idx, method, params):
        obj = { 'version' : '1.1',
            'method' : method,
            'id' : idx }
        if params is None:
            obj['params'] = []
        else:
            obj['params'] = params
        return obj

    @staticmethod
    def response_is_error(resp_obj):
        return 'error' in resp_obj and resp_obj['error'] is not None

def get_block_hashes(settings, max_blocks_per_call=10000):
    rpc = BitcoinRPC(settings['host'], settings['port'],
             settings['rpcuser'], settings['rpcpassword'])

    height = settings['min_height']
    while height < settings['max_height']+1:
        num_blocks = min(settings['max_height']+1-height, max_blocks_per_call)
        batch = []
        for x in range(num_blocks):
            batch.append(rpc.build_request(x, 'getblockhash', [height + x]))

        reply = rpc.execute(batch)
        if reply is None:
            print('Cannot continue. Program will halt.')
            return None

        for x,resp_obj in enumerate(reply):
            if rpc.response_is_error(resp_obj):
                print('JSON-RPC: error at height', height+x, ': ', resp_obj['error'], file=sys.stderr)
                sys.exit(1)
            assert(resp_obj['id'] == x) # assume replies are in-sequence
            if settings['rev_hash_bytes'] == 'true':
                resp_obj['result'] = hex_switchEndian(resp_obj['result'])
            print(resp_obj['result'])

        height += num_blocks

def get_rpc_cookie():
    # Open the cookie file
    with open(os.path.join(os.path.expanduser(settings['datadir']), '.cookie'), 'r', encoding="ascii") as f:
        combined = f.readline()
        combined_split = combined.split(":")
        settings['rpcuser'] = combined_split[0]
        settings['rpcpassword'] = combined_split[1]

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: linearize-hashes.py CONFIG-FILE")
        sys.exit(1)

    f = open(sys.argv[1], encoding="utf8")
    for line in f:
        # skip comment lines
        m = re.search('^\s*#', line)
        if m:
            continue

        # parse key=value lines
        m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
        if m is None:
            continue
        settings[m.group(1)] = m.group(2)
    f.close()

    if 'host' not in settings:
        settings['host'] = '127.0.0.1'
    if 'port' not in settings:
        settings['port'] = 8332
    if 'min_height' not in settings:
        settings['min_height'] = 0
    if 'max_height' not in settings:
        settings['max_height'] = 313000
    if 'rev_hash_bytes' not in settings:
        settings['rev_hash_bytes'] = 'false'

    use_userpass = True
    use_datadir = False
    if 'rpcuser' not in settings or 'rpcpassword' not in settings:
        use_userpass = False
    if 'datadir' in settings and not use_userpass:
        use_datadir = True
    if not use_userpass and not use_datadir:
        print("Missing datadir or username and/or password in cfg file", file=sys.stderr)
        sys.exit(1)

    settings['port'] = int(settings['port'])
    settings['min_height'] = int(settings['min_height'])
    settings['max_height'] = int(settings['max_height'])

    # Force hash byte format setting to be lowercase to make comparisons easier.
    settings['rev_hash_bytes'] = settings['rev_hash_bytes'].lower()

    # Get the rpc user and pass from the cookie if the datadir is set
    if use_datadir:
        get_rpc_cookie()

    get_block_hashes(settings)
<|endoftext|>


<commit_before>from candidate_generation.candidate_generator_cache import CandidateGeneratorCache
from candidate_generation.neighborhood_candidate_generator import NeighborhoodCandidateGenerator
from database_interface.data_interface.CsvInterface import CsvInterface
from database_interface.data_interface.FreebaseInterface import FreebaseInterface
from database_interface.expansion_strategies.all_through_expansion_strategy import AllThroughExpansionStrategy
from database_interface.expansion_strategies.only_freebase_element_strategy import OnlyFreebaseExpansionStrategy
from database_interface.hypergraph_interface import HypergraphInterface
from database_interface.indexed_interface import IndexedInterface
from experiment_construction.candidate_generator_construction.edge_filter import EdgeFilter

class CandidateGeneratorFactory:

    def construct_candidate_generator(self, index, settings):
        if "prefix" in settings["endpoint"]:
            prefix = settings["endpoint"]["prefix"]
        else:
            prefix = ""

        if settings["endpoint"]["type"] == "sparql":
            database_interface = FreebaseInterface()
            expansion_strategy = OnlyFreebaseExpansionStrategy()
        elif settings["endpoint"]["type"] == "csv":
            database_interface = CsvInterface(settings["endpoint"]["file"])
            expansion_strategy = AllThroughExpansionStrategy()
            prefix = ""

        database = HypergraphInterface(database_interface, expansion_strategy, prefix=prefix)
        database = IndexedInterface(database, index.entity_indexer, index.relation_indexer)

        disk_cache = settings["endpoint"]["disk_cache"] if "disk_cache" in settings["endpoint"] else None
        candidate_generator = NeighborhoodCandidateGenerator(database, neighborhood_search_scope=1,
                                                             extra_literals=True)
        print(settings["endpoint"])
        if "frequency_filter" in settings["endpoint"]:
            print("haha")
            candidate_generator = EdgeFilter(candidate_generator,
                                             settings["endpoint"]["frequency_list"],
                                             settings["endpoint"]["frequency_filter"],
                                             relation_indexer=index.relation_indexer)

        if disk_cache:
            candidate_generator = CandidateGeneratorCache(candidate_generator, disk_cache=disk_cache)

        return candidate_generator
<commit_msg>frequency filter<commit_after>from candidate_generation.candidate_generator_cache import CandidateGeneratorCache
from candidate_generation.neighborhood_candidate_generator import NeighborhoodCandidateGenerator
from database_interface.data_interface.CsvInterface import CsvInterface
from database_interface.data_interface.FreebaseInterface import FreebaseInterface
from database_interface.expansion_strategies.all_through_expansion_strategy import AllThroughExpansionStrategy
from database_interface.expansion_strategies.only_freebase_element_strategy import OnlyFreebaseExpansionStrategy
from database_interface.hypergraph_interface import HypergraphInterface
from database_interface.indexed_interface import IndexedInterface
from experiment_construction.candidate_generator_construction.edge_filter import EdgeFilter

class CandidateGeneratorFactory:

    def construct_candidate_generator(self, index, settings):
        if "prefix" in settings["endpoint"]:
            prefix = settings["endpoint"]["prefix"]
        else:
            prefix = ""

        if settings["endpoint"]["type"] == "sparql":
            database_interface = FreebaseInterface()
            expansion_strategy = OnlyFreebaseExpansionStrategy()
        elif settings["endpoint"]["type"] == "csv":
            database_interface = CsvInterface(settings["endpoint"]["file"])
            expansion_strategy = AllThroughExpansionStrategy()
            prefix = ""

        database = HypergraphInterface(database_interface, expansion_strategy, prefix=prefix)
        database = IndexedInterface(database, index.entity_indexer, index.relation_indexer)
        candidate_generator = NeighborhoodCandidateGenerator(database, neighborhood_search_scope=1,
                                                             extra_literals=True)

        disk_cache = settings["endpoint"]["disk_cache"] if "disk_cache" in settings["endpoint"] else None
        if disk_cache:
            candidate_generator = CandidateGeneratorCache(candidate_generator, disk_cache=disk_cache)

        if "frequency_filter" in settings["endpoint"]:
            print("haha")
            candidate_generator = EdgeFilter(candidate_generator,
                                             settings["endpoint"]["frequency_list"],
                                             settings["endpoint"]["frequency_filter"],
                                             relation_indexer=index.relation_indexer)

        return candidate_generator
<|endoftext|>


<commit_before>from lambda_client import upload
from api_gateway import ApiGatewayConnection
import os
from argparse import ArgumentParser
import json
import yaml
from jsonschema import validate

def get_path_segments(path):
    parts = filter(None, path.split(os.sep))
    return parts

def create_resource_path(api_connection, api_id, path):
    segments = get_path_segments(path)
    resources = api_connection.get_resources(api_id).json()
    is_resource_list = isinstance(resources['_embedded']['item'], list)
    if is_resource_list:
        parent_id = next(
            (x for x in resources['_embedded']
             ['item'] if x['path'] == '/'),
            None)['id']
    else:
        parent_id = resources['_embedded']['item']['id']

    cur_path = "/"
    for segment in segments:
        cur_path += segment
        # see if we've already created the endpoint we're
        # looking for
        previous_created_resource = None if not is_resource_list else next(
            (x for x in resources['_embedded']['item'] if x['path'] == cur_path
             and x['parentId'] == parent_id), None)

        if previous_created_resource:
            resource_json = previous_created_resource
        else:
            create_resource_resp = api_connection.create_resource(
                api_id, parent_id, segment)
            resource_json = create_resource_resp.json()

        parent_id = resource_json["id"]
        cur_path += "/"

    return parent_id

parser = ArgumentParser(description=str('deploy an api to AWS lambda '
                                        'and API Gateway'))
parser.add_argument(
    "--conf", type=str, default=None, required=True,
    help="YAML or JSON swagger config describing your API")

api_group = parser.add_mutually_exclusive_group(required=True)
api_group.add_argument(
    "--api_id", type=str, help="the api you wish to update")
api_group.add_argument("--api_name", type=str,
                       help="name of the new api to create")

args = parser.parse_args()

if args.conf:
    load_str = args.conf
    with open("schema.json") as schema_file:
        schema_text = schema_file.read()
        schema_object = json.loads(schema_text)
    with open(load_str) as foo:
        body = foo.read()
    if "yaml" in load_str:
        # hack to make schema work, likely related to unicode
        spec = json.loads(json.dumps(yaml.load(body)))
    elif "json" in load_str:
        spec = json.loads(body)
    validate(spec, schema_object)
    produces = spec["produces"]
    path_infos = []
    for path_name in spec["paths"]:
        for method in spec["paths"][path_name].keys():
            path_infos.append(
                [path_name,
                 spec["paths"][path_name][method]["x-zip-path"],
                 spec["paths"][path_name][method]["operationId"],
                 spec["paths"][path_name][method]["x-handler-name"],
                 spec["paths"][path_name][method]["x-role-arn"],
                 method.upper(),
                 spec["paths"][path_name][method]["parameters"]])

def create_request_mapping_template(parameters):
    query_params_collection = [
        x for x in parameters if x['in'] in ['query', 'path', 'header']]
    values_dictionary = dict((x["name"], "$input.params('{0}')".format(
        x["name"])) for x in query_params_collection)
    body_params_collection = [
        x for x in parameters if x['in'] in ['body']]
    if len(body_params_collection) == 1:
        values_dictionary[
            body_params_collection[0]['name']] = "$input.json('$')"
    elif len(body_params_collection) > 1:
        raise Exception("there can only be one body parameter per swagger def")
    return json.dumps(values_dictionary)

def create_integration_request(api_id, parent_id, method,
                               gateway_function_arn, creds_arn, content_type,
                               parameters):
    query_params_collection = create_request_mapping_template(parameters)
    mapping_templates = {}
    mapping_templates[content_type] = query_params_collection

    api_connection.create_integration(
        api_id, parent_id, method, gateway_function_arn,
        creds_arn, mapping_templates)

# this role will require the AWSLambdaRole role
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')

if not access_key or not secret_key:
    raise Exception("Critical information is missing")

api_connection = ApiGatewayConnection(access_key, secret_key)

# shouldn't need a third case here, parser should catch it
if args.api_name:
    api_resp = api_connection.create_api(args.api_name)
elif args.api_id:
    api_resp = api_connection.get_api(args.api_id)

for path_info in path_infos:
    path = path_info[0]
    zip_path = path_info[1]
    function_name = path_info[2]
    handler_name = path_info[3]
    creds_arn = path_info[4]
    method = path_info[5]
    parameters = path_info[6]
    status_code = 200
    content_type = "application/json"
    stage_name = "test"

    resp = upload(function_name, open(zip_path),
                  creds_arn,
                  handler_name)

    function_arn = resp["FunctionARN"]
    # rebuild this string concat so that respects region
    gateway_function_arn = str('arn:aws:apigateway:us-east-1:lambda:path'
                               '/2015-03-31/functions/{0}/invocations').format(
        function_arn)
    api_id = api_resp.json()["id"]

    parent_id = create_resource_path(
        api_connection, api_id, path)

    api_connection.create_method(
        api_id, parent_id, method)

    create_integration_request(api_id, parent_id, method,
                               gateway_function_arn, creds_arn, content_type,
                               parameters)

    api_connection.create_integration_response(
        api_id, parent_id, method, status_code)
    api_connection.create_method_response(
        api_id, parent_id, method, status_code)
    api_connection.create_deployment(api_id, stage_name)

print("We worked on {0}".format(api_id))
<commit_msg>replaced generated integration mapping template with static<commit_after>from lambda_client import upload
from api_gateway import ApiGatewayConnection
import os
from argparse import ArgumentParser
import json
import yaml
from jsonschema import validate

def get_path_segments(path):
    parts = filter(None, path.split(os.sep))
    return parts

def create_resource_path(api_connection, api_id, path):
    segments = get_path_segments(path)
    resources = api_connection.get_resources(api_id).json()
    is_resource_list = isinstance(resources['_embedded']['item'], list)
    if is_resource_list:
        parent_id = next(
            (x for x in resources['_embedded']
             ['item'] if x['path'] == '/'),
            None)['id']
    else:
        parent_id = resources['_embedded']['item']['id']

    cur_path = "/"
    for segment in segments:
        cur_path += segment
        # see if we've already created the endpoint we're
        # looking for
        previous_created_resource = None if not is_resource_list else next(
            (x for x in resources['_embedded']['item'] if x['path'] == cur_path
             and x['parentId'] == parent_id), None)

        if previous_created_resource:
            resource_json = previous_created_resource
        else:
            create_resource_resp = api_connection.create_resource(
                api_id, parent_id, segment)
            resource_json = create_resource_resp.json()

        parent_id = resource_json["id"]
        cur_path += "/"

    return parent_id

def create_request_mapping_template(parameters):
    mapping_template = """#set($params = $input.params())
#set($path = $params.path)
#set($querystring = $params.querystring)
#set($headers = $params.header)
#set($body = $input.json('$'))

{
"path" : {
    #foreach ($mapEntry in $path.entrySet())
        "$mapEntry.key":"$mapEntry.value"
        #if($velocityCount < $path.size()),#end
    #end
    },
"querystring" : {
    #foreach ($mapEntry in $querystring.entrySet())
        "$mapEntry.key":"$mapEntry.value"
        #if($velocityCount < $querystring.size()),#end
    #end
    },
"headers" : {
    #foreach ($mapEntry in $headers.entrySet())
        "$mapEntry.key":"$mapEntry.value"
        #if($velocityCount < $headers.size()),#end
    #end
    }

    #if("$!body" != ""),
"body": $body
#end
}"""

    return mapping_template

def create_integration_request(api_id, parent_id, method,
                               gateway_function_arn, creds_arn, content_type,
                               parameters):
    query_params_collection = create_request_mapping_template(parameters)
    mapping_templates = {}
    mapping_templates[content_type] = query_params_collection

    api_connection.create_integration(
        api_id, parent_id, method, gateway_function_arn,
        creds_arn, mapping_templates)

parser = ArgumentParser(description=str('deploy an api to AWS lambda '
                                        'and API Gateway'))
parser.add_argument(
    "--conf", type=str, default=None, required=True,
    help="YAML or JSON swagger config describing your API")

api_group = parser.add_mutually_exclusive_group(required=True)
api_group.add_argument(
    "--api_id", type=str, help="the api you wish to update")
api_group.add_argument("--api_name", type=str,
                       help="name of the new api to create")

args = parser.parse_args()

if args.conf:
    load_str = args.conf
    with open("schema.json") as schema_file:
        schema_text = schema_file.read()
        schema_object = json.loads(schema_text)
    with open(load_str) as foo:
        body = foo.read()
    if "yaml" in load_str:
        # hack to make schema work, likely related to unicode
        spec = json.loads(json.dumps(yaml.load(body)))
    elif "json" in load_str:
        spec = json.loads(body)
    validate(spec, schema_object)
    produces = spec["produces"]
    path_infos = []
    for path_name in spec["paths"]:
        for method in spec["paths"][path_name].keys():
            path_infos.append(
                [path_name,
                 spec["paths"][path_name][method]["x-zip-path"],
                 spec["paths"][path_name][method]["operationId"],
                 spec["paths"][path_name][method]["x-handler-name"],
                 spec["paths"][path_name][method]["x-role-arn"],
                 method.upper(),
                 spec["paths"][path_name][method]["parameters"]])

# this role will require the AWSLambdaRole role
access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')

if not access_key or not secret_key:
    raise Exception("Critical information is missing")

api_connection = ApiGatewayConnection(access_key, secret_key)

# shouldn't need a third case here, parser should catch it
if args.api_name:
    api_resp = api_connection.create_api(args.api_name)
elif args.api_id:
    api_resp = api_connection.get_api(args.api_id)

for path_info in path_infos:
    path = path_info[0]
    zip_path = path_info[1]
    function_name = path_info[2]
    handler_name = path_info[3]
    creds_arn = path_info[4]
    method = path_info[5]
    parameters = path_info[6]
    status_code = 200
    content_type = "application/json"
    stage_name = "test"

    resp = upload(function_name, open(zip_path),
                  creds_arn,
                  handler_name)

    function_arn = resp["FunctionARN"]
    # rebuild this string concat so that respects region
    gateway_function_arn = str('arn:aws:apigateway:us-east-1:lambda:path'
                               '/2015-03-31/functions/{0}/invocations').format(
        function_arn)
    api_id = api_resp.json()["id"]

    parent_id = create_resource_path(
        api_connection, api_id, path)

    api_connection.create_method(
        api_id, parent_id, method)

    create_integration_request(api_id, parent_id, method,
                               gateway_function_arn, creds_arn, content_type,
                               parameters)

    api_connection.create_integration_response(
        api_id, parent_id, method, status_code)
    api_connection.create_method_response(
        api_id, parent_id, method, status_code)
    api_connection.create_deployment(api_id, stage_name)

print("We worked on {0}".format(api_id))
<|endoftext|>


<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

from auto_nag.bzcleaner import BzCleaner
from auto_nag import utils

class oldP1Bug(BzCleaner):

    def __init__(self):
        super(oldP1Bug, self).__init__()
        self.nweeks = utils.get_config(self.name(), 'number_of_weeks', 104)

    def description(self):
        return 'Get old P2 bugs with no activity for the last {} years'.format(self.nweeks/52)

    def name(self):
        return 'old-p2-bug'

    def template(self):
        return 'old_p2_bug.html'

    def subject(self):
        return self.description()

    def get_extra_for_template(self):
        return {'nyears': self.nweeks/52}

    def ignore_bug_summary(self):
        return False

    def get_bz_params(self, date):
        params = {
            'resolution': '---',
            'priority': 'p2',
            'product': ['Core', 'DevTools', 'Firefox'],
            'f1': 'days_elapsed',
            'o1': 'greaterthan',
            'v1': self.nweeks * 7,
            'bug_id': '86950'
        }

        return params

    def get_autofix_change(self):
        return {'comment': {'body': 'Moving to p3 because no activity for at least {} years.\nSee https://github.com/mozilla/bug-handling/blob/master/policy/triage-bugzilla.md#how-do-you-triage for more information'.format(self.nweeks/52)},
                'priority': 'p3'
                }

if __name__ == '__main__':
    oldP1Bug().run()
<commit_msg>remove the limit<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

from auto_nag.bzcleaner import BzCleaner
from auto_nag import utils

class oldP1Bug(BzCleaner):

    def __init__(self):
        super(oldP1Bug, self).__init__()
        self.nweeks = utils.get_config(self.name(), 'number_of_weeks', 104)

    def description(self):
        return 'Get old P2 bugs with no activity for the last {} years'.format(self.nweeks/52)

    def name(self):
        return 'old-p2-bug'

    def template(self):
        return 'old_p2_bug.html'

    def subject(self):
        return self.description()

    def get_extra_for_template(self):
        return {'nyears': self.nweeks/52}

    def ignore_bug_summary(self):
        return False

    def get_bz_params(self, date):
        params = {
            'resolution': '---',
            'priority': 'p2',
            'product': ['Core', 'DevTools', 'Firefox'],
            'f1': 'days_elapsed',
            'o1': 'greaterthan',
            'v1': self.nweeks * 7
        }

        return params

    def get_autofix_change(self):
        return {'comment': {'body': 'Moving to p3 because no activity for at least {} years.\nSee https://github.com/mozilla/bug-handling/blob/master/policy/triage-bugzilla.md#how-do-you-triage for more information'.format(self.nweeks/52)},
                'priority': 'p3'
                }

if __name__ == '__main__':
    oldP1Bug().run()
<|endoftext|>


<commit_before>import json
import logging
import sys
import os

from datetime import datetime

from flask import Flask, redirect, render_template, request, views
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy

from redis import Redis

def get_redis_connection(decode_responses = False, attach_redis_connection = None):
    if attach_redis_connection is not None:
        return attach_redis_connection
    if 'docker' in sys.argv:
        return Redis(host='redis', decode_responses = decode_responses)
    return Redis(decode_responses = decode_responses)

ctime_format = "%a %b %d %H:%M:%S %Y"

logger = logging.getLogger('input_log')
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('transact.log')
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

app = Flask(__name__)

if not os.path.exists('data'):
    os.makedirs('data')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/transact_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

socketio = SocketIO(app)
db = SQLAlchemy(app)

class CreateOrder():
    def __init__(self, redis):
        self.redis = redis

    def perform(self, json_data):
        self.redis.rpush('queue', json_data)

# Orders API
@app.route('/api/v1/orders/', methods=['GET'])
def get_orders():
    all_orders = Order.query.all()
    as_dicts = [order.make_as_dict for order in all_orders]
    return json.dumps(as_dicts)

@app.route('/api/v1/orders/<order_id>', methods=['GET'])
def get_order(order_id):
    try:
        order_id = int(order_id)
    except ValueError:
        return 'Error: order_id must be a number'
    one_order = Order.query.filter(Order.order_id == order_id).first()
    if one_order is None:
        return 'Error: No such record'
    return one_order.make_as_json

@app.route('/api/v1/orders/', methods=['POST'])
def post_order(json_data):
    redis = get_redis_connection()
    handler = CreateOrder(redis)
    handler.perform(json_data)

# Page: New order form
@app.route('/new', methods=['GET'])
def get_new_order():
    return render_template('orders/new-order.html')

@app.route('/new', methods=['POST'])
def receive_new_order():
    message = request.form.get('message', '')
    drink = {
        'g&t': 'Gin & Tonic',
        'espresso-martini': 'Espresso Martini',
        'negroni': 'Negroni',
        'beer': 'Beer',
        'other': request.form.get('other')
    }.get(request.form.get('drink'))
    if drink is None:
        return (
            'Something\'s wrong with your order, '
            'perhaps you meant to select "Other".',
            400)
    broadcast(drink, message)
    order = Order(drink, message)
    json_data = order.make_as_json
    post_order(json_data)
    return ('drink', 204)

@app.route('/', methods=['GET'])
def get_index_page():
    return redirect('/orders', code=302)

@app.route('/orders', methods=['GET'])
def get_orders_page():
    all_orders = Order.query.all()
    return render_template('/orders/index.html', orders = all_orders)

@app.route('/live', methods=['GET'])
def get_live_orders():
    return render_template('/orders/live-orders.html')

def broadcast(drink, message):
    socketio.emit(
        'incomming',
        {
            'drink': drink,
            'message': message
        },
        broadcast=True
    )

class Order(db.Model):

    order_id = db.Column(db.Integer, primary_key = True)
    drink = db.Column(db.String(64), nullable = False)
    message = db.Column(db.String(256), nullable = False)
    order_received = db.Column(db.DateTime)

    def __init__(self, drink, message, order_received = None):
        if order_received is None:
            order_received = datetime.now()
        if not isinstance(order_received, datetime):
            try:
                order_received = datetime.strptime(order_received, ctime_format)
            except ValueError:
                raise ValueError('order_received must be datetime instance')
        if False in (isinstance(drink, str), isinstance(message, str)):
            raise ValueError('drink and message must be strings')
        self.order_received = order_received
        self.drink = drink
        self.message = message

    def save_order(self, database, commit=True):
        database.session.add(self)
        if commit: database.session.commit()

    def __repr__(self):
        return 'Order("{}", "{}", "{}")'.format(
            self.drink, self.message, self.order_received)

    @property
    def nicely_formatted(self):
        return '{}, {} (order received: {})'.format(
            self.drink, self.message, self.order_received.ctime())

    @property
    def make_as_json(self):
        return json.dumps([self.make_as_dict])

    @property
    def make_as_dict(self):
        return {
            'drink': self.drink,
            'message': self.message,
            'order_received': self.order_received.ctime()}

def consumer(redis, database):
    while True:
        source, orders = redis.blpop(['queue'])
        if source == 'queue':
            for order in json.loads(orders):
                Order(**order).save_order(db, commit = False)
            database.session.commit()

def prepare_demo_data():
    dummy_orders = [Order(*_) for _ in (
        ('Negroni', 'If you bring it here fast, I\'ll sing you a song.'),
        ('Espresso Martini', 'Hurry up, I\'m thirsty!'),
        ('Strawberry Daiquiri', 'Last time I had this was at a Bieber concert'),
        ('Magic Potion', 'Ya wouldn\'t happen to have any tiramisu, would ya?'),
        ('Injection attack', '<script> a = function(){ return "DROP TABLE Users or whatever"}</script>'),
        ('Rosy Martini', 'Shaken not stirred'))]
    dummy_data = [order.make_as_dict for order in dummy_orders]
    json_data = json.dumps(dummy_data)
    return json_data

if __name__ == '__main__':
    db.create_all()
    try:
        if 'dbwriter' in sys.argv:
            if len(Order.query.all()) == 0:
                print('Preparing demo data...')
                json_data = prepare_demo_data()
                post_order(json_data)
            redis = get_redis_connection(decode_responses = True)
            consumer(redis, db)
        else:
            socketio.run(app, host='0.0.0.0')
    except KeyboardInterrupt:
        logger.info('Server shut down by user')
<commit_msg>consumer now takes database model class as an argument, making it completely generic<commit_after>import json
import logging
import sys
import os

from datetime import datetime

from flask import Flask, redirect, render_template, request, views
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy

from redis import Redis

def get_redis_connection(decode_responses = False, attach_redis_connection = None):
    if attach_redis_connection is not None:
        return attach_redis_connection
    if 'docker' in sys.argv:
        return Redis(host='redis', decode_responses = decode_responses)
    return Redis(decode_responses = decode_responses)

ctime_format = "%a %b %d %H:%M:%S %Y"

logger = logging.getLogger('input_log')
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('transact.log')
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

app = Flask(__name__)

if not os.path.exists('data'):
    os.makedirs('data')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data/transact_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

socketio = SocketIO(app)
db = SQLAlchemy(app)

class CreateOrder():
    def __init__(self, redis):
        self.redis = redis

    def perform(self, json_data):
        self.redis.rpush('queue', json_data)

# Orders API
@app.route('/api/v1/orders/', methods=['GET'])
def get_orders():
    all_orders = Order.query.all()
    as_dicts = [order.make_as_dict for order in all_orders]
    return json.dumps(as_dicts)

@app.route('/api/v1/orders/<order_id>', methods=['GET'])
def get_order(order_id):
    try:
        order_id = int(order_id)
    except ValueError:
        return 'Error: order_id must be a number'
    one_order = Order.query.filter(Order.order_id == order_id).first()
    if one_order is None:
        return 'Error: No such record'
    return one_order.make_as_json

@app.route('/api/v1/orders/', methods=['POST'])
def post_order(json_data):
    redis = get_redis_connection()
    handler = CreateOrder(redis)
    handler.perform(json_data)

# Page: New order form
@app.route('/new', methods=['GET'])
def get_new_order():
    return render_template('orders/new-order.html')

@app.route('/new', methods=['POST'])
def receive_new_order():
    message = request.form.get('message', '')
    drink = {
        'g&t': 'Gin & Tonic',
        'espresso-martini': 'Espresso Martini',
        'negroni': 'Negroni',
        'beer': 'Beer',
        'other': request.form.get('other')
    }.get(request.form.get('drink'))
    if drink is None:
        return (
            'Something\'s wrong with your order, '
            'perhaps you meant to select "Other".',
            400)
    broadcast(drink, message)
    order = Order(drink, message)
    json_data = order.make_as_json
    post_order(json_data)
    return ('drink', 204)

@app.route('/', methods=['GET'])
def get_index_page():
    return redirect('/orders', code=302)

@app.route('/orders', methods=['GET'])
def get_orders_page():
    all_orders = Order.query.all()
    return render_template('/orders/index.html', orders = all_orders)

@app.route('/live', methods=['GET'])
def get_live_orders():
    return render_template('/orders/live-orders.html')

def broadcast(drink, message):
    socketio.emit(
        'incomming',
        {
            'drink': drink,
            'message': message
        },
        broadcast=True
    )

class Order(db.Model):

    order_id = db.Column(db.Integer, primary_key = True)
    drink = db.Column(db.String(64), nullable = False)
    message = db.Column(db.String(256), nullable = False)
    order_received = db.Column(db.DateTime)

    def __init__(self, drink, message, order_received = None):
        if order_received is None:
            order_received = datetime.now()
        if not isinstance(order_received, datetime):
            try:
                order_received = datetime.strptime(order_received, ctime_format)
            except ValueError:
                raise ValueError('order_received must be datetime instance')
        if False in (isinstance(drink, str), isinstance(message, str)):
            raise ValueError('drink and message must be strings')
        self.order_received = order_received
        self.drink = drink
        self.message = message

    def save_order(self, database, commit=True):
        database.session.add(self)
        if commit: database.session.commit()

    def __repr__(self):
        return 'Order("{}", "{}", "{}")'.format(
            self.drink, self.message, self.order_received)

    @property
    def nicely_formatted(self):
        return '{}, {} (order received: {})'.format(
            self.drink, self.message, self.order_received.ctime())

    @property
    def make_as_json(self):
        return json.dumps([self.make_as_dict])

    @property
    def make_as_dict(self):
        return {
            'drink': self.drink,
            'message': self.message,
            'order_received': self.order_received.ctime()}

def consumer(redis, database, model_class):
    while True:
        source, orders = redis.blpop(['queue'])
        if source == 'queue':
            for order in json.loads(orders):
                model_class(**order).save_order(db, commit = False)
            database.session.commit()

def prepare_demo_data():
    dummy_orders = [Order(*_) for _ in (
        ('Negroni', 'If you bring it here fast, I\'ll sing you a song.'),
        ('Espresso Martini', 'Hurry up, I\'m thirsty!'),
        ('Strawberry Daiquiri', 'Last time I had this was at a Bieber concert'),
        ('Magic Potion', 'Ya wouldn\'t happen to have any tiramisu, would ya?'),
        ('Injection attack', '<script> a = function(){ return "DROP TABLE Users or whatever"}</script>'),
        ('Rosy Martini', 'Shaken not stirred'))]
    dummy_data = [order.make_as_dict for order in dummy_orders]
    json_data = json.dumps(dummy_data)
    return json_data

if __name__ == '__main__':
    db.create_all()
    try:
        if 'dbwriter' in sys.argv:
            if len(Order.query.all()) == 0:
                print('Preparing demo data...')
                json_data = prepare_demo_data()
                post_order(json_data)
            redis = get_redis_connection(decode_responses = True)
            consumer(redis, db, Order)
        else:
            socketio.run(app, host='0.0.0.0')
    except KeyboardInterrupt:
        logger.info('Server shut down by user')
<|endoftext|>


<commit_before>#!/usr/bin/env python

import os
from os.path import abspath, join, dirname
import unittest

import unittest_helper
from modipyd.pyscript import PyScript

class TestPyScript(unittest_helper.TestCase):

    def test_abspath(self):
        self.assertRaises(RuntimeError, PyScript, 'runtests.py')

    def test_not_found(self):
        filepath = abspath(join(dirname(__file__), 'not_found.py'))
        self.assertRaises(RuntimeError, PyScript, filepath)

    def test_init(self):
        filepath = abspath(join(dirname(__file__), 'runtests.py'))
        script = PyScript(filepath)
        self.assertNotNone(script)
        self.assertEqual(filepath, script.filename)

    def test_bytecode_file(self):
        """Tests compiled byte-code file"""
        filepath = abspath(__file__)
        pypath = os.path.splitext(filepath)[0] + ".py"
        pycpath = pypath + "c"

        if not os.path.exists(pycpath):
            import py_compile
            print "Compile", pycpath
            py_compile.compile(pypath, pycpath)
            self.assert_(os.path.exists(pycpath))

        script = PyScript(pycpath)
        self.assertNotNone(script)
        self.assertEqual(pycpath, script.filename)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Added assertion<commit_after>#!/usr/bin/env python

import os
from os.path import abspath, join, dirname
import unittest

import unittest_helper
from modipyd.pyscript import PyScript

class TestPyScript(unittest_helper.TestCase):

    def test_abspath(self):
        self.assertRaises(RuntimeError, PyScript, 'runtests.py')

    def test_not_found(self):
        filepath = abspath(join(dirname(__file__), 'not_found.py'))
        self.assertRaises(RuntimeError, PyScript, filepath)

    def test_init(self):
        filepath = abspath(join(dirname(__file__), 'runtests.py'))
        script = PyScript(filepath)
        self.assertNotNone(script)
        self.assertEqual(filepath, script.filename)

    def test_bytecode_file(self):
        """Tests compiled byte-code file"""
        filepath = abspath(__file__)
        pypath = os.path.splitext(filepath)[0] + ".py"
        pycpath = pypath + "c"

        assert pypath.endswith(".py")
        assert pycpath.endswith(".pyc")

        if not os.path.exists(pycpath):
            import py_compile
            print "Compile", pycpath
            py_compile.compile(pypath, pycpath)
            self.assert_(os.path.exists(pycpath))

        script = PyScript(pycpath)
        self.assertNotNone(script)
        self.assertEqual(pycpath, script.filename)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>import unittest
import skrf as rf
from scipy.constants import *

class MediaTestCase():
        """Base class, contains tests for all media."""
	def test_propagation_constant(self):
		self.media.propagation_constant

	def test_characterisitc_impedance_value(self):
		self.media.characteristic_impedance

	def test_match(self):
		self.media.match()

	def test_load(self):
		self.media.load(1)

	def test_short(self):
		self.media.short()

	def test_open(self):
		self.media.open()

	def test_capacitor(self):
		self.media.capacitor(1)

	def test_inductor(self):
		self.media.inductor(1)

	def test_impedance_mismatch(self):
		self.media.impedance_mismatch(1,2)

	def test_tee(self):
		self.media.tee()

	def test_splitter(self):
		self.media.splitter(4)

	def test_thru(self):
		self.media.thru()

	def test_line(self):
		self.media.line(1)

	def test_delay_load(self):
		self.media.delay_load(1,2)

	def test_delay_short(self):
		self.media.delay_short(1)

	def test_delay_open(self):
		self.media.delay_open(1)

	def test_shunt_delay_load(self):
		self.media.shunt_delay_load(1,1)

	def test_shunt_delay_short(self):
		self.media.shunt_delay_short(1)

	def test_shunt_delay_open(self):
		self.media.shunt_delay_open(1)

class FreespaceTestCase(MediaTestCase, unittest.TestCase):
	def setUp(self):
		self.frequency = rf.Frequency(75,110,101,'ghz')
		self.media = rf.media.Freespace(self.frequency)

	def test_characterisitc_impedance_value(self):
		self.assertEqual(round(self.media.characteristic_impedance[0].real) , 377)

class CPWTestCase(MediaTestCase, unittest.TestCase):
	def setUp(self):
		self.frequency = rf.Frequency(75,110,101,'ghz')
		self.media = rf.media.CPW(\
			frequency=self.frequency,
			w=10e-6,
			s=5e-6,
			ep_r=11.7,
			t=1e-6,
			rho=22e-9)

class RectangularWaveguideTestCase(MediaTestCase, unittest.TestCase):
	def setUp(self):
		self.frequency = rf.Frequency(75,110,101,'ghz')
		self.media = rf.media.RectangularWaveguide(\
			frequency=self.frequency,
			a=100*mil,
			)

class DistributedCircuitTestCase(MediaTestCase, unittest.TestCase):
	def setUp(self):
		self.frequency = rf.Frequency(75,110,101,'ghz')
		self.media = rf.media.DistributedCircuit(\
			frequency=self.frequency,
			I=1,C=1,R=0,G=0
			)

suite = unittest.TestSuite()
loader = unittest.TestLoader()

suite.addTests([\
	loader.loadTestsFromTestCase(FreespaceTestCase),
	loader.loadTestsFromTestCase(CPWTestCase),
	loader.loadTestsFromTestCase(RectangularWaveguideTestCase),
	loader.loadTestsFromTestCase(DistributedCircuitTestCase),

	])

#suite = unittest.TestLoader().loadTestsFromTestCase(FreespaceTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
<commit_msg>fixed indent on testMedia.py<commit_after>import unittest
import skrf as rf
from scipy.constants import *

class MediaTestCase():
    """Base class, contains tests for all media."""
    def test_propagation_constant(self):
        self.media.propagation_constant

    def test_characterisitc_impedance_value(self):
        self.media.characteristic_impedance

    def test_match(self):
        self.media.match()

    def test_load(self):
        self.media.load(1)

    def test_short(self):
        self.media.short()

    def test_open(self):
        self.media.open()

    def test_capacitor(self):
        self.media.capacitor(1)

    def test_inductor(self):
        self.media.inductor(1)

    def test_impedance_mismatch(self):
        self.media.impedance_mismatch(1, 2)

    def test_tee(self):
        self.media.tee()

    def test_splitter(self):
        self.media.splitter(4)

    def test_thru(self):
        self.media.thru()

    def test_line(self):
        self.media.line(1)

    def test_delay_load(self):
        self.media.delay_load(1,2)

    def test_delay_short(self):
        self.media.delay_short(1)

    def test_delay_open(self):
        self.media.delay_open(1)

    def test_shunt_delay_load(self):
        self.media.shunt_delay_load(1,1)

    def test_shunt_delay_short(self):
        self.media.shunt_delay_short(1)

    def test_shunt_delay_open(self):
        self.media.shunt_delay_open(1)

class FreespaceTestCase(MediaTestCase, unittest.TestCase):
    def setUp(self):
        self.frequency = rf.Frequency(75,110,101,'ghz')
        self.media = rf.media.Freespace(self.frequency)

    def test_characterisitc_impedance_value(self):
        self.assertEqual(round(\
            self.media.characteristic_impedance[0].real), 377)

class CPWTestCase(MediaTestCase, unittest.TestCase):
    def setUp(self):
        self.frequency = rf.Frequency(75,110,101,'ghz')
        self.media = rf.media.CPW(\
            frequency=self.frequency,
            w=10e-6,
            s=5e-6,
            ep_r=11.7,
            t=1e-6,
            rho=22e-9)

class RectangularWaveguideTestCase(MediaTestCase, unittest.TestCase):
    def setUp(self):
        self.frequency = rf.Frequency(75,110,101,'ghz')
        self.media = rf.media.RectangularWaveguide(\
            frequency=self.frequency,
            a=100*mil,
            )

class DistributedCircuitTestCase(MediaTestCase, unittest.TestCase):
    def setUp(self):
        self.frequency = rf.Frequency(75,110,101,'ghz')
        self.media = rf.media.DistributedCircuit(\
            frequency=self.frequency,
            I=1,C=1,R=0,G=0
            )

suite = unittest.TestSuite()
loader = unittest.TestLoader()

suite.addTests([\
    loader.loadTestsFromTestCase(FreespaceTestCase),
    loader.loadTestsFromTestCase(CPWTestCase),
    loader.loadTestsFromTestCase(RectangularWaveguideTestCase),
    loader.loadTestsFromTestCase(DistributedCircuitTestCase),
    ])

#suite = unittest.TestLoader().loadTestsFromTestCase(FreespaceTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import telebot
import os

from utils import store_user_location
from weather import get_current_weather_in_location, is_bad_weather, get_5day_forecast_in_location

# Creating the bot
TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN') # Token previously stored in an environment var
bot = telebot.TeleBot(TOKEN)

# The decorator (@bot.message_handler) indicates the type of messages that will activate this function
#@bot.message_handler(content_types=['location'])
def answer_if_I_have_to_worry_from_location_message(message):

    # Getting the current weather
    weathers = get_current_weather_in_location(message)

    # Checking if it's raining/snowing/thunderstorming/etc
    I_need_to_worry = [is_bad_weather(weather) for weather in weathers]

    if True in I_need_to_worry:
        bot.reply_to(message, 'Males notícies... Si tens roba estesa, ja cal que la llaves altra volta')
    else:
        bot.reply_to(message, 'Pots estar tranquil, que fa bon temps!')

# Method temporarily disabled
#@bot.message_handler(commands=['lavadora'])
def check_5day_forecast_from_location(message):
    """Method that indicates if there will be any bad weather in the following 5 days"""

    weathers = get_5day_forecast_in_location(message)

    # Checking if it's raining/snowing/thunderstorming/etc
    I_need_to_worry = [is_bad_weather(weather) for weather in weathers]

    if True in I_need_to_worry:
        bot.reply_to(message, 'Et recomane mirar bé el temps abans, ha de ploure en els pròxims 5 dies')
    else:
        bot.reply_to(message, 'Pots estar tranquil, que fa i farà bon temps!')

@bot.message_handler(content_types=['location'])
def update_user_location(message):
    store_user_location(message.from_user, message.location)

@bot.message_handler(regexp='^ping$')
def test_that_bot_works(message):
    bot.reply_to(message, 'ACK')

# Starting the bot
bot.polling(none_stop=True)
<commit_msg>Enabled "Lavadora" command<commit_after># -*- coding: utf-8 -*-
import telebot
import os

from utils import store_user_location
from weather import get_current_weather_in_location, is_bad_weather, get_5day_forecast_in_location

# Creating the bot
TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN') # Token previously stored in an environment var
bot = telebot.TeleBot(TOKEN)

# The decorator (@bot.message_handler) indicates the type of messages that will activate this function
#@bot.message_handler(content_types=['location'])
def answer_if_I_have_to_worry_from_location_message(message):

    # Getting the current weather
    weathers = get_current_weather_in_location(message)

    # Checking if it's raining/snowing/thunderstorming/etc
    I_need_to_worry = [is_bad_weather(weather) for weather in weathers]

    if True in I_need_to_worry:
        bot.reply_to(message, 'Males notícies... Si tens roba estesa, ja cal que la llaves altra volta')
    else:
        bot.reply_to(message, 'Pots estar tranquil, que fa bon temps!')

# Method temporarily disabled
@bot.message_handler(commands=['lavadora'])
def check_5day_forecast_from_location(message):
    """Method that indicates if there will be any bad weather in the following 5 days"""

    weathers = get_5day_forecast_in_location(message)

    # Checking if it's raining/snowing/thunderstorming/etc
    I_need_to_worry = [is_bad_weather(weather) for weather in weathers]

    if True in I_need_to_worry:
        bot.reply_to(message, 'Et recomane mirar bé el temps abans, ha de ploure en els pròxims 5 dies')
    else:
        bot.reply_to(message, 'Pots estar tranquil, que fa i farà bon temps!')

@bot.message_handler(content_types=['location'])
def update_user_location(message):
    store_user_location(message.from_user, message.location)

@bot.message_handler(regexp='^ping$')
def test_that_bot_works(message):
    bot.reply_to(message, 'ACK')

# Starting the bot
bot.polling(none_stop=True)
<|endoftext|>