Skip to content

Commit

Permalink
helper to replace session - from #45
Browse files Browse the repository at this point in the history
  • Loading branch information
CastixGitHub authored and brondsem committed Jun 2, 2022
1 parent ae76cdd commit 4ae649e
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ parsetab_*
.tox
.eggs/
venv/
.\#*
\#*\#
10 changes: 10 additions & 0 deletions ming/odm/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,16 @@ def __init__(self, mapped_class, collection, session, **kwargs):
raise TypeError('Unknown kwd args: %r' % kwargs)
self._instrument_class(properties, include_properties, exclude_properties)

@classmethod
def replace_session(cls, session):
for _mapper in cls.all_mappers():
_mapper.session = session
_mapper.mapped_class.query.session = session
_mapper.mapped_class.__mongometa__.session = session
_mapper._compiled = False
_mapper.compile()
_mapper.session.ensure_indexes(_mapper.collection)

def __repr__(self):
return '<Mapper %s:%s>' % (
self.mapped_class.__name__, self.collection.m.collection_name)
Expand Down
26 changes: 26 additions & 0 deletions ming/tests/odm/test_declarative.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import sys
from collections import defaultdict
from unittest import TestCase, SkipTest
from unittest.mock import MagicMock

from ming import schema as S
from ming import create_datastore
Expand Down Expand Up @@ -811,3 +812,28 @@ def test_hook_base(self):
[
{'_id': doc._id, 'a': doc.a}
])


class TestReplacingSession(TestCase):

def setUp(self):
Mapper._mapper_by_classname.clear()
self.datastore = create_datastore('mim:///test_db')
self.session = ODMSession(bind=self.datastore)
class Basic(MappedClass):
class __mongometa__:
name = 'hook'
session = self.session
_id = FieldProperty(S.ObjectId)
a = FieldProperty(int)
Mapper.compile_all()
self.Basic = Basic
self.session.remove(self.Basic)

def test_hook_base(self):
assert id(self.Basic.query.session) == id(self.session)
session2 = MagicMock()
new_session = ODMSession(bind=session2)
Mapper.replace_session(new_session)
assert id(self.Basic.query.session) == id(new_session)
assert id(self.session) != id(new_session)
3 changes: 3 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
[pylint]
# disabling protected-access because of mongodb _id property
disable = protected-access

[nosetests]
detailed-errors=1

0 comments on commit 4ae649e

Please sign in to comment.