def test_missing_keys(): """Adding computations that refer to missing keys raises KeyError.""" r = Reporter() r.add('a', 3) r.add('d', 4) def gen(other): """A generator for apply().""" return (lambda a, b: a * b, 'a', other) # One missing key with pytest.raises(KeyError, match=r"\['b'\]"): r.add_product('ab', 'a', 'b') # Two missing keys with pytest.raises(KeyError, match=r"\['c', 'b'\]"): r.add_product('abc', 'c', 'a', 'b') # Using apply() targeted at non-existent keys also raises an Exception with pytest.raises(KeyError, match=r"\['e', 'f'\]"): r.apply(gen, 'd', 'e', 'f') # add(..., strict=True) checks str or Key arguments g = Key('g', 'hi') with pytest.raises(KeyError, match=r"\['b', g:h-i\]"): r.add('foo', (computations.product, 'a', 'b', g), strict=True) # aggregate() and disaggregate() call add(), which raises the exception with pytest.raises(KeyError, match=r"\[g:h-i\]"): r.aggregate(g, 'tag', 'i') with pytest.raises(KeyError, match=r"\[g:h-i\]"): r.disaggregate(g, 'j')
def test_reporter_add(): """Adding computations that refer to missing keys raises KeyError.""" r = Reporter() r.add('a', 3) r.add('d', 4) # Adding an existing key with strict=True with pytest.raises(KeyExistsError, match=r"key 'a' already exists"): r.add('a', 5, strict=True) def gen(other): """A generator for apply().""" return (lambda a, b: a * b, 'a', other) def msg(*keys): """Return a regex for str(MissingKeyError(*keys)).""" return 'required keys {!r} not defined'.format(tuple(keys)) \ .replace('(', '\\(') \ .replace(')', '\\)') # One missing key with pytest.raises(MissingKeyError, match=msg('b')): r.add_product('ab', 'a', 'b') # Two missing keys with pytest.raises(MissingKeyError, match=msg('c', 'b')): r.add_product('abc', 'c', 'a', 'b') # Using apply() targeted at non-existent keys also raises an Exception with pytest.raises(MissingKeyError, match=msg('e', 'f')): r.apply(gen, 'd', 'e', 'f') # add(..., strict=True) checks str or Key arguments g = Key('g', 'hi') with pytest.raises(MissingKeyError, match=msg('b', g)): r.add('foo', (computations.product, 'a', 'b', g), strict=True) # aggregate() and disaggregate() call add(), which raises the exception with pytest.raises(MissingKeyError, match=msg(g)): r.aggregate(g, 'tag', 'i') with pytest.raises(MissingKeyError, match=msg(g)): r.disaggregate(g, 'j') # add(..., sums=True) also adds partial sums r.add('foo:a-b-c', [], sums=True) assert 'foo:b' in r # add(name, ...) where name is the name of a computation r.add('select', 'bar', 'a', indexers={'dim': ['d0', 'd1', 'd2']}) # add(name, ...) with keyword arguments not recognized by the computation # raises an exception msg = "unexpected keyword argument 'bad_kwarg'" with pytest.raises(TypeError, match=msg): r.add('select', 'bar', 'a', bad_kwarg='foo', index=True)