def __init__(self, **kwargs): super(User, self).__init__() # If no arguments are passed, then create a new DbUser if not kwargs: raise ValueError("User can not be instantiated without arguments") # If a DbUser is passed as argument. Just use it and # wrap it with a User object elif 'dbuser' in kwargs: # When a dbuser is passed as argument, then no other arguments # should be passed. if len(kwargs) > 1: raise ValueError("When a DbUser is passed as argument, no" "further arguments are accepted.") dbuser = kwargs.pop('dbuser') if not isinstance(dbuser, DbUser): raise ValueError("Expected a DbUser. Object of a different" "class was given as argument.") self._dbuser = dbuser # If the email of a users is given then create a new User object with # this email. elif 'email' in kwargs: # When a dbuser is passed as argument, then no other arguments # should be passed. if len(kwargs) > 1: raise ValueError("When an email is passed as argument, no" "further arguments are accepted.") email = normalize_email(kwargs.pop('email')) self._dbuser = DbUser(email=email) else: raise ValueError("Only dbuser & email are accepted as arguments")
def test_query(self): """ Test if queries are working """ g1 = Group(name='testquery1').store() g2 = Group(name='testquery2').store() n1 = Node().store() n2 = Node().store() n3 = Node().store() n4 = Node().store() g1.add_nodes([n1, n2]) g2.add_nodes([n1, n3]) newuser = DbUser(email='*****@*****.**', password='').save() g3 = Group(name='testquery3', user=newuser).store() # I should find it g1copy = Group.get(uuid=g1.uuid) self.assertEquals(g1.pk, g1copy.pk) # Try queries res = Group.query(nodes=n4) self.assertEquals([_.pk for _ in res], []) res = Group.query(nodes=n1) self.assertEquals([_.pk for _ in res], [_.pk for _ in [g1, g2]]) res = Group.query(nodes=n2) self.assertEquals([_.pk for _ in res], [_.pk for _ in [g1]]) # I try to use 'get' with zero or multiple results with self.assertRaises(NotExistent): Group.get(nodes=n4) with self.assertRaises(MultipleObjectsError): Group.get(nodes=n1) self.assertEquals(Group.get(nodes=n2).pk, g1.pk) # Query by user res = Group.query(user=newuser) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g3])) # Same query, but using a string (the username=email) instead of # a DbUser object res = Group.query(user=newuser.email) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g3])) res = Group.query(user=get_automatic_user()) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g1, g2])) # Final cleanup g1.delete() g2.delete() newuser.delete()
def insert_data(self): """ Insert default data into the DB. """ email = get_configured_user_email() has_user = DbUser.query.filter(DbUser.email == email).first() if not has_user: self.user = DbUser(get_configured_user_email(), "foo", "bar", "tests") self.test_session.add(self.user) self.test_session.commit() else: self.user = has_user # Required by the calling class self.user_email = self.user.email # Also self.computer is required by the calling class has_computer = DbComputer.query.filter( DbComputer.hostname == 'localhost').first() if not has_computer: self.computer = SqlAlchemyTests._create_computer() self.computer.store() else: self.computer = Computer(dbcomputer=has_computer)
def test_user_node_1(self): """Test that when a user and a node having that user are created, storing NODE induces storage of the USER Assert the correct storage of user and node.""" # Create user dbu1 = DbUser('test1@schema', 'spam', 'eggs', 'monty') # Creat node node_dict = dict(user=dbu1) dbn_1 = DbNode(**node_dict) # Check that the two are neither flushed nor committed self.assertIsNone(dbu1.id) self.assertIsNone(dbn_1.id) session = aiida.backends.sqlalchemy.get_scoped_session() # Add only the node and commit session.add(dbn_1) session.commit() # Check that a pk has been assigned, which means that things have # been flushed into the database self.assertIsNotNone(dbn_1.id) self.assertIsNotNone(dbu1.id)
def test_user_node_4(self): """Test that when several nodes are created with the same user and each of them is assigned to the same name, storage of last node object associated to that node does not trigger storage of all objects. Assert the correct storage of the user and node. Assert the non-storage of the other nodes.""" # Create user dbu1 = DbUser('tests4@schema', 'spam', 'eggs', 'monty') # Creat node objects assigningd them to the same name # Check https://docs.python.org/2/tutorial/classes.html subsec. 9.1 for _ in range(5): # It is important to change the uuid each time (or any other # variable) so that a different objects (with a different pointer) # is actually created in this scope. dbn_1 = DbNode(user=dbu1, uuid=get_new_uuid()) # Check that the two are neither flushed nor committed self.assertIsNone(dbu1.id) self.assertIsNone(dbn_1.id) session = aiida.backends.sqlalchemy.get_scoped_session() # Add only first node and commit session.add(dbn_1) session.commit() # Check for which object a pk has been assigned, which means that # things have been at least flushed into the database self.assertIsNotNone(dbu1.id) self.assertIsNotNone(dbn_1.id)
def test_user_node_3(self): """Test that when a user and two nodes having that user are created, storing only ONE NODE induces storage of that node, of the user but not of the other node Assert the correct storage of the user and node. Assert the non-storage of the other node.""" # Create user dbu1 = DbUser('tests3@schema', 'spam', 'eggs', 'monty') # Creat node node_dict = dict(user=dbu1) dbn_1 = DbNode(**node_dict) dbn_2 = DbNode(**node_dict) # Check that the two are neither flushed nor committed self.assertIsNone(dbu1.id) self.assertIsNone(dbn_1.id) self.assertIsNone(dbn_2.id) session = aiida.backends.sqlalchemy.get_scoped_session() # Add only first node and commit session.add(dbn_1) session.commit() # Check for which object a pk has been assigned, which means that # things have been at least flushed into the database self.assertIsNotNone(dbu1.id) self.assertIsNotNone(dbn_1.id) self.assertIsNone(dbn_2.id)
def test_user_node_2(self): """Test that when a user and a node having that user are created, storing USER does NOT induce storage of the NODE Assert the correct storage of user and node.""" import warnings from sqlalchemy import exc as sa_exc # Create user dbu1 = DbUser('tests2@schema', 'spam', 'eggs', 'monty') # Creat node node_dict = dict(user=dbu1) dbn_1 = DbNode(**node_dict) # Check that the two are neither flushed nor committed self.assertIsNone(dbu1.id) self.assertIsNone(dbn_1.id) session = aiida.backends.sqlalchemy.get_scoped_session() # Catch all the SQLAlchemy warnings generated by the following code with warnings.catch_warnings(): # pylint: disable=no-member warnings.simplefilter('ignore', category=sa_exc.SAWarning) # pylint: disable=no-member # Add only the user and commit session.add(dbu1) session.commit() # Check that a pk has been assigned (or not), which means that things # have been flushed into the database self.assertIsNotNone(dbu1.id) self.assertIsNone(dbn_1.id)
def test_User_node_2(self): """ Test that when a user and a node having that user are created, storing USER does NOT induce storage of the NODE Assert the correct storage of user and node """ import warnings from sqlalchemy import exc as sa_exc # Create user dbu1 = DbUser('tests2@schema', "spam", "eggs", "monty") # Creat node node_dict = dict(user=dbu1) dbn1 = DbNode(**node_dict) # Check that the two are neither flushed nor committed self.assertIsNone(dbu1.id) self.assertIsNone(dbn1.id) # Catch all the SQLAlchemy warnings generated by the following code with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa_exc.SAWarning) # Add only the user and commit aiida.backends.sqlalchemy.session.add(dbu1) aiida.backends.sqlalchemy.session.commit() # Check that a pk has been assigned (or not), which means that things # have been flushed into the database self.assertIsNotNone(dbu1.id) self.assertIsNone(dbn1.id)
def __init__(self, backend, email, first_name, last_name, institution): super(SqlaUser, self).__init__(backend) self._dbuser = utils.ModelWrapper( DbUser(email=email, first_name=first_name, last_name=last_name, institution=institution))
def __init__(self, backend, email, first_name, last_name, institution): # pylint: disable=too-many-arguments super().__init__(backend) self._dbmodel = utils.ModelWrapper( DbUser(email=email, first_name=first_name, last_name=last_name, institution=institution))
def setUpClass(cls): config = get_profile_config("tests") engine_url = ("postgresql://{AIIDADB_USER}:{AIIDADB_PASS}@" "{AIIDADB_HOST}:{AIIDADB_PORT}/{AIIDADB_NAME}").format( **config) engine = create_engine(engine_url, json_serializer=dumps_json, json_deserializer=loads_json) cls.connection = engine.connect() session = Session(bind=cls.connection) sa.session = session if cls.drop_all: Base.metadata.drop_all(cls.connection) Base.metadata.create_all(cls.connection) install_tc(cls.connection) email = get_configured_user_email() has_user = DbUser.query.filter(DbUser.email == email).first() if not has_user: user = DbUser(email, "foo", "bar", "tests") sa.session.add(user) sa.session.commit() sa.session.expire_all() has_computer = DbComputer.query.filter( DbComputer.hostname == 'localhost').first() if not has_computer: computer = SqlAlchemyTests._create_computer() computer.store() session.close()
def test_query(self): """ Test if queries are working """ from aiida.orm.group import Group from aiida.common.exceptions import NotExistent, MultipleObjectsError from aiida.backends.sqlalchemy.models.user import DbUser from aiida.orm.backend import construct_backend backend = construct_backend() g1 = Group(name='testquery1').store() self.addCleanup(g1.delete) g2 = Group(name='testquery2').store() self.addCleanup(g2.delete) n1 = Node().store() n2 = Node().store() n3 = Node().store() n4 = Node().store() g1.add_nodes([n1, n2]) g2.add_nodes([n1, n3]) newuser = DbUser(email='*****@*****.**', password='').get_aiida_class() g3 = Group(name='testquery3', user=newuser).store() # I should find it g1copy = Group.get(uuid=g1.uuid) self.assertEquals(g1.pk, g1copy.pk) # Try queries res = Group.query(nodes=n4) self.assertEquals([_.pk for _ in res], []) res = Group.query(nodes=n1) self.assertEquals([_.pk for _ in res], [_.pk for _ in [g1, g2]]) res = Group.query(nodes=n2) self.assertEquals([_.pk for _ in res], [_.pk for _ in [g1]]) # I try to use 'get' with zero or multiple results with self.assertRaises(NotExistent): Group.get(nodes=n4) with self.assertRaises(MultipleObjectsError): Group.get(nodes=n1) self.assertEquals(Group.get(nodes=n2).pk, g1.pk) # Query by user res = Group.query(user=newuser) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g3])) # Same query, but using a string (the username=email) instead of # a DbUser object res = Group.query(user=newuser.email) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g3])) res = Group.query(user=backend.users.get_automatic_user()) self.assertEquals(set(_.pk for _ in res), set(_.pk for _ in [g1, g2]))
class User(AbstractUser): def __init__(self, **kwargs): super(User, self).__init__() # If no arguments are passed, then create a new DbUser if not kwargs: raise ValueError("User can not be instantiated without arguments") # If a DbUser is passed as argument. Just use it and # wrap it with a User object elif 'dbuser' in kwargs: # When a dbuser is passed as argument, then no other arguments # should be passed. if len(kwargs) > 1: raise ValueError("When a DbUser is passed as argument, no" "further arguments are accepted.") dbuser = kwargs.pop('dbuser') if not isinstance(dbuser, DbUser): raise ValueError("Expected a DbUser. Object of a different" "class was given as argument.") self._dbuser = dbuser # If the email of a users is given then create a new User object with # this email. elif 'email' in kwargs: # When a dbuser is passed as argument, then no other arguments # should be passed. if len(kwargs) > 1: raise ValueError("When an email is passed as argument, no" "further arguments are accepted.") email = normalize_email(kwargs.pop('email')) self._dbuser = DbUser(email=email) else: raise ValueError("Only dbuser & email are accepted as arguments") @staticmethod def get_db_columns(): from aiida.orm.implementation.general.utils import get_db_columns return get_db_columns(DbUser) @property def pk(self): return self._dbuser.id @property def id(self): return self._dbuser.id @property def to_be_stored(self): return self._dbuser.id is None def save(self): if not self.to_be_stored: self._dbuser.save() def force_save(self): self._dbuser.save() @property def email(self): return self._dbuser.email @email.setter def email(self, val): self._dbuser.email = val if not self.to_be_stored: self._dbuser.save() def _set_password(self, val): self._dbuser.password = val self.save() def _get_password(self): return self._dbuser.password @property def is_superuser(self): return self._dbuser.is_superuser @is_superuser.setter def is_superuser(self, val): self._dbuser.is_superuser = val self.save() @property def first_name(self): return self._dbuser.first_name @first_name.setter def first_name(self, val): self._dbuser.first_name = val self.save() @property def last_name(self): return self._dbuser.last_name @last_name.setter def last_name(self, val): self._dbuser.last_name = val self.save() @property def institution(self): return self._dbuser.institution @institution.setter def institution(self, val): self._dbuser.institution = val self.save() @property def is_staff(self): return self._dbuser.is_staff @is_staff.setter def is_staff(self, val): self._dbuser.is_staff = val self.save() @property def is_active(self): return self._dbuser.is_active @is_active.setter def is_active(self, val): self._dbuser.is_active = val self.save() @property def last_login(self): return self._dbuser.last_login @last_login.setter def last_login(self, val): self._dbuser.last_login = val self.save() @property def date_joined(self): return self._dbuser.date_joined @date_joined.setter def date_joined(self, val): self._dbuser.date_joined = val self.save() @classmethod def search_for_users(cls, **kwargs): id = kwargs.pop('id', None) if id is None: id = kwargs.pop('pk', None) email = kwargs.pop('email', None) # Constructing the default query dbuser_query = DbUser.query # If an id is specified then we add it to the query if id is not None: dbuser_query = dbuser_query.filter_by(id=id) # If an email is specified then we add it to the query if email is not None: dbuser_query = dbuser_query.filter_by(email=email) dbusers = dbuser_query.all() users = [] for dbuser in dbusers: users.append(cls(dbuser=dbuser)) return users