Пример #1
0
def test_item():
    # Add a tree of 10 items
    items = []
    for i in range(10):
        items.append(Item(id='Foo {}'.format(i)))

        if i > 0:
            items[-1].parent = items[-2]
            items[-2].child.append(items[-1])

    # __init__(parent=...)
    Item(id='Bar 1', parent=items[0])
    assert len(items[0].child) == 2

    # __init__(child=)
    bar2 = Item(id='Bar 2', child=[items[0]])

    # __contains__()
    assert items[0] in bar2
    assert items[-1] in items[0]

    # get_child()
    assert items[0].get_child('Foo 1') == items[1]

    with raises(ValueError):
        items[0].get_child('Foo 2')
Пример #2
0
def test_itemscheme():
    is0 = ItemScheme(id="is0")
    foo0 = Item(id="foo0")

    # With a single Item

    # append()
    is0.append(foo0)

    # __getattr__
    assert is0.foo0 is foo0

    # __getitem__
    assert is0["foo0"] is foo0

    # __contains__
    assert "foo0" in is0
    assert foo0 in is0

    # __len__
    assert len(is0) == 1

    # __repr__
    assert repr(is0) == "<ItemScheme is0 (1 items)>"

    # __iter__
    assert all(i is foo0 for i in is0)

    # With multiple Items

    foo1 = Item(id="foo1")
    foo2 = Item(id="foo2")
    items_list = [foo0, foo1, foo2]
    items_dict = {"foo0": foo0, "foo1": foo1, "foo2": foo2}

    # set with a non-dict
    is0.items = items_list
    assert is0.items == items_dict

    # set with a dict
    is0.items = items_dict
    assert is0.items == items_dict

    # extend()
    is0.items = [foo0]
    is0.extend(items_list)
    assert is0.items == items_dict

    # setdefault()
    bar0 = is0.setdefault(id="bar")
    assert bar0.id == "bar"

    with raises(ValueError):
        is0.setdefault(foo0, id="bar")

    is0.setdefault(id="bar1", parent="foo0")
    bar1 = is0.setdefault(id="bar1", parent=foo0)

    # get_hierarchical()
    assert is0.get_hierarchical("foo0.bar1") == bar1
Пример #3
0
def test_item():
    # Add a tree of 10 items
    items = []
    for i in range(10):
        items.append(Item(id="Foo {}".format(i)))

        if i > 0:
            items[-1].parent = items[-2]
            items[-2].child.append(items[-1])

    # __init__(parent=...)
    Item(id="Bar 1", parent=items[0])
    assert len(items[0].child) == 2

    # __init__(child=)
    bar2 = Item(id="Bar 2", child=[items[0]])

    # __contains__()
    assert items[0] in bar2
    assert items[-1] in items[0]

    # get_child()
    assert items[0].get_child("Foo 1") == items[1]

    with raises(ValueError):
        items[0].get_child("Foo 2")

    # Hierarchical IDs constructed automatically
    assert items[0].child[0].hierarchical_id == "Bar 2.Foo 0.Foo 1"
Пример #4
0
def test_itemscheme():
    is0 = ItemScheme(id='is0')
    foo0 = Item(id='foo0')

    # With a single Item

    # append()
    is0.append(foo0)

    # __getattr__
    assert is0.foo0 is foo0

    # __getitem__
    assert is0['foo0'] is foo0

    # __contains__
    assert 'foo0' in is0
    assert foo0 in is0

    # __len__
    assert len(is0) == 1

    # __repr__
    assert repr(is0) == "<ItemScheme: 'is0', 1 items>"

    # __iter__
    assert all(i is foo0 for i in is0)

    # With multiple Items

    foo1 = Item(id='foo1')
    foo2 = Item(id='foo2')
    items_list = [foo0, foo1, foo2]
    items_dict = {'foo0': foo0, 'foo1': foo1, 'foo2': foo2}

    # set with a non-dict
    is0.items = items_list
    assert is0.items == items_dict

    # set with a dict
    is0.items = items_dict
    assert is0.items == items_dict

    # extend()
    is0.items = [foo0]
    is0.extend(items_list)
    assert is0.items == items_dict

    # setdefault()
    bar0 = is0.setdefault(id='bar')
    assert bar0.id == 'bar'

    with raises(ValueError):
        is0.setdefault(foo0, id='bar')

    is0.setdefault(id='bar1', parent='foo0')
    is0.setdefault(id='bar1', parent=foo0)
Пример #5
0
def test_item():
    items = []
    for i in range(10):
        items.append(Item(id='Foo {}'.format(i)))

        if i > 0:
            items[-1].parent = items[-2]
            items[-2].child.append(items[-1])

    assert items[-1] in items[0]
Пример #6
0
def test_internationalstring():
    # Constructor; the .name attribute is an InternationalString
    i = Item(id='ECB')

    # Set and get using the attribute directly
    i.name.localizations['DE'] = 'Europäische Zentralbank'
    assert i.name.localizations['DE'] == 'Europäische Zentralbank'

    # Set and get using item convenience
    i.name['FR'] = 'Banque centrale européenne'
    assert len(i.name.localizations) == 2
    assert i.name['FR'] == 'Banque centrale européenne'

    # repr() gives all localizations
    assert repr(i.name) == '\n'.join(
        sorted([
            'DE: Europäische Zentralbank',
            'FR: Banque centrale européenne',
        ]))

    # Setting with a string directly sets the value in the default locale
    i.name = 'European Central Bank'
    assert len(i.name.localizations) == 1
    assert i.name.localizations[DEFAULT_LOCALE] == 'European Central Bank'

    # Setting with a (locale, text) tuple
    i.name = ('FI', 'Euroopan keskuspankki')
    assert len(i.name.localizations) == 1

    # Setting with a dict()
    i.name = {'IT': 'Banca centrale europea'}
    assert len(i.name.localizations) == 1

    # Using some other type is an error
    with raises(pydantic.ValidationError):
        i.name = 123

    # Same, but in the constructor
    i2 = Item(id='ECB', name='European Central Bank')

    # str() uses the default locale
    assert str(i2.name) == 'European Central Bank'
Пример #7
0
    def read_message(self, source):
        # Initialize message instance
        msg = DataMessage()

        # Read JSON
        tree = json.load(source)

        # Read the header
        # FIXME KeyError: 'header'
        elem = tree['header']
        msg.header = Header(id=elem['id'],
                            prepared=elem['prepared'],
                            sender=Item(**elem['sender']))

        # pre-fetch some structures for efficient use in series and obs
        structure = tree['structure']

        # Read dimensions and values
        self._dim_level = dict()
        self._dim_values = dict()
        for level_name, level in structure['dimensions'].items():
            for elem in level:
                # Create the Dimension
                d = msg.structure.dimension(id=elem['id'],
                                            order=elem.get('keyPosition', -1))

                # Record the level it appears at
                self._dim_level[d] = level_name

                # Record values
                self._dim_values[d] = list()
                for value in elem.get('values', []):
                    self._dim_values[d].append(
                        KeyValue(id=d.id, value=value['id']))

        # Assign an order to an implicit dimension
        for d in msg.structure.dimensions:
            if d.order == -1:
                d.order = len(msg.structure.dimensions)

        # Determine the dimension at the observation level
        if all([level == 'observation' for level in self._dim_level.values()]):
            dim_at_obs = AllDimensions
        else:
            dim_at_obs = [
                dim for dim, level in self._dim_level.items()
                if level == 'observation'
            ]

        msg.observation_dimension = dim_at_obs

        # Read attributes and values
        self._attr_level = dict()
        self._attr_values = dict()
        for level_name, level in structure['attributes'].items():
            for attr in level:
                # Create a DataAttribute in the DSD
                a = msg.structure.attribute(
                    id=attr['id'],
                    concept_identity=Concept(name=attr['name']),
                )

                # Record the level it appears at
                self._attr_level[a] = level_name

                # Record its values
                self._attr_values[a] = list()
                for value in attr.get('values', []):
                    self._attr_values[a].append(
                        AttributeValue(value=value['name'], value_for=a))

        self.msg = msg

        # Make a SeriesKey for Observations in this DataSet
        ds_key = self._make_key('dataSet')

        # Read DataSets
        for ds in tree['dataSets']:
            msg.data.append(self.read_dataset(ds, ds_key))

        return msg
Пример #8
0
def test_internationalstring():
    # Constructor; the .name attribute is an InternationalString
    i = Item(id='ECB')

    # Set and get using the attribute directly
    i.name.localizations['DE'] = 'Europäische Zentralbank'
    assert i.name.localizations['DE'] == 'Europäische Zentralbank'

    # Set and get using item convenience
    i.name['FR'] = 'Banque centrale européenne'
    assert len(i.name.localizations) == 2
    assert i.name['FR'] == 'Banque centrale européenne'

    # repr() gives all localizations
    assert repr(i.name) == '\n'.join(
        sorted([
            'DE: Europäische Zentralbank',
            'FR: Banque centrale européenne',
        ]))

    # Setting with a string directly sets the value in the default locale
    i.name = 'European Central Bank'
    assert len(i.name.localizations) == 1
    assert i.name.localizations[DEFAULT_LOCALE] == 'European Central Bank'

    # Setting with a (locale, text) tuple
    i.name = ('FI', 'Euroopan keskuspankki')
    assert len(i.name.localizations) == 1

    # Setting with a dict()
    i.name = {'IT': 'Banca centrale europea'}
    assert len(i.name.localizations) == 1

    # Using some other type is an error
    with raises(pydantic.ValidationError):
        i.name = 123

    # Same, but in the constructor
    i2 = Item(id='ECB', name='European Central Bank')

    # str() uses the default locale
    assert str(i2.name) == 'European Central Bank'

    # Creating with name=None raises an exception…
    with raises(pydantic.ValidationError,
                match='none is not an allowed value'):
        Item(id='ECB', name=None)

    # …giving empty dict is equivalent to giving nothing
    i3 = Item(id='ECB', name={})
    assert i3.name.localizations == Item(id='ECB').name.localizations

    # Create with iterable of 2-tuples
    i4 = Item(id='ECB',
              name=[
                  ('DE', 'Europäische Zentralbank'),
                  ('FR', 'Banque centrale européenne'),
              ])
    assert i4.name['FR'] == 'Banque centrale européenne'
Пример #9
0
def test_internationalstring():
    # Constructor; the .name attribute is an InternationalString
    i = Item(id="ECB")

    # Set and get using the attribute directly
    i.name.localizations["DE"] = "Europäische Zentralbank"
    assert i.name.localizations["DE"] == "Europäische Zentralbank"

    # Set and get using item convenience
    i.name["FR"] = "Banque centrale européenne"
    assert len(i.name.localizations) == 2
    assert i.name["FR"] == "Banque centrale européenne"

    # repr() gives all localizations
    assert repr(i.name) == "\n".join(
        sorted(["DE: Europäische Zentralbank", "FR: Banque centrale européenne"])
    )

    # Setting with a string directly sets the value in the default locale
    i.name = "European Central Bank"
    assert len(i.name.localizations) == 1
    assert i.name.localizations[DEFAULT_LOCALE] == "European Central Bank"

    # Setting with a (locale, text) tuple
    i.name = ("FI", "Euroopan keskuspankki")
    assert len(i.name.localizations) == 1

    # Setting with a dict()
    i.name = {"IT": "Banca centrale europea"}
    assert len(i.name.localizations) == 1

    # Using some other type is an error
    with raises(pydantic.ValidationError):
        i.name = 123

    # Same, but in the constructor
    i2 = Item(id="ECB", name="European Central Bank")

    # str() uses the default locale
    assert str(i2.name) == "European Central Bank"

    # Creating with name=None raises an exception…
    with raises(pydantic.ValidationError, match="none is not an allowed value"):
        Item(id="ECB", name=None)

    # …giving empty dict is equivalent to giving nothing
    i3 = Item(id="ECB", name={})
    assert i3.name.localizations == Item(id="ECB").name.localizations

    # Create with iterable of 2-tuples
    i4 = Item(
        id="ECB",
        name=[("DE", "Europäische Zentralbank"), ("FR", "Banque centrale européenne")],
    )
    assert i4.name["FR"] == "Banque centrale européenne"

    # Compares equal with same contents
    is1 = model.InternationalString(en="Foo", fr="Le foo")
    is2 = model.InternationalString(en="Foo", fr="Le foo")
    assert is1 == is2