Beispiel #1
0
def test_cache_miss():
    s_nocache = Session.connect('unit-testing', cache_size=10)
    t = TExtra(i=4)
    s_nocache.save(t)

    s = Session.connect('unit-testing', cache_size=10)
    s.add_to_session(t)
    t2 = s.query(TExtra).filter_by(mongo_id=t.mongo_id).one()
Beispiel #2
0
def test_dereference():
    class A(Document):
        x = IntField()

    s = Session.connect('unit-testing', cache_size=0)
    s.clear_collection(A)

    a = A(x=5)
    s.save(a)
    dbaref = DBRef(collection='A', id=a.mongo_id, database='unit-testing')
    s2 = Session.connect('unit-testing2', cache_size=0)
    assert s2.dereference(dbaref).x == 5
Beispiel #3
0
def test_update_list():
    s = Session.connect('unit-testing')
    s.clear_collection(TIntListDoc)

    tIntList = TIntListDoc(intlist=[1, 2])
    s.save(tIntList)

    # pull out of db
    tFetched = s.query(TIntListDoc).one()

    assert sorted([1, 2]) == sorted(tFetched.intlist)

    # append to list, update
    l = tFetched.intlist
    l.append(3)
    s.update(tFetched)

    # pull out of db
    tFetched = s.query(TIntListDoc).one()

    assert sorted([1, 2, 3]) == sorted(tFetched.intlist)

    tFetched.intlist.remove(1)
    s.update(tFetched)

    tFetched = s.query(TIntListDoc).one()

    assert sorted([2, 3]) == sorted(tFetched.intlist)
Beispiel #4
0
def test_tz_aware():
    import pytz
    from ommongo.session import Session
    from ommongo.document import Document
    # doc
    class DocTZ(Document):
        time = DateTimeField(use_tz=True)
    class DocNoTZ(Document):
        time = DateTimeField(use_tz=False)

    # timezone -- choose one where the author doesn't live
    eastern = pytz.timezone('Australia/Melbourne')
    utc = pytz.utc
    # session
    s = Session.connect('unit-testing', timezone=eastern)
    s.clear_collection(DocTZ)
    s.clear_collection(DocNoTZ)
    # time
    local = eastern.localize(datetime.now())
    local = local.replace(microsecond=0)
    doc = DocTZ(time=local)
    s.save(doc)

    doc = s.query(DocTZ).one()
    assert doc.time == local, (doc.time, local)

    # do the no timezone case for code coverage
    s.save(DocNoTZ(time=datetime(2012, 1, 1)))
    obj = s.query(DocNoTZ).one()
Beispiel #5
0
def test_regex():
    class Spell(Document):
        name = StringField()
    s = Session.connect('unit-testing')
    s.clear_collection(Spell)
    s.save(Spell(name='Wingardium Leviosa'))
    s.save(Spell(name='abracadabra'))
    s.save(Spell(name='ab.*ra.ca.da.*bra'))
    s.save(Spell(name='Alacazam'))

    # check ignore case True
    q = s.query(Spell).filter(Spell.name.startswith('wingardium', ignore_case=True))
    assert q.first().name == 'Wingardium Leviosa'

    # check ignore case False (default)
    xs = s.query(Spell).filter(Spell.name.startswith('wingardium')).all()
    assert len(xs) == 0

    # check regex-free startswith and endswith
    assert len(s.query(Spell).filter(Spell.name.startswith('ab.*ra.ca')).all()) == 1
    assert len(s.query(Spell).filter(Spell.name.endswith('da.*bra')).all()) == 1

    # check regex
    assert len(s.query(Spell).filter(Spell.name.regex(r'^[Aa]\w*[am]$')).all()) == 2

    # check regex with options
    assert len(s.query(Spell).filter(Spell.name.regex(r'^[a]\w*[am]$', options='i')).all()) == 2
Beispiel #6
0
def test_update_ignore_extras():
    s = Session.connect('unit-testing')
    s.clear_collection(TExtra)
    # Create Object
    t = TExtra(i=1, j='test', k='test2')
    s.save(t)
    # Retrieve Object
    t = s.query(TExtra).one()
    assert t.i == 1
    assert t.get_extra_fields()['j'] == 'test'
    assert t.get_extra_fields()['k'] == 'test2'
    # Update Object
    t.i = 5
    del t.get_extra_fields()['j']  # delete an extra field
    t.get_extra_fields()['k'] = 'changed'  # change an extra field
    t.get_extra_fields()['l'] = 'added'  # new extra field
    s.update(t)

    # Retrieve Object
    t_new = s.query(TExtra).one()

    assert 'j' not in t_new.get_extra_fields()
    assert t_new.get_extra_fields()['k'] == 'changed'
    assert t_new.get_extra_fields()['l'] == 'added'
    assert t_new.i == 5
Beispiel #7
0
def test_geo():
    class Place(Document):
        config_collection_name = 'places4'
        loc = GeoField()
        val = IntField()
        index = Index().geo2d(loc, min=-100, max=100)
    s = Session.connect('unit-testing')
    s.clear_collection(Place)
    s.save(Place(loc=(1,1), val=2))
    s.save(Place(loc=(5,5), val=4))
    s.save(Place(loc=(30,30 ), val=5))
    x = s.query(Place).filter(Place.loc.near(0, 1))
    assert x.first().val == 2, x.query

    xs = s.query(Place).filter(Place.loc.near(1, 1, max_distance=2)).all()
    assert len(xs) == 1, xs

    xs = s.query(Place).filter(Place.loc.near_sphere(1, 1, max_distance=50)).all()
    assert len(xs) == 3

    q = s.query(Place).filter(Place.loc.within_box([-2, -2], [2, 2]))
    assert len(q.all()) == 1, q.query

    q = s.query(Place).filter(Place.loc.within_radius(0, 0, 2))
    assert len(q.all()) == 1, q.query

    q = s.query(Place).filter(Place.loc.within_polygon(
        [[-2, 0], [2, 0], [0, 2], [0, -2]]
    ))
    assert len(q.all()) == 1, q.query

    q = s.query(Place).filter(Place.loc.within_radius_sphere(30, 30, 0.0001))
    assert len(q.all()) == 1, q.all()
Beispiel #8
0
def test_cache_max():
    # not a great test, but gets coverage
    s = Session.connect('unit-testing', cache_size=3)
    for i in range(0, 10):
        t = TExtra(i=4)
        s.save(t)
    assert len(s.cache) == 3
Beispiel #9
0
def test_bad_dereference():
    class A(Document):
        x = IntField()

    s = Session.connect('unit-testing', cache_size=0)
    s.clear_collection(A)
    dbaref = DBRef(collection='A', id=ObjectId(), database='unit-testing')
    s.dereference(dbaref)
Beispiel #10
0
def test_cache3():
    s = Session.connect('unit-testing', cache_size=10)
    t = TExtra(i=4)
    s.save(t)
    s.save(t)
    t2 = s.query(TExtra).filter_by(mongo_id=t.mongo_id)[0]
    assert id(t) == id(t2)
    assert id(s.refresh(t)) != t2
Beispiel #11
0
def test_clone():
    s = Session.connect('unit-testing', cache_size=10)
    t = TExtra(i=4)
    s.save(t)

    t2 = s.clone(t)
    s.save(t2)

    assert t2.mongo_id != t.mongo_id
Beispiel #12
0
def test_safe_with_error():
    s = Session.connect('unit-testing')
    s.clear_collection(TUnique)
    s.save(TUnique(i=1))
    try:
        s.save(TUnique(i=1), safe=True)
        assert False, 'No error raised on safe insert for second unique item'
    except DuplicateKeyError:
        assert len(s.queue) == 0
Beispiel #13
0
def test_update():
    s = Session.connect('unit-testing')
    s.clear_collection(T)
    t = T(i=6)
    s.save(t)
    assert s.query(T).one().i == 6

    t.i = 7
    s.update(t)
    assert s.query(T).one().i == 7
Beispiel #14
0
def test_geo_haystack():
    class Place(Document):
        config_collection_name = 'places'
        loc = GeoField()
        val = IntField()
        index = Index().geo_haystack(loc, bucket_size=100).descending('val')
    s = Session.connect('unit-testing')
    s.clear_collection(Place)
    s.save(Place(loc=(1,1), val=2))
    s.save(Place(loc=(5,5), val=4))
Beispiel #15
0
def test_auto_ensure_indexes():
    s = Session.connect('unit-testing', auto_ensure=True)
    s.db.drop_collection(TUnique.get_collection_name())

    s.save(TUnique(i=1))

    indexes = s.get_indexes(TUnique)

    assert len(indexes) == 2
    assert "_id_" in indexes
    assert "i_1" in indexes
Beispiel #16
0
def test_update_change_ops():
    s = Session.connect('unit-testing')
    s.clear_collection(T)
    t = T(i=6, l=[8])
    s.save(t)
    assert s.query(T).one().i == 6

    t.i = 7
    t.l = [8]
    s.update(t, update_ops={T.l: '$pullAll'}, i='$inc')
    t = s.query(T).one()
    assert t.i == 13, t.i
    assert t.l == [], t.l
Beispiel #17
0
def test_update_push():
    s = Session.connect('unit-testing')
    s.clear_collection(T)
    # Create object
    t = T(i=6, l=[3])
    s.save(t)
    t = s.query(T).one()
    assert t.i == 6 and t.l == [3]

    t = s.query(T).fields(T.i).one()
    t.i = 7
    t.l = [4]
    s.update(t, id_expression=T.i == 6)

    t = s.query(T).one()
    assert s.query(T).one().i == 7 and t.l == [3, 4]
Beispiel #18
0
def test_transactions3():
    class Doc(Document):
        i = IntField()

    s = Session.connect('unit-testing')
    s.clear_collection(Doc)
    assert s.query(Doc).count() == 0
    with s:
        s.add(Doc(i=4))
        try:

            with s:
                s.add(Doc(i=2))
                raise Exception()
        except:
            assert s.query(Doc).count() == 0, s.query(Doc).count()
    assert s.query(Doc).count() == 1, s.query(Doc).count()
Beispiel #19
0
def test_transactions():
    class Doc(Document):
        i = IntField()

    s = Session.connect('unit-testing')
    s.clear_collection(Doc)
    assert s.query(Doc).count() == 0
    with s:
        assert s.query(Doc).count() == 0
        s.add(Doc(i=4))
        assert s.query(Doc).count() == 0
        with s:
            assert s.query(Doc).count() == 0
            s.add(Doc(i=2))
            assert s.query(Doc).count() == 0
        assert s.query(Doc).count() == 0, s.query(Doc).count()
    assert s.query(Doc).count() == 2
Beispiel #20
0
def main():
    class Address(Document):
        street_address = StringField()
        city = StringField()
        state_province = StringField()
        country = StringField()

    class User(Document):

        name_index = Index().ascending('name').unique()

        name = StringField()
        email = StringField()

        address = DocumentField(Address)

        def __str__(self):
            return '%s (%s)' % (self.name, self.email)

    with Session.connect('ommongo') as s:

        def print_all():
            for u in s.query(User).filter(User.address.country == 'ID'):
                print u

        s.clear_collection(User)

        a = Address(street_address='Jakarta Barat',
                    city='JKT',
                    state_province='JKT',
                    country='ID')
        u = User(name='OmMongo', email='*****@*****.**', address=a)
        s.save(u)
        print u.mongo_id

        query = User.address.country == 'ID'

        print_all()

        update = s.query(User).filter(User.name > 'adi',
                                      User.name < 'oji').set(
                                          User.email, '*****@*****.**')
        update.execute()
        print_all()
Beispiel #21
0
def test_set_dict_field():
    class TestDict(Document):
        data = DictField(AnythingField())

    s = Session.connect('ommongo-unit-testing')
    s.clear_collection(TestDict)

    td = TestDict()

    td.data = {"foo": "bar", "baz": "qux"}
    s.save(td)

    td = s.query(TestDict).one()

    td.data = {"foo": "bar"}
    s.save(td)

    td = s.query(TestDict).one()

    assert td.data == {'foo': 'bar'}, td.data
Beispiel #22
0
def test_update_docfield_extras():
    s = Session.connect('unit-testing')
    s.clear_collection(TExtraDocField)
    # Create Object
    t = TExtra(i=1, j='test')
    t2 = TExtraDocField(doc=t)
    s.save(t2)
    # Retrieve Object
    t2 = s.query(TExtraDocField).one()
    assert t2.doc.i == 1
    assert t2.doc.get_extra_fields()['j'] == 'test'
    # Update Object's extra fields
    t2.doc.get_extra_fields()['t'] = 'added'

    s.update(t2)

    # Retrieve Object
    t2_new = s.query(TExtraDocField).one()
    assert t2_new.doc.i == 1
    assert t2_new.doc.get_extra_fields()['j'] == 'test'
    assert t2_new.doc.get_extra_fields().get(
        't') == 'added', t2_new.doc.get_extra_fields()
Beispiel #23
0
def test_tz():
    import pytz
    from datetime import datetime

    class DT(Document):
        dt = DateTimeField()
        created = CreatedField(tz_aware=True)
        modified = ModifiedField(tz_aware=True)
        created1 = CreatedField(tz_aware=False)
        modified1 = ModifiedField(tz_aware=False)

    session = Session.connect('unit-testing', timezone=pytz.utc)
    assert session.tz_aware
    session.clear_collection(DT)
    d = DT(dt=pytz.utc.localize(datetime(2012, 1, 1)))
    assert d.created1.tzinfo is None
    assert d.modified1.tzinfo is None

    session.save(d)
    for x in session.query(DT):
        assert x.dt.tzinfo is not None
        assert x.created.tzinfo is not None
        assert x.modified.tzinfo is not None
Beispiel #24
0
def test_update_docfield_list_extras():
    s = Session.connect('unit-testing')
    s.clear_collection(TExtraDocFieldList)

    # Create Objects
    t = TExtra(i=1, j='test')
    t2 = TExtra(i=2, j='test2')
    tListDoc = TExtraDocFieldList(doclist=[t, t2])

    s.save(tListDoc)
    # Retrieve Object
    tListDoc = s.query(TExtraDocFieldList).one()
    assert len(tListDoc.doclist) == 2
    for doc in tListDoc.doclist:
        if doc.i == 1:
            assert doc.get_extra_fields()['j'] == 'test'
            # go ahead and update j now
            doc.get_extra_fields()['j'] = 'testChanged'
        elif doc.i == 2:
            assert doc.get_extra_fields()['j'] == 'test2'
        else:
            assert False

    # update the parent document
    s.update(tListDoc)

    # re-fetch and verify
    tListDoc = s.query(TExtraDocFieldList).one()

    for doc in tListDoc.doclist:
        if doc.i == 1:
            assert doc.get_extra_fields()['j'] == 'testChanged'
        elif doc.i == 2:
            assert doc.get_extra_fields()['j'] == 'test2'
        else:
            assert False
Beispiel #25
0
def test_find_and_modify_in_session():
    s = Session.connect('unit-testing')
    with s:
        s.execute_find_and_modify({})
Beispiel #26
0
 def test_replica_set():
     # just for code coverage
     session = Session.connect('unit-testing', replica_set='rs1')
Beispiel #27
0
def test_safe():
    s = Session.connect('unit-testing', safe=True)
    assert s.safe == True
    s = Session.connect('unit-testing', safe=False)
    assert s.safe == False
Beispiel #28
0
def test_end_in_transaction():
    s = Session.connect('unit-testing')
    with s:
        s.end()
Beispiel #29
0
def test_session():
    s = Session.connect('unit-testing')
    s.clear_collection(T)
    s.save(T(i=1))
    s.clear_queue()
    s.end()
Beispiel #30
0
def test_cache2():
    s = Session.connect('unit-testing')
    t = TExtra(i=4)
    s.save(t)
    t2 = s.query(TExtra).filter_by(mongo_id=t.mongo_id).one()
    assert id(t) != id(t2)