<commit_before>import pickle
import platform

import pytest

from tri_struct import FrozenStruct, merged, DefaultStruct, to_default_struct
from tri_struct._pystruct import Struct as PyStruct

try:
    from tri_struct._cstruct import _Struct as CStruct
except ImportError:
    CStruct = None

@pytest.fixture(scope="module",
                params=filter(None, [CStruct, PyStruct]),
                ids=[name for (name, cls) in [("CStruct", CStruct),
                                              ("PyStruct", PyStruct)]
                     if cls is not None])
def Struct(request):
    return request.param

def test_pybasestruct(Struct):
    s = Struct(a=1)
    assert s['a'] == 1
    assert s.a == 1

    s.b = 2
    assert s['b'] == 2

def test_constructor(Struct):
    s = Struct(a=1, b=2, c=3)
    assert s == Struct(dict(a=1, b=2, c=3))
    assert s == Struct([('a', 1), ('b', 2), ('c', 3)])
    assert s == Struct((k, v) for k, v in zip('abc', (1, 2, 3)))

def test_get_item(Struct):
    s = Struct(a=1, b=2, c=3)
    assert 1 == s['a']
    assert 1 == s.a
    assert 1 == s.get('a')

def test_set_item(Struct):
    s = Struct(a=1, b=2, c=3)
    s['a'] = 8
    assert 8 == s['a']
    assert 8 == s.a

def test_isinstance(Struct):
    s = Struct()
    assert isinstance(s, dict)

    class FooStruct(Struct):
        pass

    f = FooStruct(x=17)
    assert isinstance(f, Struct)

def test_containment(Struct):
    s = Struct(c=3)
    assert 3 not in s
    assert 'c' in s

def test_copy(Struct):
    s = Struct(a=1, b=2, c=3)
    q = s.copy()

    assert 'a' in q
    assert 'b' in q
    assert 'c' in q

    q.x = 6
    with pytest.raises(AttributeError) as e:
        # noinspection PyStatementEffect
        s.x

    assert "'Struct' object has no attribute 'x'" in str(e)

    class MyStruct(Struct):
        pass

    s = MyStruct()
    q = s.copy()

    assert type(s) == type(q)

def test_to_dict(Struct):
    s = Struct(a=1, b=2, c=3)
    assert {'a': 1, 'b': 2, 'c': 3} == dict(s)

def test_items(Struct):
    s = Struct(a=1, b=2, c=3)
    assert [('a', 1), ('b', 2), ('c', 3)] == sorted(s.items())

def test_no_longer_has_dict(Struct):
    s = Struct()
    with pytest.raises(AttributeError) as e:
        s.__dict__
    assert "'Struct' object has no attribute '__dict__'" in str(e)

    fs = FrozenStruct()
    with pytest.raises(AttributeError) as e:
        fs.__dict__
    assert "'%s' object has no attribute '__dict__'" % FrozenStruct.__name__ in str(e)

def test_shadow_methods(Struct):
    if platform.python_implementation() == "PyPy":
        method_str = "<bound method Struct.get of Struct"
    else:
        method_str = "<built-in method get of Struct object at"

    s = Struct(not_get=17)
    assert method_str in str(s.get)

    s = Struct(get=17)
    assert 17 == s.get

    del s.get

    assert method_str in str(s.get)

def test_hash(Struct):
    s = Struct(x=17)
    with pytest.raises(TypeError) as e:
        hash(s)
    if platform.python_implementation() == "PyPy":
        assert "" in str(e)
    else:
        assert "unhashable type: 'Struct'" in str(e)

    f = FrozenStruct(x=17)
    assert isinstance(hash(f), int)
    assert '_hash' not in f.keys()

def test_equality(Struct):
    a = Struct()
    b = Struct()

    assert a == b

def test_del(Struct):
    s = Struct(a=1)
    del s.a
    assert s.get('a', 'sentinel') == 'sentinel'
    with pytest.raises(AttributeError) as e:
        del s.a
    assert str(e.value) == "'Struct' object has no attribute 'a'"

def test_stable_str(Struct):
    assert str(Struct(b=1, a=2)) == 'Struct(a=2, b=1)'

def test_recursive_repr(Struct):
    s = Struct()
    s.s = s

    assert str(s) == 'Struct(s=Struct(...))'

    # test fix for use-after-free
    s = Struct()
    s.a = s
    s.b = s
    assert repr(s) == 'Struct(a=Struct(...), b=Struct(...))'

def test_missing_method(Struct):
    class MyStruct(Struct):
        def __missing__(self, key):
            return 1

    m = MyStruct()

    # the missing method should override attributes on dict access
    # assert m['get'] == 1

    # but not on attribute access
    assert m.get == MyStruct.get.__get__(m)

    # the missing method should be called for attr access, on missing attribute
    assert m.bar == 1

##
# because of class name & module renaming, pickling the different
# implementations won't, unless you also switch the tri_struct.Struct
# implementation to match
##
@pytest.mark.skipif(CStruct is None, reason="CStruct not available")
def test_pickle_cstruct():
    import tri_struct

    _Struct = tri_struct.Struct
    try:
        tri_struct.Struct = CStruct
        s = CStruct(x=17)
        assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
        assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))
    finally:
        tri_struct.Struct = _Struct

def test_pickle_pystruct():
    import tri_struct

    _Struct = tri_struct.Struct
    try:
        tri_struct.Struct = PyStruct
        s = PyStruct(x=17)
        assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
        assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))
    finally:
        tri_struct.Struct = _Struct

def test_frozen_struct(Struct):
    f1 = FrozenStruct(x=17)
    f2 = FrozenStruct(x=17)
    assert f1 == f2
    assert hash(f1) == hash(f2)

    assert f1 in {f1}
    assert f2 in {f1}
    assert f1 not in {FrozenStruct(x=42)}
    assert f1 not in {FrozenStruct(y=17)}

    assert Struct(x=17) == FrozenStruct(x=17)

def test_modify_frozen_struct():
    f = FrozenStruct(x=17)
    with pytest.raises(TypeError) as e:
        f.x = 42
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f['x'] = 42
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.update(dict(x=42))
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.setdefault('foo', 11)
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.clear()
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        del f.x
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        del f['x']
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

def test_pickle_frozen_struct():
    s = FrozenStruct(x=17)
    assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
    assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))

def test_merged(Struct):
    assert Struct(x=1, y=2) == merged(Struct(x=1), Struct(y=2))
    assert Struct(x=1, y=2) == merged(Struct(x=1), FrozenStruct(y=2))
    assert FrozenStruct(x=1, y=2) == merged(FrozenStruct(x=1), Struct(y=2))
    assert {} == merged()
    assert Struct(x=1, y=2) == merged(Struct(x=1), y=2)

def test_merged_with_kwarg_constructor(Struct):
    class MyStruct(Struct):
        def __init__(self, **kwargs):
            super(MyStruct, self).__init__(**kwargs)

    s = MyStruct(foo='foo')
    assert MyStruct(foo='foo', bar='bar') == merged(s, dict(bar='bar'))

def test_merge_to_other_type(Struct):
    s1 = Struct(x=1)
    s2 = dict(y=2)
    m = merged(FrozenStruct(), s1, s2)
    assert FrozenStruct(x=1, y=2) == m
    assert isinstance(m, FrozenStruct)

def test_default_struct():
    d = DefaultStruct()
    assert type(d.a) is DefaultStruct

    d.a.b.c = 17
    d.a.d.e = 42
    d.x
    assert {'a': {'b': {'c': 17},
                  'd': {'e': 42}},
            'x': {}} == d

def test_default_struct_with_list():
    d = DefaultStruct(list)
    d.a.append(17)
    assert dict(a=[17]) == d

def test_to_default_struct():
    d = to_default_struct({
        'a': {'b': {'c': 17},
              'd': DefaultStruct(e=42)}})

    d.x.y = 'z'

    assert {'a': {'b': {'c': 17},
                  'd': {'e': 42}},
            'x': {'y': 'z'}} == d

def test_repr_with_value_exception(Struct):
    class MyException(Exception):
        pass

    with pytest.raises(MyException):
        class Fisk:
            def __repr__(self):
                raise MyException("bummer")

        repr(Struct({'a': Fisk()}))

def test_module_attribute(Struct):
    assert Struct.__module__ == 'tri_struct'

def test_frozen_struct_cache_actually_caches():
    f = FrozenStruct(a=1, b=2)
    old_hash = hash(f)
    dict.__setitem__(f, 'a', 2)
    assert hash(f) == old_hash
    assert f._hash == old_hash
<commit_msg>Fixed test that failed on pypy3<commit_after>import pickle
import platform

import pytest

from tri_struct import FrozenStruct, merged, DefaultStruct, to_default_struct
from tri_struct._pystruct import Struct as PyStruct

try:
    from tri_struct._cstruct import _Struct as CStruct
except ImportError:
    CStruct = None

@pytest.fixture(scope="module",
                params=filter(None, [CStruct, PyStruct]),
                ids=[name for (name, cls) in [("CStruct", CStruct),
                                              ("PyStruct", PyStruct)]
                     if cls is not None])
def Struct(request):
    return request.param

def test_pybasestruct(Struct):
    s = Struct(a=1)
    assert s['a'] == 1
    assert s.a == 1

    s.b = 2
    assert s['b'] == 2

def test_constructor(Struct):
    s = Struct(a=1, b=2, c=3)
    assert s == Struct(dict(a=1, b=2, c=3))
    assert s == Struct([('a', 1), ('b', 2), ('c', 3)])
    assert s == Struct((k, v) for k, v in zip('abc', (1, 2, 3)))

def test_get_item(Struct):
    s = Struct(a=1, b=2, c=3)
    assert 1 == s['a']
    assert 1 == s.a
    assert 1 == s.get('a')

def test_set_item(Struct):
    s = Struct(a=1, b=2, c=3)
    s['a'] = 8
    assert 8 == s['a']
    assert 8 == s.a

def test_isinstance(Struct):
    s = Struct()
    assert isinstance(s, dict)

    class FooStruct(Struct):
        pass

    f = FooStruct(x=17)
    assert isinstance(f, Struct)

def test_containment(Struct):
    s = Struct(c=3)
    assert 3 not in s
    assert 'c' in s

def test_copy(Struct):
    s = Struct(a=1, b=2, c=3)
    q = s.copy()

    assert 'a' in q
    assert 'b' in q
    assert 'c' in q

    q.x = 6
    with pytest.raises(AttributeError) as e:
        # noinspection PyStatementEffect
        s.x

    assert "'Struct' object has no attribute 'x'" in str(e)

    class MyStruct(Struct):
        pass

    s = MyStruct()
    q = s.copy()

    assert type(s) == type(q)

def test_to_dict(Struct):
    s = Struct(a=1, b=2, c=3)
    assert {'a': 1, 'b': 2, 'c': 3} == dict(s)

def test_items(Struct):
    s = Struct(a=1, b=2, c=3)
    assert [('a', 1), ('b', 2), ('c', 3)] == sorted(s.items())

def test_no_longer_has_dict(Struct):
    s = Struct()
    with pytest.raises(AttributeError) as e:
        s.__dict__
    assert "'Struct' object has no attribute '__dict__'" in str(e)

    fs = FrozenStruct()
    with pytest.raises(AttributeError) as e:
        fs.__dict__
    assert "'%s' object has no attribute '__dict__'" % FrozenStruct.__name__ in str(e)

def test_shadow_methods(Struct):
    if platform.python_implementation() == "PyPy":
        method_str = "<bound method dict.get of Struct"
    else:
        method_str = "<built-in method get of Struct object at"

    s = Struct(not_get=17)
    assert method_str in str(s.get)

    s = Struct(get=17)
    assert 17 == s.get

    del s.get

    assert method_str in str(s.get)

def test_hash(Struct):
    s = Struct(x=17)
    with pytest.raises(TypeError) as e:
        hash(s)
    if platform.python_implementation() == "PyPy":
        assert "" in str(e)
    else:
        assert "unhashable type: 'Struct'" in str(e)

    f = FrozenStruct(x=17)
    assert isinstance(hash(f), int)
    assert '_hash' not in f.keys()

def test_equality(Struct):
    a = Struct()
    b = Struct()

    assert a == b

def test_del(Struct):
    s = Struct(a=1)
    del s.a
    assert s.get('a', 'sentinel') == 'sentinel'
    with pytest.raises(AttributeError) as e:
        del s.a
    assert str(e.value) == "'Struct' object has no attribute 'a'"

def test_stable_str(Struct):
    assert str(Struct(b=1, a=2)) == 'Struct(a=2, b=1)'

def test_recursive_repr(Struct):
    s = Struct()
    s.s = s

    assert str(s) == 'Struct(s=Struct(...))'

    # test fix for use-after-free
    s = Struct()
    s.a = s
    s.b = s
    assert repr(s) == 'Struct(a=Struct(...), b=Struct(...))'

def test_missing_method(Struct):
    class MyStruct(Struct):
        def __missing__(self, key):
            return 1

    m = MyStruct()

    # the missing method should override attributes on dict access
    # assert m['get'] == 1

    # but not on attribute access
    assert m.get == MyStruct.get.__get__(m)

    # the missing method should be called for attr access, on missing attribute
    assert m.bar == 1

##
# because of class name & module renaming, pickling the different
# implementations won't, unless you also switch the tri_struct.Struct
# implementation to match
##
@pytest.mark.skipif(CStruct is None, reason="CStruct not available")
def test_pickle_cstruct():
    import tri_struct

    _Struct = tri_struct.Struct
    try:
        tri_struct.Struct = CStruct
        s = CStruct(x=17)
        assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
        assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))
    finally:
        tri_struct.Struct = _Struct

def test_pickle_pystruct():
    import tri_struct

    _Struct = tri_struct.Struct
    try:
        tri_struct.Struct = PyStruct
        s = PyStruct(x=17)
        assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
        assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))
    finally:
        tri_struct.Struct = _Struct

def test_frozen_struct(Struct):
    f1 = FrozenStruct(x=17)
    f2 = FrozenStruct(x=17)
    assert f1 == f2
    assert hash(f1) == hash(f2)

    assert f1 in {f1}
    assert f2 in {f1}
    assert f1 not in {FrozenStruct(x=42)}
    assert f1 not in {FrozenStruct(y=17)}

    assert Struct(x=17) == FrozenStruct(x=17)

def test_modify_frozen_struct():
    f = FrozenStruct(x=17)
    with pytest.raises(TypeError) as e:
        f.x = 42
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f['x'] = 42
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.update(dict(x=42))
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.setdefault('foo', 11)
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        f.clear()
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        del f.x
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

    with pytest.raises(TypeError) as e:
        del f['x']
    assert "'FrozenStruct' object attributes are read-only" == str(e.value)

def test_pickle_frozen_struct():
    s = FrozenStruct(x=17)
    assert s == pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
    assert type(s) == type(pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL)))

def test_merged(Struct):
    assert Struct(x=1, y=2) == merged(Struct(x=1), Struct(y=2))
    assert Struct(x=1, y=2) == merged(Struct(x=1), FrozenStruct(y=2))
    assert FrozenStruct(x=1, y=2) == merged(FrozenStruct(x=1), Struct(y=2))
    assert {} == merged()
    assert Struct(x=1, y=2) == merged(Struct(x=1), y=2)

def test_merged_with_kwarg_constructor(Struct):
    class MyStruct(Struct):
        def __init__(self, **kwargs):
            super(MyStruct, self).__init__(**kwargs)

    s = MyStruct(foo='foo')
    assert MyStruct(foo='foo', bar='bar') == merged(s, dict(bar='bar'))

def test_merge_to_other_type(Struct):
    s1 = Struct(x=1)
    s2 = dict(y=2)
    m = merged(FrozenStruct(), s1, s2)
    assert FrozenStruct(x=1, y=2) == m
    assert isinstance(m, FrozenStruct)

def test_default_struct():
    d = DefaultStruct()
    assert type(d.a) is DefaultStruct

    d.a.b.c = 17
    d.a.d.e = 42
    d.x
    assert {'a': {'b': {'c': 17},
                  'd': {'e': 42}},
            'x': {}} == d

def test_default_struct_with_list():
    d = DefaultStruct(list)
    d.a.append(17)
    assert dict(a=[17]) == d

def test_to_default_struct():
    d = to_default_struct({
        'a': {'b': {'c': 17},
              'd': DefaultStruct(e=42)}})

    d.x.y = 'z'

    assert {'a': {'b': {'c': 17},
                  'd': {'e': 42}},
            'x': {'y': 'z'}} == d

def test_repr_with_value_exception(Struct):
    class MyException(Exception):
        pass

    with pytest.raises(MyException):
        class Fisk:
            def __repr__(self):
                raise MyException("bummer")

        repr(Struct({'a': Fisk()}))

def test_module_attribute(Struct):
    assert Struct.__module__ == 'tri_struct'

def test_frozen_struct_cache_actually_caches():
    f = FrozenStruct(a=1, b=2)
    old_hash = hash(f)
    dict.__setitem__(f, 'a', 2)
    assert hash(f) == old_hash
    assert f._hash == old_hash
<|endoftext|>


<commit_before>
import unittest

from units.trivia import check_answer

class TestCheckAnswer(unittest.TestCase):

    def test_correct_answer(self):
        self.assertTrue(check_answer("correct", "correct"))

    def test_incorrect_answer(self):
        self.assertFalse(check_answer("correct", "incorrect"))

if __name__ == "__main__":
    unittest.main()
<commit_msg>[Tests] Test trivia answers in parentheses with article prefixes<commit_after>
import unittest

from units.trivia import check_answer

class TestCheckAnswer(unittest.TestCase):

    def test_correct_answer(self):
        self.assertTrue(check_answer("correct", "correct"))

    def test_incorrect_answer(self):
        self.assertFalse(check_answer("correct", "incorrect"))

    def test_parentheses_with_article_prefix(self):
        self.assertTrue(
            check_answer(
                "the ISS (the International Space Station)",
                "International Space Station"
            )
        )
        self.assertTrue(
            check_answer("Holland (The Netherlands)", "Netherlands")
        )

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


<commit_before>from sqlalchemy_continuum import vacuum

from tests import TestCase

class TestVacuum(TestCase):
    def test_deletes_futile_versions(self):
        history_objects = [
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=1,
                operation_type=1
            ),
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=2,
                operation_type=1
            )
        ]

        self.session.add_all(history_objects)
        self.session.commit()

        vacuum(self.session, self.Article)
        assert history_objects[0] not in self.session.deleted
        assert history_objects[1] in self.session.deleted
<commit_msg>More tests for vacuum<commit_after>from sqlalchemy_continuum import vacuum

from tests import TestCase

class TestVacuum(TestCase):
    def test_deletes_futile_versions(self):
        history_objects = [
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=1,
                operation_type=1
            ),
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=2,
                operation_type=1
            ),
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=3,
                operation_type=1
            )
        ]

        self.session.add_all(history_objects)
        self.session.commit()

        vacuum(self.session, self.Article)
        assert history_objects[0] not in self.session.deleted
        assert history_objects[1] in self.session.deleted
        assert history_objects[2] in self.session.deleted

    def test_does_not_delete_versions_with_actual_changes(self):
        history_objects = [
            self.ArticleHistory(
                id=1,
                name=u'Some article',
                transaction_id=1,
                operation_type=1
            ),
            self.ArticleHistory(
                id=1,
                name=u'Some other article',
                transaction_id=2,
                operation_type=1
            )
        ]

        self.session.add_all(history_objects)
        self.session.commit()

        vacuum(self.session, self.Article)
        assert history_objects[0] not in self.session.deleted
        assert history_objects[1] not in self.session.deleted
<|endoftext|>


<commit_before>import os
import sys
import time

import pytest

from bit.crypto import ECDSA_SHA256, EllipticCurvePrivateKey
from bit.curve import Point
from bit.keygen import generate_private_key
from bit.wallet import BaseKey, Key, PrivateKey, PrivateKeyTestnet, wif_to_key
from .samples import (
    BITCOIN_ADDRESS, BITCOIN_ADDRESS_TEST, PRIVATE_KEY_DER,
    PRIVATE_KEY_HEX, PRIVATE_KEY_NUM, PRIVATE_KEY_PEM,
    PUBLIC_KEY_COMPRESSED, PUBLIC_KEY_UNCOMPRESSED, PUBLIC_KEY_X,
    PUBLIC_KEY_Y, WALLET_FORMAT_COMPRESSED_MAIN, WALLET_FORMAT_COMPRESSED_TEST,
    WALLET_FORMAT_MAIN, WALLET_FORMAT_TEST
)

TRAVIS = 'TRAVIS' in os.environ

class TestWIFToKey:
    def test_compressed_main(self):
        key = wif_to_key(WALLET_FORMAT_COMPRESSED_MAIN)
        assert isinstance(key, PrivateKey)
        assert key.is_compressed()

    def test_uncompressed_main(self):
        key = wif_to_key(WALLET_FORMAT_MAIN)
        assert isinstance(key, PrivateKey)
        assert not key.is_compressed()

    def test_compressed_test(self):
        key = wif_to_key(WALLET_FORMAT_COMPRESSED_TEST)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.is_compressed()

    def test_uncompressed_test(self):
        key = wif_to_key(WALLET_FORMAT_TEST)
        assert isinstance(key, PrivateKeyTestnet)
        assert not key.is_compressed()

class TestBaseKey:
    def test_init_default(self):
        base_key = BaseKey()

        assert isinstance(base_key._pk, EllipticCurvePrivateKey)
        assert len(base_key.public_key) == 33

    def test_init_from_key(self):
        pk = generate_private_key()
        base_key = BaseKey(pk)
        assert base_key._pk == pk

    def test_init_wif_error(self):
        with pytest.raises(TypeError):
            BaseKey(b'\x00')

    def test_public_key_compressed(self):
        base_key = BaseKey(WALLET_FORMAT_COMPRESSED_MAIN)
        assert base_key.public_key == PUBLIC_KEY_COMPRESSED

    def test_public_key_uncompressed(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.public_key == PUBLIC_KEY_UNCOMPRESSED

    def test_public_point(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.public_point == Point(PUBLIC_KEY_X, PUBLIC_KEY_Y)
        assert base_key.public_point == Point(PUBLIC_KEY_X, PUBLIC_KEY_Y)

    def test_sign(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        public_key = base_key._pk.public_key()
        assert public_key.verify(signature, PUBLIC_KEY_COMPRESSED, ECDSA_SHA256)

    def test_verify_success(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        assert base_key.verify(signature, PUBLIC_KEY_COMPRESSED)

    def test_verify_failure(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        assert not base_key.verify(signature, PUBLIC_KEY_UNCOMPRESSED)

    def test_to_hex(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_hex() == PRIVATE_KEY_HEX

    def test_to_der(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_der() == PRIVATE_KEY_DER

    def test_to_pem(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_pem() == PRIVATE_KEY_PEM

    def test_to_int(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_int() == PRIVATE_KEY_NUM

    def test_is_compressed(self):
        assert BaseKey(WALLET_FORMAT_COMPRESSED_MAIN).is_compressed() is True
        assert BaseKey(WALLET_FORMAT_MAIN).is_compressed() is False

    def test_equal(self):
        assert BaseKey(WALLET_FORMAT_COMPRESSED_MAIN) == BaseKey(WALLET_FORMAT_COMPRESSED_MAIN)

class TestPrivateKey:
    def test_alias(self):
        assert Key == PrivateKey

    def test_init_default(self):
        private_key = PrivateKey()

        assert private_key._address is None
        assert private_key.balance == 0
        assert private_key.unspents == []
        assert private_key.transactions == []

    def test_address(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        assert private_key.address == BITCOIN_ADDRESS
        assert private_key.address == BITCOIN_ADDRESS

    def test_to_wif(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        assert private_key.to_wif() == WALLET_FORMAT_MAIN

        private_key = PrivateKey(WALLET_FORMAT_COMPRESSED_MAIN)
        assert private_key.to_wif() == WALLET_FORMAT_COMPRESSED_MAIN

    def test_get_balance(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        balance = int(private_key.get_balance())
        assert balance == private_key.balance

    def test_get_unspent(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        unspent = private_key.get_unspents()
        assert unspent == private_key.unspents

    def test_get_transactions(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        transactions = private_key.get_transactions()
        assert transactions == private_key.transactions

    def test_from_hex(self):
        key = PrivateKey.from_hex(PRIVATE_KEY_HEX)
        assert isinstance(key, PrivateKey)
        assert key.to_hex() == PRIVATE_KEY_HEX

    def test_from_der(self):
        key = PrivateKey.from_der(PRIVATE_KEY_DER)
        assert isinstance(key, PrivateKey)
        assert key.to_der() == PRIVATE_KEY_DER

    def test_from_pem(self):
        key = PrivateKey.from_pem(PRIVATE_KEY_PEM)
        assert isinstance(key, PrivateKey)
        assert key.to_pem() == PRIVATE_KEY_PEM

    def test_from_int(self):
        key = PrivateKey.from_int(PRIVATE_KEY_NUM)
        assert isinstance(key, PrivateKey)
        assert key.to_int() == PRIVATE_KEY_NUM

    def test_repr(self):
        assert repr(PrivateKey(WALLET_FORMAT_MAIN)) == '<PrivateKey: 1ELReFsTCUY2mfaDTy32qxYiT49z786eFg>'

class TestPrivateKeyTestnet:
    def test_init_default(self):
        private_key = PrivateKeyTestnet()

        assert private_key._address is None
        assert private_key.balance == 0
        assert private_key.unspents == []
        assert private_key.transactions == []

    def test_address(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        assert private_key.address == BITCOIN_ADDRESS_TEST
        assert private_key.address == BITCOIN_ADDRESS_TEST

    def test_to_wif(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        assert private_key.to_wif() == WALLET_FORMAT_TEST

        private_key = PrivateKeyTestnet(WALLET_FORMAT_COMPRESSED_TEST)
        assert private_key.to_wif() == WALLET_FORMAT_COMPRESSED_TEST

    def test_get_balance(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        balance = int(private_key.get_balance())
        assert balance == private_key.balance

    def test_get_unspent(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        unspent = private_key.get_unspents()
        assert unspent == private_key.unspents

    def test_get_transactions(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        transactions = private_key.get_transactions()
        assert transactions == private_key.transactions

    def test_send(self):
        if TRAVIS and sys.version_info[:2] != (3, 6):
            assert True
        else:
            private_key = PrivateKeyTestnet(WALLET_FORMAT_COMPRESSED_TEST)
            private_key.get_unspents()
            initial = len(private_key.get_transactions())
            private_key.send([('n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi', 1, 'jpy')])

            current = initial
            tries = 0

            while tries < 15:  # pragma: no cover
                current = len(private_key.get_transactions())
                if current > initial:
                    break
                time.sleep(5)
                tries += 1

            assert current > initial

    def test_from_hex(self):
        key = PrivateKeyTestnet.from_hex(PRIVATE_KEY_HEX)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_hex() == PRIVATE_KEY_HEX

    def test_from_der(self):
        key = PrivateKeyTestnet.from_der(PRIVATE_KEY_DER)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_der() == PRIVATE_KEY_DER

    def test_from_pem(self):
        key = PrivateKeyTestnet.from_pem(PRIVATE_KEY_PEM)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_pem() == PRIVATE_KEY_PEM

    def test_from_int(self):
        key = PrivateKeyTestnet.from_int(PRIVATE_KEY_NUM)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_int() == PRIVATE_KEY_NUM

    def test_repr(self):
        assert repr(PrivateKeyTestnet(WALLET_FORMAT_MAIN)) == '<PrivateKeyTestnet: mtrNwJxS1VyHYn3qBY1Qfsm3K3kh1mGRMS>'
<commit_msg>this is bollocks<commit_after>import os
import sys
import time

import pytest

from bit.crypto import ECDSA_SHA256, EllipticCurvePrivateKey
from bit.curve import Point
from bit.keygen import generate_private_key
from bit.wallet import BaseKey, Key, PrivateKey, PrivateKeyTestnet, wif_to_key
from .samples import (
    BITCOIN_ADDRESS, BITCOIN_ADDRESS_TEST, PRIVATE_KEY_DER,
    PRIVATE_KEY_HEX, PRIVATE_KEY_NUM, PRIVATE_KEY_PEM,
    PUBLIC_KEY_COMPRESSED, PUBLIC_KEY_UNCOMPRESSED, PUBLIC_KEY_X,
    PUBLIC_KEY_Y, WALLET_FORMAT_COMPRESSED_MAIN, WALLET_FORMAT_COMPRESSED_TEST,
    WALLET_FORMAT_MAIN, WALLET_FORMAT_TEST
)

TRAVIS = 'TRAVIS' in os.environ

class TestWIFToKey:
    def test_compressed_main(self):
        key = wif_to_key(WALLET_FORMAT_COMPRESSED_MAIN)
        assert isinstance(key, PrivateKey)
        assert key.is_compressed()

    def test_uncompressed_main(self):
        key = wif_to_key(WALLET_FORMAT_MAIN)
        assert isinstance(key, PrivateKey)
        assert not key.is_compressed()

    def test_compressed_test(self):
        key = wif_to_key(WALLET_FORMAT_COMPRESSED_TEST)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.is_compressed()

    def test_uncompressed_test(self):
        key = wif_to_key(WALLET_FORMAT_TEST)
        assert isinstance(key, PrivateKeyTestnet)
        assert not key.is_compressed()

class TestBaseKey:
    def test_init_default(self):
        base_key = BaseKey()

        assert isinstance(base_key._pk, EllipticCurvePrivateKey)
        assert len(base_key.public_key) == 33

    def test_init_from_key(self):
        pk = generate_private_key()
        base_key = BaseKey(pk)
        assert base_key._pk == pk

    def test_init_wif_error(self):
        with pytest.raises(TypeError):
            BaseKey(b'\x00')

    def test_public_key_compressed(self):
        base_key = BaseKey(WALLET_FORMAT_COMPRESSED_MAIN)
        assert base_key.public_key == PUBLIC_KEY_COMPRESSED

    def test_public_key_uncompressed(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.public_key == PUBLIC_KEY_UNCOMPRESSED

    def test_public_point(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.public_point == Point(PUBLIC_KEY_X, PUBLIC_KEY_Y)
        assert base_key.public_point == Point(PUBLIC_KEY_X, PUBLIC_KEY_Y)

    def test_sign(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        public_key = base_key._pk.public_key()
        assert public_key.verify(signature, PUBLIC_KEY_COMPRESSED, ECDSA_SHA256)

    def test_verify_success(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        assert base_key.verify(signature, PUBLIC_KEY_COMPRESSED)

    def test_verify_failure(self):
        base_key = BaseKey()
        signature = base_key.sign(PUBLIC_KEY_COMPRESSED)
        assert not base_key.verify(signature, PUBLIC_KEY_UNCOMPRESSED)

    def test_to_hex(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_hex() == PRIVATE_KEY_HEX

    def test_to_der(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_der() == PRIVATE_KEY_DER

    def test_to_pem(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_pem() == PRIVATE_KEY_PEM

    def test_to_int(self):
        base_key = BaseKey(WALLET_FORMAT_MAIN)
        assert base_key.to_int() == PRIVATE_KEY_NUM

    def test_is_compressed(self):
        assert BaseKey(WALLET_FORMAT_COMPRESSED_MAIN).is_compressed() is True
        assert BaseKey(WALLET_FORMAT_MAIN).is_compressed() is False

    def test_equal(self):
        assert BaseKey(WALLET_FORMAT_COMPRESSED_MAIN) == BaseKey(WALLET_FORMAT_COMPRESSED_MAIN)

class TestPrivateKey:
    def test_alias(self):
        assert Key == PrivateKey

    def test_init_default(self):
        private_key = PrivateKey()

        assert private_key._address is None
        assert private_key.balance == 0
        assert private_key.unspents == []
        assert private_key.transactions == []

    def test_address(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        assert private_key.address == BITCOIN_ADDRESS
        assert private_key.address == BITCOIN_ADDRESS

    def test_to_wif(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        assert private_key.to_wif() == WALLET_FORMAT_MAIN

        private_key = PrivateKey(WALLET_FORMAT_COMPRESSED_MAIN)
        assert private_key.to_wif() == WALLET_FORMAT_COMPRESSED_MAIN

    def test_get_balance(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        balance = int(private_key.get_balance())
        assert balance == private_key.balance

    def test_get_unspent(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        unspent = private_key.get_unspents()
        assert unspent == private_key.unspents

    def test_get_transactions(self):
        private_key = PrivateKey(WALLET_FORMAT_MAIN)
        transactions = private_key.get_transactions()
        assert transactions == private_key.transactions

    def test_from_hex(self):
        key = PrivateKey.from_hex(PRIVATE_KEY_HEX)
        assert isinstance(key, PrivateKey)
        assert key.to_hex() == PRIVATE_KEY_HEX

    def test_from_der(self):
        key = PrivateKey.from_der(PRIVATE_KEY_DER)
        assert isinstance(key, PrivateKey)
        assert key.to_der() == PRIVATE_KEY_DER

    def test_from_pem(self):
        key = PrivateKey.from_pem(PRIVATE_KEY_PEM)
        assert isinstance(key, PrivateKey)
        assert key.to_pem() == PRIVATE_KEY_PEM

    def test_from_int(self):
        key = PrivateKey.from_int(PRIVATE_KEY_NUM)
        assert isinstance(key, PrivateKey)
        assert key.to_int() == PRIVATE_KEY_NUM

    def test_repr(self):
        assert repr(PrivateKey(WALLET_FORMAT_MAIN)) == '<PrivateKey: 1ELReFsTCUY2mfaDTy32qxYiT49z786eFg>'

class TestPrivateKeyTestnet:
    def test_init_default(self):
        private_key = PrivateKeyTestnet()

        assert private_key._address is None
        assert private_key.balance == 0
        assert private_key.unspents == []
        assert private_key.transactions == []

    def test_address(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        assert private_key.address == BITCOIN_ADDRESS_TEST
        assert private_key.address == BITCOIN_ADDRESS_TEST

    def test_to_wif(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        assert private_key.to_wif() == WALLET_FORMAT_TEST

        private_key = PrivateKeyTestnet(WALLET_FORMAT_COMPRESSED_TEST)
        assert private_key.to_wif() == WALLET_FORMAT_COMPRESSED_TEST

    def test_get_balance(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        balance = int(private_key.get_balance())
        assert balance == private_key.balance

    def test_get_unspent(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        unspent = private_key.get_unspents()
        assert unspent == private_key.unspents

    def test_get_transactions(self):
        private_key = PrivateKeyTestnet(WALLET_FORMAT_TEST)
        transactions = private_key.get_transactions()
        assert transactions == private_key.transactions

    def test_send(self):
        if TRAVIS:  # and sys.version_info[:2] != (3, 6):
            assert True
        else:
            private_key = PrivateKeyTestnet(WALLET_FORMAT_COMPRESSED_TEST)
            private_key.get_unspents()
            initial = len(private_key.get_transactions())
            private_key.send([('n2eMqTT929pb1RDNuqEnxdaLau1rxy3efi', 1, 'jpy')])

            current = initial
            tries = 0

            while tries < 15:  # pragma: no cover
                current = len(private_key.get_transactions())
                if current > initial:
                    break
                time.sleep(5)
                tries += 1

            assert current > initial

    def test_from_hex(self):
        key = PrivateKeyTestnet.from_hex(PRIVATE_KEY_HEX)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_hex() == PRIVATE_KEY_HEX

    def test_from_der(self):
        key = PrivateKeyTestnet.from_der(PRIVATE_KEY_DER)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_der() == PRIVATE_KEY_DER

    def test_from_pem(self):
        key = PrivateKeyTestnet.from_pem(PRIVATE_KEY_PEM)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_pem() == PRIVATE_KEY_PEM

    def test_from_int(self):
        key = PrivateKeyTestnet.from_int(PRIVATE_KEY_NUM)
        assert isinstance(key, PrivateKeyTestnet)
        assert key.to_int() == PRIVATE_KEY_NUM

    def test_repr(self):
        assert repr(PrivateKeyTestnet(WALLET_FORMAT_MAIN)) == '<PrivateKeyTestnet: mtrNwJxS1VyHYn3qBY1Qfsm3K3kh1mGRMS>'
<|endoftext|>


<commit_before># vim: set fileencoding=utf-8 :

import webapp
from create_schema import create_schema
from recreate_schema import recreate_schema
from create_user import create_user
from model import User
import pytest

app = None

class TestWebapp(object):

    @classmethod
    def setup_class(cls):
        global app
        app = webapp.init()
        db_uri = 'sqlite:///:memory:'
        app.config.update(SQLALCHEMY_ECHO=False, DEBUG=True, TESTING=True, SQLALCHEMY_DATABASE_URI=db_uri)

    def test_create_schema(self):
        create_schema(app)

    def test_recreate_schema(self):
        recreate_schema(app)

    def test_create_user(self):
        with app.test_request_context():
            assert User.query.count() == 0
        create_user(app, username='test_user')
        with app.test_request_context():
            assert User.query.count() == 1
            assert User.query.filter_by(username='test_user').one()

        with pytest.raises(AssertionError):
            create_user(app, username='test_user')

        create_user(app, username='test_user2')
        with app.test_request_context():
            assert User.query.count() == 2
            assert User.query.filter_by(username='test_user').one() != User.query.filter_by(username='test_user2').one()
<commit_msg>improve unit test<commit_after># vim: set fileencoding=utf-8 :

import webapp
from create_schema import create_schema
from recreate_schema import recreate_schema
from create_user import create_user
from model import User
import pytest

app = None

class TestWebapp(object):

    @classmethod
    def setup_class(cls):
        global app
        app = webapp.init()
        db_uri = 'sqlite:///:memory:'
        app.config.update(SQLALCHEMY_ECHO=False, DEBUG=True, TESTING=True, SQLALCHEMY_DATABASE_URI=db_uri)

    def test_create_schema(self):
        create_schema(app)

    def test_recreate_schema(self):
        recreate_schema(app)

    def test_create_user(self):
        with app.test_request_context():
            assert User.query.count() == 0
        create_user(app, username='test_user')
        with app.test_request_context():
            assert User.query.count() == 1
            assert User.query.filter_by(username='test_user').one()

        with pytest.raises(AssertionError) as e:
            create_user(app, username='test_user')
        assert "user already exists" in str(e.value)

        create_user(app, username='test_user2')
        with app.test_request_context():
            assert User.query.count() == 2
            assert User.query.filter_by(username='test_user').one() != User.query.filter_by(username='test_user2').one()
<|endoftext|>


<commit_before>import numpy as np
from holoviews import Dimension, DynamicMap, Image
from holoviews.element.comparison import ComparisonTestCase

frequencies =  np.linspace(0.5,2.0,5)
phases = np.linspace(0, np.pi*2, 5)
x,y = np.mgrid[-5:6, -5:6] * 0.1

def sine_array(phase, freq):
    return np.sin(phase + (freq*x**2+freq*y**2))

class DynamicTestGeneratorOpen(ComparisonTestCase):

    def test_generator_open_init(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        self.assertEqual(dmap.mode, 'open')

    def test_generator_open_clone(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        self.assertEqual(dmap, dmap.clone())

    def test_generator_open_stopiteration(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        for i in range(10):
            el = next(dmap)
            self.assertEqual(type(el), Image)
        try:
            el = next(dmap)
            raise AssertionError("StopIteration not raised when expected")
        except Exception as e:
            if e.__class__ != StopIteration:
                raise AssertionError("StopIteration was expected, got %s" % e)

class DynamicTestCallableOpen(ComparisonTestCase):

    def test_callable_open_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn)
        self.assertEqual(dmap.mode, 'open')

    def test_callable_open_clone(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn)
        self.assertEqual(dmap, dmap.clone())

class DynamicTestCallableClosed(ComparisonTestCase):

    def test_callable_closed_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])
        self.assertEqual(dmap.mode, 'closed')

    def test_generator_closed_clone(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])
        self.assertEqual(dmap, dmap.clone())
<commit_msg>Added DynamicMap sampled unit tests<commit_after>import numpy as np
from holoviews import Dimension, DynamicMap, Image
from holoviews.element.comparison import ComparisonTestCase

frequencies =  np.linspace(0.5,2.0,5)
phases = np.linspace(0, np.pi*2, 5)
x,y = np.mgrid[-5:6, -5:6] * 0.1

def sine_array(phase, freq):
    return np.sin(phase + (freq*x**2+freq*y**2))

class DynamicTestGeneratorOpen(ComparisonTestCase):

    def test_generator_open_init(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        self.assertEqual(dmap.mode, 'open')

    def test_generator_open_clone(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        self.assertEqual(dmap, dmap.clone())

    def test_generator_open_stopiteration(self):
        generator = (Image(sine_array(0,i)) for i in range(10))
        dmap=DynamicMap(generator)
        for i in range(10):
            el = next(dmap)
            self.assertEqual(type(el), Image)
        try:
            el = next(dmap)
            raise AssertionError("StopIteration not raised when expected")
        except Exception as e:
            if e.__class__ != StopIteration:
                raise AssertionError("StopIteration was expected, got %s" % e)

class DynamicTestCallableOpen(ComparisonTestCase):

    def test_callable_open_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn)
        self.assertEqual(dmap.mode, 'open')

    def test_callable_open_clone(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn)
        self.assertEqual(dmap, dmap.clone())

class DynamicTestCallableClosed(ComparisonTestCase):

    def test_callable_closed_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])
        self.assertEqual(dmap.mode, 'closed')

    def test_generator_closed_clone(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, kdims=[Dimension('dim', range=(0,10))])
        self.assertEqual(dmap, dmap.clone())

class DynamicTestSampledClosed(ComparisonTestCase):

    def test_sampled_closed_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, sampled=True)
        self.assertEqual(dmap.mode, 'closed')

    def test_sampled_closed_init(self):
        fn = lambda i: Image(sine_array(0,i))
        dmap=DynamicMap(fn, sampled=True)
        self.assertEqual(dmap[{0, 1, 2}].keys(), [0, 1, 2])

<|endoftext|>


<commit_before>"""
Test cases for the HTML/JavaScript scrubber and widgets.
"""
import re
from hashlib import sha256
from unittest import SkipTest
import numpy as np

try:
    from holoviews.ipython import IPTestCase
    from holoviews.plotting.mpl.widgets import ScrubberWidget, SelectionWidget
    # Standardize backend due to random inconsistencies
    from matplotlib import pyplot
    pyplot.switch_backend('agg')
except:
    raise SkipTest("Matplotlib required to test widgets")

from holoviews import Image, HoloMap
from holoviews.plotting.mpl import RasterPlot

def digest_data(data):
    hashfn = sha256()
    hashfn.update(data.encode('utf-16'))
    return hashfn.hexdigest()

prefixes =  ['anim', '_anim_slider', '_anim_img',
             '_anim_loop_select', 'textInput', '_anim_widget', 'valMap']
filters  = [re.compile('{p}[a-f0-9]+'.format(p=p)) for p in prefixes]
filters += [re.compile('new ScrubberWidget\([a-z0-9_, "]+')]
filters += [re.compile('new SelectionWidget\([a-z0-9_, "]+')]

def normalize(data):
    for f in filters:
        data = re.sub(f, '[CLEARED]', data)
    # Hack around inconsistencies in jinja between Python 2 and 3
    return data.replace('0.0', '0').replace('1.0', '1')

class TestWidgets(IPTestCase):

    def setUp(self):
        super(TestWidgets, self).setUp()
        im1 = Image(np.array([[1,2],[3,4]]))
        im2 = Image(np.array([[1,2],[3,5]]))
        holomap = HoloMap(initial_items=[(0,im1), (1,im2)], kdims=['test'])
        self.plot1 = RasterPlot(im1)
        self.plot2 = RasterPlot(holomap)

    def tearDown(self):
        super(TestWidgets, self).tearDown()

    def test_scrubber_widget_1(self):
        html = normalize(ScrubberWidget(self.plot1, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), '61d1b1a41e3a06899110c36e23c5db85d3dba064ca26470f932f2c1d6c3497b4')

    def test_scrubber_widget_2(self):
        html = normalize(ScrubberWidget(self.plot2, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), 'ce0d3917cf72e4ffc87f9b91afd5dfaa302263d818fd784f72ee4c0d8b1a3a40')

    def test_selection_widget_1(self):
        html = normalize(SelectionWidget(self.plot1, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), '6783419ddf6c77fbff2f7cdf2afb632704337c2185fcb247491ef1c8d58fb778')

    def test_selection_widget_2(self):
        html = normalize(SelectionWidget(self.plot2, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), '8571ca63d1c6abe11d004dbb9432f6e7ce5dd4b60b8e6eff7081f21dcbf3baa8')
<commit_msg>Updated SelectionWidget SHA tests<commit_after>"""
Test cases for the HTML/JavaScript scrubber and widgets.
"""
import re
from hashlib import sha256
from unittest import SkipTest
import numpy as np

try:
    from holoviews.ipython import IPTestCase
    from holoviews.plotting.mpl.widgets import ScrubberWidget, SelectionWidget
    # Standardize backend due to random inconsistencies
    from matplotlib import pyplot
    pyplot.switch_backend('agg')
except:
    raise SkipTest("Matplotlib required to test widgets")

from holoviews import Image, HoloMap
from holoviews.plotting.mpl import RasterPlot

def digest_data(data):
    hashfn = sha256()
    hashfn.update(data.encode('utf-16'))
    return hashfn.hexdigest()

prefixes =  ['anim', '_anim_slider', '_anim_img',
             '_anim_loop_select', 'textInput', '_anim_widget', 'valMap']
filters  = [re.compile('{p}[a-f0-9]+'.format(p=p)) for p in prefixes]
filters += [re.compile('new ScrubberWidget\([a-z0-9_, "]+')]
filters += [re.compile('new SelectionWidget\([a-z0-9_, "]+')]

def normalize(data):
    for f in filters:
        data = re.sub(f, '[CLEARED]', data)
    # Hack around inconsistencies in jinja between Python 2 and 3
    return data.replace('0.0', '0').replace('1.0', '1')

class TestWidgets(IPTestCase):

    def setUp(self):
        super(TestWidgets, self).setUp()
        im1 = Image(np.array([[1,2],[3,4]]))
        im2 = Image(np.array([[1,2],[3,5]]))
        holomap = HoloMap(initial_items=[(0,im1), (1,im2)], kdims=['test'])
        self.plot1 = RasterPlot(im1)
        self.plot2 = RasterPlot(holomap)

    def tearDown(self):
        super(TestWidgets, self).tearDown()

    def test_scrubber_widget_1(self):
        html = normalize(ScrubberWidget(self.plot1, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), '61d1b1a41e3a06899110c36e23c5db85d3dba064ca26470f932f2c1d6c3497b4')

    def test_scrubber_widget_2(self):
        html = normalize(ScrubberWidget(self.plot2, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), 'ce0d3917cf72e4ffc87f9b91afd5dfaa302263d818fd784f72ee4c0d8b1a3a40')

    def test_selection_widget_1(self):
        html = normalize(SelectionWidget(self.plot1, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), cafd0a60594440cf0fced7d9e7d2e51e88e8ff76f744a0ab8a4e983d8f220b93')

    def test_selection_widget_2(self):
        html = normalize(SelectionWidget(self.plot2, display_options={'figure_format': 'png'})())
        self.assertEqual(digest_data(html), 'e2a4fab7a76e9b97d89d029d8e200117671bb1026f8a6a1e1db716dd7c02f228')
<|endoftext|>


<commit_before>import flask
import flask_login
import flask_socketio as fsio
import sqlalchemy
from . import socketio, redis
from .models import db, User
from .game_instance import GameInstance
from .tasks import play_game
from .rooms import (
    get_room_of_player,
    get_players_in_room,
    remove_player_from_room,
    get_room_state_json_string,
    set_script,
    set_player_ready,
    all_players_are_ready,
    reset_all_players,
    get_name_of_player,
)

NAMESPACE = '/game-session'

@socketio.on('joined', namespace=NAMESPACE)
def joined(message):
    """Sent by clients when they enter a room."""

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)
    if game_id is None:
        flask.flash("sorry something isn't quite right... try joining another game")
        return flask.redirect(flask.url_for('.main.lobby'))

    # subscribe client to room broadcasts
    fsio.join_room(game_id)

    update_players(game_id)

    # TODO: gaurd against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' has joined!', room=game_id, namespace=NAMESPACE)

@socketio.on('left', namespace=NAMESPACE)
def left(message):
    """Sent by clients when they leave a room."""

    # TODO: need to also account for ungraceful exit
    # - setup a heartbeat?

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)

    if game_id is None:
        return

    fsio.leave_room(game_id)
    remove_player_from_room(game_id, player_id)

    if get_players_in_room(game_id) == []:
        # TODO: remove room from redis
        pass
    else:
        # notify players that one has left
        update_players(game_id)

        # TODO: guard against no player entry
        player_name = get_name_of_player(player_id)
        fsio.emit('message_room', player_name + ' has left.', room=game_id, namespace=NAMESPACE)

        run_game_if_everyone_ready(game_id)

@socketio.on('submit', namespace=NAMESPACE)
def submit_code(message):
    """Sent by clients when submitting code."""

    flask_login.current_user.script = message
    db.session.commit()

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)

    if game_id is None:
        flask.flash("sorry something isn't quite right... try joining another game")
        return flask.redirect(flask.url_for('.main.lobby'))

    set_script(game_id, player_id, message)
    update_players(game_id)

    # TODO: guard against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' has submitted a new script.', room=game_id, namespace=NAMESPACE)

@socketio.on('test', namespace=NAMESPACE)
def test(message):
    """
    Sent by clients to run a wave that tests their (unsubmitted) code.
    The message contains the player script to use.
    """
    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)

    player_jsons = get_players_in_room(game_id)
    player_names = []
    player_scripts = []
    for player in player_jsons:
        player_names.append(player['name'])

        # use the submitted script
        if player['id'] == player_id:
            player_scripts.append(message)
        else:
            player_scripts.append(player['script'])

    fsio.emit('message_room', 'Running a test for you...', room=flask.request.sid, namespace=NAMESPACE)

    # TODO: specify test run in call
    # TODO: Give choice for a wave
    wave = 1
    handle = play_game.delay(game_id, player_names, player_scripts, NAMESPACE, flask.request.sid, wave=wave)
    result = handle.get()

    fsio.emit('message_result', 'Test complete!', room=flask.request.sid, namespace=NAMESPACE)

@socketio.on('play', namespace=NAMESPACE)
def play(message):
    """Sent by clients to indicate they are ready to play."""

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)
    set_player_ready(game_id, player_id)

    # TODO: guard against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' is ready to go!', room=game_id, namespace=NAMESPACE)

    run_game_if_everyone_ready(game_id)

def run_game_if_everyone_ready(game_id):
    if all_players_are_ready(game_id):
        player_jsons = get_players_in_room(game_id)
        player_names = []
        player_scripts = []
        for player in player_jsons:
            player_names.append(player['name'])
            player_scripts.append(player['script'])

        fsio.emit('message_room', 'Everyone is ready! Here we go...', room=game_id, namespace=NAMESPACE)
        # TODO: Give choice for a wave
        wave = 1
        handle = play_game.delay(game_id, player_names, player_scripts, NAMESPACE, game_id, wave=wave)
        result = handle.get()
        fsio.emit('message_result', 'Run complete!', room=game_id, namespace=NAMESPACE)
        reset_all_players(game_id)

def update_players(game_id):
    game_json_string = get_room_state_json_string(game_id)
    if game_json_string is not None:
        fsio.emit('update', game_json_string, room=game_id, namespace=NAMESPACE)
<commit_msg>[NG] Subscribe to 'disconnect' to gaurd against ungraceful exits.<commit_after>import flask
import flask_login
import flask_socketio as fsio
import sqlalchemy
from . import socketio, redis
from .models import db, User
from .game_instance import GameInstance
from .tasks import play_game
from .rooms import (
    get_room_of_player,
    get_players_in_room,
    remove_player_from_room,
    get_room_state_json_string,
    set_script,
    set_player_ready,
    all_players_are_ready,
    reset_all_players,
    get_name_of_player,
)

NAMESPACE = '/game-session'

@socketio.on('joined', namespace=NAMESPACE)
def joined(message):
    """Sent by clients when they enter a room."""

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)
    if game_id is None:
        flask.flash("sorry something isn't quite right... try joining another game")
        return flask.redirect(flask.url_for('.main.lobby'))

    # subscribe client to room broadcasts
    fsio.join_room(game_id)

    update_players(game_id)

    # TODO: guard against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' has joined!', room=game_id, namespace=NAMESPACE)

@socketio.on('left', namespace=NAMESPACE)
def left(message):
    """Sent by clients when they leave a room."""
    player_id = flask_login.current_user.id
    manage_player_leaves(player_id)

@socketio.on('disconnect', namespace=NAMESPACE)
def left(message):
    """Received when a client ungracefully leaves a room."""
    player_id = flask_login.current_user.id
    manage_player_leaves(player_id)

@socketio.on('submit', namespace=NAMESPACE)
def submit_code(message):
    """Sent by clients when submitting code."""

    flask_login.current_user.script = message
    db.session.commit()

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)

    if game_id is None:
        flask.flash("sorry something isn't quite right... try joining another game")
        return flask.redirect(flask.url_for('.main.lobby'))

    set_script(game_id, player_id, message)
    update_players(game_id)

    # TODO: guard against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' has submitted a new script.', room=game_id, namespace=NAMESPACE)

@socketio.on('test', namespace=NAMESPACE)
def test(message):
    """
    Sent by clients to run a wave that tests their (unsubmitted) code.
    The message contains the player script to use.
    """
    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)

    player_jsons = get_players_in_room(game_id)
    player_names = []
    player_scripts = []
    for player in player_jsons:
        player_names.append(player['name'])

        # use the submitted script
        if player['id'] == player_id:
            player_scripts.append(message)
        else:
            player_scripts.append(player['script'])

    fsio.emit('message_room', 'Running a test for you...', room=flask.request.sid, namespace=NAMESPACE)

    # TODO: specify test run in call
    # TODO: Give choice for a wave
    wave = 1
    handle = play_game.delay(game_id, player_names, player_scripts, NAMESPACE, flask.request.sid, wave=wave)
    result = handle.get()

    fsio.emit('message_result', 'Test complete!', room=flask.request.sid, namespace=NAMESPACE)

@socketio.on('play', namespace=NAMESPACE)
def play(message):
    """Sent by clients to indicate they are ready to play."""

    player_id = flask_login.current_user.id
    game_id = get_room_of_player(player_id)
    set_player_ready(game_id, player_id)

    # TODO: guard against no player entry
    player_name = get_name_of_player(player_id)
    fsio.emit('message_room', player_name + ' is ready to go!', room=game_id, namespace=NAMESPACE)

    run_game_if_everyone_ready(game_id)

def manage_player_leaves(player_id):
    game_id = get_room_of_player(player_id)

    if game_id is None:
        return

    fsio.leave_room(game_id)
    remove_player_from_room(game_id, player_id)

    if get_players_in_room(game_id) == []:
        # TODO: remove room from redis
        pass
    else:
        # notify players that one has left
        update_players(game_id)

        player_name = get_name_of_player(player_id)
        if player_name is not None:
            fsio.emit('message_room', player_name + ' has left.', room=game_id, namespace=NAMESPACE)

        run_game_if_everyone_ready(game_id)

def run_game_if_everyone_ready(game_id):
    if all_players_are_ready(game_id):
        player_jsons = get_players_in_room(game_id)
        player_names = []
        player_scripts = []
        for player in player_jsons:
            player_names.append(player['name'])
            player_scripts.append(player['script'])

        fsio.emit('message_room', 'Everyone is ready! Here we go...', room=game_id, namespace=NAMESPACE)
        # TODO: Give choice for a wave
        wave = 1
        handle = play_game.delay(game_id, player_names, player_scripts, NAMESPACE, game_id, wave=wave)
        result = handle.get()
        fsio.emit('message_result', 'Run complete!', room=game_id, namespace=NAMESPACE)
        reset_all_players(game_id)

def update_players(game_id):
    game_json_string = get_room_state_json_string(game_id)
    if game_json_string is not None:
        fsio.emit('update', game_json_string, room=game_id, namespace=NAMESPACE)
<|endoftext|>


<commit_before>#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Authors:
# Caner Candan <caner@candan.fr>, http://caner.candan.fr
# Geraldine Starke <geraldine@starke.fr>, http://www.vegeclic.fr
#

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
import common.models as cm
import numpy as np

class Supplier(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)
    slug = models.SlugField(unique=True)
    suppliers = models.ManyToManyField('self', null=True, blank=True, related_name='supplier_suppliers', verbose_name=_('suppliers'))
    delivery_delay = models.PositiveIntegerField(_('delivery delay'), null=True, blank=True)
    threshold_order = models.PositiveIntegerField(_('threshold order'), null=True, blank=True)
    main_image = models.OneToOneField('common.Image', null=True, blank=True, related_name='+', verbose_name=_('main image'))

    def __unicode__(self): return self.name

    def fee_per_weight(self):
        try:
            return self.supplierfee_set.get(currency__name=settings.DEFAULT_CURRENCY)
        except Supplier.DoesNotExist:
            return None

class SupplierFee(models.Model):
    class Meta:
        unique_together = ('supplier', 'currency')

    supplier = models.ForeignKey(Supplier, verbose_name=_('supplier'))
    currency = models.ForeignKey('common.Currency', related_name='supplier_fee_currency', verbose_name=_('currency'))
    fee_per_weight = models.FloatField(_('fee per weight'))

    def __unicode__(self): return '%s %s / 1 kg' % (self.fee_per_weight, self.currency.symbol)

class Ingredient(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)

class IngredientExtent(models.Model):
    ingredient = models.ForeignKey(Ingredient, verbose_name=_('ingredient'))
    ingredient_parent = models.ManyToManyField('self', symmetrical=False, null=True, blank=True, related_name='ingredient_children', verbose_name=_('ingredient parent'))
    extent = models.FloatField(_('extent'), default=0.)
    bio = models.BooleanField(_('bio'), default=False)

class Energy(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)

class EnergyExtent(models.Model):
    energy = models.ForeignKey(Energy, verbose_name=_('energy'), unique=True)
    value = models.CharField(_('value'), max_length=200, null=True, blank=True)

class Product(models.Model):
    name = models.CharField(_('name'), max_length=100)
    slug = models.SlugField(max_length=100, null=True, blank=True)
    body = models.TextField(_('body'), blank=True)
    brut_ingredients = models.TextField(_('brut ingredients'), blank=True)
    allergies = models.ManyToManyField(Ingredient, null=True, blank=True, related_name='product_allergies', verbose_name=_('allergies'))
    traces = models.ManyToManyField(Ingredient, null=True, blank=True, related_name='product_traces', verbose_name=_('traces'))
    product = models.ForeignKey('products.Product', related_name='product_product', verbose_name=_('product'))
    STATUS_CHOICES = (
        ('d', _('Draft')),
        ('p', _('Published')),
        ('o', _('Out of stock')),
        ('e', _('Expired')),
        ('w', _('Withdrawn')),
    )
    status = models.CharField(_('status'), max_length=1, choices=STATUS_CHOICES, default='d')
    suppliers = models.ManyToManyField(Supplier, null=True, blank=True, related_name='product_suppliers', verbose_name=_('suppliers'))
    criterias = models.ManyToManyField('common.Criteria', null=True, blank=True, related_name='product_criterias', verbose_name=_('criterias'))
    weight = models.FloatField(_('weight'), null=True, blank=True)
    sku = models.CharField(max_length=100, blank=True)
    main_image = models.OneToOneField('common.Image', null=True, blank=True, related_name='+', verbose_name=_('main image'))
    main_price = models.OneToOneField('Price', null=True, blank=True, related_name='+', verbose_name=_('main price'))
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.name

    def price(self):
        try:
            return self.price_set.select_related('currency', 'tax').get(currency__name=settings.DEFAULT_CURRENCY)
        except Product.DoesNotExist:
            return None

class Tax(models.Model):
    class Meta:
        verbose_name_plural = _('taxes')

    name = models.CharField(_('name'), max_length=100, null=True, blank=True)
    rate = models.FloatField(_('rate'))

    def __unicode__(self): return self.name

class Price(models.Model):
    class Meta:
        unique_together = ('product', 'supplier', 'currency')

    product = models.ForeignKey(Product, verbose_name=_('product'))
    supplier = models.ForeignKey(Supplier, verbose_name=_('supplier'))
    reference = models.CharField(_('reference'), max_length=30, null=True, blank=True)
    supplier_product_url = models.URLField(_('supplier product url'), null=True, blank=True)
    limited = models.BooleanField(_('limited product'), default=False)
    currency = models.ForeignKey('common.Currency', related_name='supplier_product_price_currency', verbose_name=_('currency'))
    purchase_price = models.FloatField(_('purchase price'))
    selling_price = models.FloatField(_('selling price'), null=True, blank=True)
    tax = models.ForeignKey(Tax, related_name='supplier_product_price_tax', verbose_name=_('tax'), null=True, blank=True)

    def price(self): return self.selling_price if self.selling_price else self.purchase_price

    def margin_price(self): return round(self.selling_price if self.selling_price else (self.purchase_price * (1+settings.PRICE_MARGIN_RATE/100)), 2)

    def get_pre_tax_price(self): return self.margin_price()

    def get_after_tax_price(self):
        tax = 1
        if self.tax:
            tax = 1+self.tax.rate/100
        elif self.product.product.tax:
            tax = 1+self.product.product.tax.rate/100
        return round(self.get_pre_tax_price()*tax,2)

    def get_after_tax_price_with_fee(self):
        weight = self.product.weight or settings.DEFAULT_WEIGHT
        return round(self.get_after_tax_price() + (weight/1000) * self.supplier.fee_per_weight().fee_per_weight, 2)

    def pro_margin_price(self): return round(self.selling_price if self.selling_price else (self.purchase_price * (1+settings.PRICE_PRO_MARGIN_RATE/100)), 2)

    def get_pro_pre_tax_price(self): return self.pro_margin_price()

    def get_pro_after_tax_price(self):
        tax = 1
        if self.tax:
            tax = 1+self.tax.rate/100
        elif self.product.product.tax:
            tax = 1+self.product.product.tax.rate/100
        return round(self.get_pro_pre_tax_price()*tax,2)

    def degressive_price(self, nb_deliveries=52):
        values = []
        for i in range(nb_deliveries):
            values.append(self.get_after_tax_price()/(1+settings.DEGRESSIVE_PRICE_RATE/100)**i)
        return round(np.mean(values), 2)

    def __unicode__(self):
        return ('%.2f %s' % (self.get_after_tax_price(), self.currency.symbol)).strip()

    def price_pro(self):
        return ('%.2f %s' % (self.get_pro_after_tax_price(), self.currency.symbol)).strip()

class Inventory(models.Model):
    class Meta:
        verbose_name_plural = _('inventories')

    store = models.ForeignKey('Store', verbose_name=_('store'))
    product = models.OneToOneField(Product, verbose_name=_('product'))
    quantity = models.PositiveIntegerField(_('quantity'), null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.product.name

class Store(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.name

class Entry(models.Model):
    class Meta:
        verbose_name_plural = _('entries')

    order = models.ForeignKey('Order', verbose_name=_('order'))
    product = models.OneToOneField(Product, verbose_name=_('product'))
    quantity = models.PositiveIntegerField(_('quantity'), null=True, blank=True)

    def __unicode__(self): return self.product.name

class Order(models.Model):
    STATUS_CHOICES = (
        ('d', _('Draft')),
        ('v', _('Validated')),
        ('e', _('Expired')),
        ('w', _('Withdrawn')),
    )
    status = models.CharField(_('status'), max_length=1, choices=STATUS_CHOICES, default='d')
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)
<commit_msg>*added suppliers fee to catalog products<commit_after>#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Authors:
# Caner Candan <caner@candan.fr>, http://caner.candan.fr
# Geraldine Starke <geraldine@starke.fr>, http://www.vegeclic.fr
#

from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
import common.models as cm
import numpy as np

class Supplier(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)
    slug = models.SlugField(unique=True)
    suppliers = models.ManyToManyField('self', null=True, blank=True, related_name='supplier_suppliers', verbose_name=_('suppliers'))
    delivery_delay = models.PositiveIntegerField(_('delivery delay'), null=True, blank=True)
    threshold_order = models.PositiveIntegerField(_('threshold order'), null=True, blank=True)
    main_image = models.OneToOneField('common.Image', null=True, blank=True, related_name='+', verbose_name=_('main image'))

    def __unicode__(self): return self.name

    def fee_per_weight(self):
        try:
            return self.supplierfee_set.get(currency__name=settings.DEFAULT_CURRENCY)
        except Supplier.DoesNotExist:
            return None

class SupplierFee(models.Model):
    class Meta:
        unique_together = ('supplier', 'currency')

    supplier = models.ForeignKey(Supplier, verbose_name=_('supplier'))
    currency = models.ForeignKey('common.Currency', related_name='supplier_fee_currency', verbose_name=_('currency'))
    fee_per_weight = models.FloatField(_('fee per weight'))

    def __unicode__(self): return '%s %s / 1 kg' % (self.fee_per_weight, self.currency.symbol)

class Ingredient(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)

class IngredientExtent(models.Model):
    ingredient = models.ForeignKey(Ingredient, verbose_name=_('ingredient'))
    ingredient_parent = models.ManyToManyField('self', symmetrical=False, null=True, blank=True, related_name='ingredient_children', verbose_name=_('ingredient parent'))
    extent = models.FloatField(_('extent'), default=0.)
    bio = models.BooleanField(_('bio'), default=False)

class Energy(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)

class EnergyExtent(models.Model):
    energy = models.ForeignKey(Energy, verbose_name=_('energy'), unique=True)
    value = models.CharField(_('value'), max_length=200, null=True, blank=True)

class Product(models.Model):
    name = models.CharField(_('name'), max_length=100)
    slug = models.SlugField(max_length=100, null=True, blank=True)
    body = models.TextField(_('body'), blank=True)
    brut_ingredients = models.TextField(_('brut ingredients'), blank=True)
    allergies = models.ManyToManyField(Ingredient, null=True, blank=True, related_name='product_allergies', verbose_name=_('allergies'))
    traces = models.ManyToManyField(Ingredient, null=True, blank=True, related_name='product_traces', verbose_name=_('traces'))
    product = models.ForeignKey('products.Product', related_name='product_product', verbose_name=_('product'))
    STATUS_CHOICES = (
        ('d', _('Draft')),
        ('p', _('Published')),
        ('o', _('Out of stock')),
        ('e', _('Expired')),
        ('w', _('Withdrawn')),
    )
    status = models.CharField(_('status'), max_length=1, choices=STATUS_CHOICES, default='d')
    suppliers = models.ManyToManyField(Supplier, null=True, blank=True, related_name='product_suppliers', verbose_name=_('suppliers'))
    criterias = models.ManyToManyField('common.Criteria', null=True, blank=True, related_name='product_criterias', verbose_name=_('criterias'))
    weight = models.FloatField(_('weight'), null=True, blank=True)
    sku = models.CharField(max_length=100, blank=True)
    main_image = models.OneToOneField('common.Image', null=True, blank=True, related_name='+', verbose_name=_('main image'))
    main_price = models.OneToOneField('Price', null=True, blank=True, related_name='+', verbose_name=_('main price'))
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.name

    def price(self):
        try:
            return self.price_set.select_related('currency', 'tax').get(currency__name=settings.DEFAULT_CURRENCY)
        except Product.DoesNotExist:
            return None

class Tax(models.Model):
    class Meta:
        verbose_name_plural = _('taxes')

    name = models.CharField(_('name'), max_length=100, null=True, blank=True)
    rate = models.FloatField(_('rate'))

    def __unicode__(self): return self.name

class Price(models.Model):
    class Meta:
        unique_together = ('product', 'supplier', 'currency')

    product = models.ForeignKey(Product, verbose_name=_('product'))
    supplier = models.ForeignKey(Supplier, verbose_name=_('supplier'))
    reference = models.CharField(_('reference'), max_length=30, null=True, blank=True)
    supplier_product_url = models.URLField(_('supplier product url'), null=True, blank=True)
    limited = models.BooleanField(_('limited product'), default=False)
    currency = models.ForeignKey('common.Currency', related_name='supplier_product_price_currency', verbose_name=_('currency'))
    purchase_price = models.FloatField(_('purchase price'))
    selling_price = models.FloatField(_('selling price'), null=True, blank=True)
    tax = models.ForeignKey(Tax, related_name='supplier_product_price_tax', verbose_name=_('tax'), null=True, blank=True)

    def price(self): return self.selling_price if self.selling_price else self.purchase_price

    def margin_price(self): return round(self.selling_price if self.selling_price else (self.purchase_price * (1+settings.PRICE_MARGIN_RATE/100)), 2)

    def get_pre_tax_price(self): return self.margin_price()

    def get_after_tax_price(self):
        tax = 1
        if self.tax:
            tax = 1+self.tax.rate/100
        elif self.product.product.tax:
            tax = 1+self.product.product.tax.rate/100
        return round(self.get_pre_tax_price()*tax,2)

    def get_after_tax_price_with_fee(self):
        weight = self.product.weight or settings.DEFAULT_WEIGHT
        return round(self.get_after_tax_price() + (weight/1000) * self.supplier.fee_per_weight().fee_per_weight, 2)

    def pro_margin_price(self): return round(self.selling_price if self.selling_price else (self.purchase_price * (1+settings.PRICE_PRO_MARGIN_RATE/100)), 2)

    def get_pro_pre_tax_price(self): return self.pro_margin_price()

    def get_pro_after_tax_price(self):
        tax = 1
        if self.tax:
            tax = 1+self.tax.rate/100
        elif self.product.product.tax:
            tax = 1+self.product.product.tax.rate/100
        return round(self.get_pro_pre_tax_price()*tax,2)

    def degressive_price(self, nb_deliveries=52):
        values = []
        for i in range(nb_deliveries):
            values.append(self.get_after_tax_price()/(1+settings.DEGRESSIVE_PRICE_RATE/100)**i)
        return round(np.mean(values), 2)

    def __unicode__(self):
        return ('%.2f %s' % (self.get_after_tax_price_with_fee(), self.currency.symbol)).strip()

    def price_pro(self):
        return ('%.2f %s' % (self.get_pro_after_tax_price(), self.currency.symbol)).strip()

class Inventory(models.Model):
    class Meta:
        verbose_name_plural = _('inventories')

    store = models.ForeignKey('Store', verbose_name=_('store'))
    product = models.OneToOneField(Product, verbose_name=_('product'))
    quantity = models.PositiveIntegerField(_('quantity'), null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.product.name

class Store(models.Model):
    name = models.CharField(_('name'), max_length=100, unique=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self): return self.name

class Entry(models.Model):
    class Meta:
        verbose_name_plural = _('entries')

    order = models.ForeignKey('Order', verbose_name=_('order'))
    product = models.OneToOneField(Product, verbose_name=_('product'))
    quantity = models.PositiveIntegerField(_('quantity'), null=True, blank=True)

    def __unicode__(self): return self.product.name

class Order(models.Model):
    STATUS_CHOICES = (
        ('d', _('Draft')),
        ('v', _('Validated')),
        ('e', _('Expired')),
        ('w', _('Withdrawn')),
    )
    status = models.CharField(_('status'), max_length=1, choices=STATUS_CHOICES, default='d')
    date_created = models.DateTimeField(auto_now_add=True)
    date_last_modified = models.DateTimeField(auto_now=True)
<|endoftext|>