Exemplo n.º 1
0
 def setUp( self ):
     super( CollectionProxyCase, self ).setUp()
     session = Session()
     self.collection = list( session.query( Person ).all() )
     self.proxy = CollectionProxy( self.person_admin,
                                   collection_getter=lambda:self.collection,
                                   columns_getter=self.person_admin.get_columns )
Exemplo n.º 2
0
 def setUp(self):
     super(CollectionProxyCase, self).setUp()
     session = Session()
     self.collection = list(session.query(Person).all())
     self.proxy = CollectionProxy(
         self.person_admin,
         collection_getter=lambda: self.collection,
         columns_getter=self.person_admin.get_columns)
Exemplo n.º 3
0
 def get_or_create( cls, username ):
     session = Session()
     authentication = session.query( cls ).filter_by( username = username ).first()
     if not authentication:
         authentication = cls( username = username )
         session.add( authentication )
         session.flush()
     return authentication
Exemplo n.º 4
0
 def get_or_create( cls, username ):
     session = Session()
     authentication = session.query( cls ).filter_by( username = username ).first()
     if not authentication:
         authentication = cls( username = username )
         session.add( authentication )
         session.flush()
     return authentication
Exemplo n.º 5
0
class SearchCase( unittest.TestCase ):
    """Test the creation of search queries"""
    
    def setUp( self ):
        metadata.bind = settings.ENGINE()
        metadata.create_all()
        self.session = Session()
        #
        # insert the value of i in each column of T, that can be searched for
        #
        for (i,name), definition in types_to_test.items():
            value = self.value_for_type( definition, i )
            t = T()
            setattr( t, name, value )
        self.session.flush()
        self.admin = TAdmin()
        
    def value_for_type( self, definition, i ):
        value = i        
        if issubclass( definition, sqlalchemy.types.DateTime ):
            value = datetime.datetime( year = 2000, month = 1, day = 1, hour = 1, minute = i )       
        elif issubclass( definition, sqlalchemy.types.Date ):
            value = datetime.date( year = 2000, month = 1, day = i%31 )                  
        elif issubclass( definition, sqlalchemy.types.Time ):
            value = datetime.time( hour = 1, minute = i )
        elif issubclass( definition, sqlalchemy.types.String ):
            value = str( i )
        elif issubclass( definition, sqlalchemy.types.Boolean ):
            value = True
        return value
            
    def test_search_decorator( self ):
        """Verify it search works for most common types"""
        from camelot.view.search import create_entity_search_query_decorator
        for (i,name), definition in types_to_test.items():
            value = self.value_for_type( definition, i )
            #
            # @todo : search for types that need special conversion to string
            #         is skipped for now because the test would become too
            #         convoluted, this should work through a to_string field
            #         attribute.
            #
            if isinstance( value, ( datetime.date, datetime.time, bool) ):
                continue
            string_value = str( value )
            
            search_decorator = create_entity_search_query_decorator( self.admin,
                                                                     string_value )
            query = self.session.query( T )
            query = search_decorator( query )
            
            #print query
            
            self.assertTrue( query.count() > 0 )
Exemplo n.º 6
0
    def model_run(self, model_context):
        from camelot.view.action_steps import (SelectFile,
                                               UpdateProgress,
                                               Refresh,
                                               FlushSession)

        select_files = SelectFile('Txt Files (*.txt *.csv);;All Files (*)')
        select_files.single = False
        file_names = yield select_files
        file_count = len(file_names)

        import os
        from camelot.core.orm import Session
        from rms.Model.ResurseUmane import ResurseUmane
        from rms.Model.Discipline import Discipline
        from rms.Model.OreSuplimentare import OreSuplimentare

        session = Session()

        for i, file_name in enumerate(file_names):
            yield UpdateProgress(i, file_count)
            f = open(file_name)
            info_prof = f.readline().split(";")[:-1]
            if session.query(Profesor).filter(Profesor.username == info_prof[0]).first() != None:
                raise UserException("Exista deja profesorul "+info_prof[2])
            prof = Profesor(*info_prof)
            session.add(prof)
            for line in f:
                if line[-1] == ';':
                    vals = line[:-1].split(',')
                else:
                    vals = line[:-2].split(',')


                print(vals)
                try:
                    vals[0] = int(vals[0])
                    oresup = OreSuplimentare(*vals)
                    oresup.profesor = prof
                    session.add(oresup)
                except ValueError:
                    disc = Discipline(*vals)
                    disc.titular = prof
                    session.add(disc)
        yield FlushSession(session)
        # begin refresh
        yield Refresh()
        # end refresh
Exemplo n.º 7
0
 def get_current_version(cls, fixture_class=None, session=None):
     """Get the current version of the fixtures in the database for a certain 
     fixture class.
     
     :param fixture_class: the fixture class for which to get the version
     :param session: the session to use to query the database, if `None` is
         given, the default Camelot session is used
     
     :return: an integer representing the current version, 0 if no version found
     """
     if session is None:
         session = Session()
     obj = session.query(cls).filter_by(fixture_class=fixture_class).first()
     if obj:
         return obj.fixture_version
     return 0
Exemplo n.º 8
0
 def set_current_version(cls,
                         fixture_class=None,
                         fixture_version=0,
                         session=None):
     """Set the current version of the fixtures in the database for a certain 
     fixture class.
     
     :param fixture_class: the fixture class for which to get the version
     :param fixture_version: the version number to which to set the fixture 
         version
     :param session: the session to use to query the database, if `None` is
         given, the default Camelot session is used
     """
     if session is None:
         session = Session()
     obj = session.query(cls).filter_by(fixture_class=fixture_class).first()
     if not obj:
         obj = FixtureVersion(fixture_class=fixture_class, _session=session)
     obj.fixture_version = fixture_version
     session.flush()
Exemplo n.º 9
0
 def translate_or_register( cls, source, language ):
     """Translate source to language, if no translation is found, register the
     source as to be translated and return the source"""
     if source:
         source = unicode( source )
         translation = cls.translate( source, language )
         if not translation:
             session = Session()
             query = session.query( cls )
             translation = query.filter_by( source = source, 
                                            language = language ).first()
             if not translation:
                 if ( source, language ) not in cls._cache:
                     registered_translation = Translation( source = source, 
                                                           language = language )
                     cls._cache[( source, language )] = source
                     session.flush( [registered_translation] )
                     logger.debug( 'registed %s with id %s' % ( source, registered_translation.id ) )
             return source
         return translation
     return ''
Exemplo n.º 10
0
    def model_run(self, model_context):
        from camelot.view.action_steps import (SelectFile,
                                               UpdateProgress,
                                               Refresh,
                                               FlushSession)

        select_files = SelectFile('Txt Files (*.txt *.csv);;All Files (*)')
        select_files.single = False
        file_names = yield select_files
        file_count = len(file_names)

        import os
        from camelot.core.orm import Session
        from rms.Model.Orar import Orar

        session = Session()

        for i, file_name in enumerate(file_names):
            yield UpdateProgress(i, file_count)
            title = os.path.splitext(os.path.basename(file_name))[0]
            print(file_name)
            for line in open(file_name):
                vals = line.split(';')[:-1]
                if len(vals) != 8:
                    raise ImportException("Fisierul nu e dat bine")
                if vals[2] not in ['0', '1', '2']:
                    raise ImportException("Frecventa nu e data bine")
                print(vals)
                orar = Orar(*vals)
                print(orar)
                session.add(orar)
                disc = session.query(Discipline).filter(Discipline.disc==orar.disc).first()
                if disc:
                    orar.disciplina = disc
                    session.flush()

        yield FlushSession(session)
        # begin refresh
        yield Refresh()
        # end refresh
Exemplo n.º 11
0
 def translate_or_register(cls, source, language):
     """Translate source to language, if no translation is found, register the
     source as to be translated and return the source"""
     if source:
         source = unicode(source)
         translation = cls.translate(source, language)
         if not translation:
             session = Session()
             query = session.query(cls)
             translation = query.filter_by(source=source,
                                           language=language).first()
             if not translation:
                 if (source, language) not in cls._cache:
                     registered_translation = Translation(source=source,
                                                          language=language)
                     cls._cache[(source, language)] = source
                     session.flush([registered_translation])
                     logger.debug('registed %s with id %s' %
                                  (source, registered_translation.id))
             return source
         return translation
     return ''
Exemplo n.º 12
0
class PartyCase(ModelThreadTestCase):
    """Test the build in party - address - contact mechanism model"""
    def setUp(self):
        super(PartyCase, self).setUp()
        from camelot.admin.application_admin import ApplicationAdmin
        self.session = Session()
        self.app_admin = ApplicationAdmin()
        self.person_admin = self.app_admin.get_related_admin(party.Person)
        self.organization_admin = self.app_admin.get_related_admin(
            party.Organization)

    def tearDown(self):
        self.session.expunge_all()

    def test_party(self):
        p = party.Party()
        self.assertFalse(p.name)

    def test_geographic_boundary(self):
        belgium = party.Country.get_or_create(code=u'BE', name=u'Belgium')
        self.assertTrue(unicode(belgium))
        city = party.City.get_or_create(country=belgium,
                                        code='1000',
                                        name='Brussels')
        return city

    def test_address(self):
        city = self.test_geographic_boundary()
        address = party.Address.get_or_create(street1='Avenue Louise',
                                              street2=None,
                                              city=city)
        self.assertTrue(unicode(address))
        return address

    def test_party_address(self):
        city = self.test_geographic_boundary()
        org = party.Organization(name='PSF')
        party_address = party.PartyAddress(party=org)
        party_address.street1 = 'Avenue Louise 5'
        party_address.street2 = 'Boite 4'
        party_address.city = city
        party_address_admin = party.AddressAdmin(self.app_admin,
                                                 party.PartyAddress)
        self.assertTrue(party_address.address in party_address_admin.
                        get_compounding_objects(party_address))
        self.assertTrue(party_address.address in self.session.new)
        # everything should be flushed through the party admin
        org_admin = self.app_admin.get_related_admin(party.Organization)
        org_validator = org_admin.get_validator()
        self.assertTrue(
            party_address in org_admin.get_compounding_objects(org))
        org_admin.flush(org)
        self.assertFalse(party_address.address in self.session.new)
        party_address_admin.refresh(party_address)
        # test hybrid property getters on Party and PartyAddress
        self.assertEqual(party_address.street1, 'Avenue Louise 5')
        self.assertEqual(party_address.street2, 'Boite 4')
        self.assertEqual(party_address.city, city)
        self.assertEqual(org.street1, 'Avenue Louise 5')
        self.assertEqual(org.street2, 'Boite 4')
        self.assertEqual(org.city, city)
        self.assertTrue(unicode(party_address))
        query = self.session.query(party.PartyAddress)
        self.assertTrue(
            query.filter(
                party.PartyAddress.street1 == 'Avenue Louise 5').first())
        self.assertTrue(
            query.filter(party.PartyAddress.street2 == 'Boite 4').first())
        # if party address changes, party should be updated
        depending_objects = list(
            party_address_admin.get_depending_objects(party_address))
        self.assertTrue(org in depending_objects)
        # if address changes, party address and party should be updated
        address = party_address.address
        address_admin = self.app_admin.get_related_admin(party.Address)
        depending_objects = list(address_admin.get_depending_objects(address))
        self.assertTrue(party_address in depending_objects)
        self.assertTrue(org in depending_objects)
        # test hybrid property setters on Party
        org.street1 = 'Rue Belliard 1'
        org.street2 = 'Second floor'
        org.city = None
        # expunge should expunge the related address objects as well, so
        # after an expunge, the session as a whole can be flushed
        org_admin.expunge(org)
        self.session.flush()
        # test hybrid property setters on a new party
        org = party.Organization(name='PSF')
        org.street1 = 'Rue Belliard 1'
        org.street2 = 'Second floor'
        org.city = city
        org_admin.flush(org)
        self.assertEqual(len(org.addresses), 1)
        self.assertEqual(org.street1, 'Rue Belliard 1')
        self.assertEqual(org.street2, 'Second floor')
        self.assertEqual(org.city, city)
        # test invalidation of org object and refresh it
        self.assertFalse(org_validator.validate_object(org))
        org.city = None
        self.assertTrue(org_validator.validate_object(org))
        org_admin.refresh(org)
        self.assertFalse(org_validator.validate_object(org))
        # removing all the address properties should make the
        # object valid again
        org.street1 = None
        org.street2 = None
        org.city = None
        self.assertFalse(org_validator.validate_object(org))
        # removing all address properties of a not yet flushed
        # address should expunge the address
        org = party.Organization(name='PSF')
        org.street1 = 'Rue Belliard 1'
        for address in org.addresses:
            self.assertTrue(address in self.session.new)
        org.street1 = None
        self.assertTrue(address not in self.session)
        self.assertEqual(len(org.addresses), 0)

    def test_person(self):
        person = party.Person(first_name=u'Robin', last_name=u'The brave')
        self.assertEqual(person.email, None)
        self.assertEqual(person.phone, None)
        self.assertEqual(person.fax, None)
        self.assertEqual(person.street1, None)
        self.assertEqual(person.street2, None)
        self.assertEqual(person.city, None)
        self.person_admin.flush(person)
        person2 = party.Person(first_name=u'Robin')
        self.assertFalse(person2.note)
        person2.last_name = u'The brave'
        # gui should warn this person exists
        self.assertTrue(person2.note)
        return person

    def test_contact_mechanism(self):
        contact_mechanism = party.ContactMechanism(mechanism=(u'email',
                                                              u'*****@*****.**'))
        self.assertTrue(unicode(contact_mechanism))

    def test_person_contact_mechanism(self):
        # create a new person
        person = party.Person(first_name=u'Robin', last_name=u'The brave')
        self.person_admin.flush(person)
        self.assertEqual(person.email, None)
        # set the contact mechanism
        mechanism_1 = (u'email', u'*****@*****.**')
        person.email = mechanism_1
        # the default from and thru dates should be set when
        # setting the party defaults
        self.person_admin.set_defaults(person)
        self.assertTrue(person.contact_mechanisms[0].from_date)
        self.person_admin.flush(person)
        self.assertEqual(person.email, mechanism_1)
        # change the contact mechanism, after a flush
        mechanism_2 = (u'email', u'*****@*****.**')
        person.email = mechanism_2
        self.person_admin.flush(person)
        self.assertEqual(person.email, mechanism_2)
        # remove the contact mechanism after a flush
        person.email = ('email', '')
        self.assertEqual(person.email, None)
        self.person_admin.flush(person)
        self.assertEqual(person.email, None)
        admin = party.PartyContactMechanismAdmin(self.app_admin,
                                                 party.PartyContactMechanism)
        contact_mechanism = party.ContactMechanism(mechanism=mechanism_1)
        party_contact_mechanism = party.PartyContactMechanism(
            party=person, contact_mechanism=contact_mechanism)
        admin.flush(party_contact_mechanism)
        admin.refresh(party_contact_mechanism)
        list(admin.get_depending_objects(party_contact_mechanism))
        #
        # if the contact mechanism changes, the party person should be
        # updated as well
        #
        contact_mechanism_admin = self.app_admin.get_related_admin(
            party.ContactMechanism)
        depending_objects = list(
            contact_mechanism_admin.get_depending_objects(contact_mechanism))
        self.assertTrue(person in depending_objects)
        self.assertTrue(party_contact_mechanism in depending_objects)
        #
        # if the party contact mechanism changes, the party should be updated
        # as well
        depending_objects = list(
            admin.get_depending_objects(party_contact_mechanism))
        self.assertTrue(person in depending_objects)
        # delete the person
        self.person_admin.delete(person)

    def test_organization(self):
        org = party.Organization(name='PSF')
        org.email = ('email', '*****@*****.**')
        org.phone = ('phone', '1234')
        org.fax = ('fax', '4567')
        self.organization_admin.flush(org)
        self.assertTrue(unicode(org))
        self.assertEqual(org.number_of_shares_issued, 0)
        query = orm.object_session(org).query(party.Organization)
        self.assertTrue(
            query.filter(
                party.Organization.email == ('email',
                                             '*****@*****.**')).first())
        self.assertTrue(
            query.filter(party.Organization.phone == ('phone',
                                                      '1234')).first())
        self.assertTrue(
            query.filter(party.Organization.fax == ('fax', '4567')).first())
        return org

    def test_party_relationship(self):
        person = self.test_person()
        org = self.test_organization()
        employee = party.EmployerEmployee(established_from=org,
                                          established_to=person)
        self.assertTrue(unicode(employee))

    def test_party_contact_mechanism(self):
        person = self.test_person()
        party_contact_mechanism = party.PartyContactMechanism(party=person)
        party_contact_mechanism.mechanism = (u'email', u'*****@*****.**')
        party_contact_mechanism.mechanism = (u'email', u'*****@*****.**')
        self.assertTrue(party_contact_mechanism in self.session.new)
        self.assertTrue(
            party_contact_mechanism.contact_mechanism in self.session.new)
        # flushing trough the party should flush the contact mechanism
        self.person_admin.flush(person)
        self.assertFalse(party_contact_mechanism in self.session.new)
        self.assertFalse(
            party_contact_mechanism.contact_mechanism in self.session.new)
        self.assertTrue(unicode(party_contact_mechanism))
        query = self.session.query(party.PartyContactMechanism)
        self.assertTrue(
            query.filter(party.PartyContactMechanism.mechanism == (
                u'email', u'*****@*****.**')).first())
        # party contact mechanism is only valid when contact mechanism is
        # valid
        party_contact_mechanism_admin = self.app_admin.get_related_admin(
            party.PartyContactMechanism)
        compounding_objects = list(
            party_contact_mechanism_admin.get_compounding_objects(
                party_contact_mechanism))
        self.assertTrue(
            party_contact_mechanism.contact_mechanism in compounding_objects)
        party_contact_mechanism_validator = party_contact_mechanism_admin.get_validator(
        )
        self.assertFalse(
            party_contact_mechanism_validator.validate_object(
                party_contact_mechanism))
        party_contact_mechanism.contact_mechanism.mechanism = None
        self.assertTrue(
            party_contact_mechanism_validator.validate_object(
                party_contact_mechanism))
        # the party is only valid when the contact mechanism is
        # valid
        party_admin = self.app_admin.get_related_admin(party.Person)
        party_validator = party_admin.get_validator()
        self.assertTrue(party_validator.validate_object(person))

    def test_party_category(self):
        org = self.test_organization()
        category = party.PartyCategory(name=u'Imortant')
        category.parties.append(org)
        self.session.flush()
        self.assertTrue(list(category.get_contact_mechanisms(u'email')))
        self.assertTrue(unicode(category))
Exemplo n.º 13
0
from camelot.core.orm import Session
import os
import sys
sys.path.append(os.environ["GRADEBOOK_ROOT"])
import main  # noqa

from camelot.core.conf import settings
settings.setup_model()

# }}}

session = Session()

from gradebook.model import (Course,
        Student, StudentContactInfo)
course, = session.query(Course).all()

import csv
with open('class-list.csv', 'rb') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=";")
    for row in reader:
        print row
        ln = row["Last"]
        fn = row["First"]
        student = Student(first_name=unicode(fn.strip()),
                last_name=unicode(ln.strip()),
                user_name=unicode(row["NetID"]),
                course=course)

        session.add(student)
        session.add(StudentContactInfo(
Exemplo n.º 14
0
# {{{ boilerplate

from camelot.core.orm import Session
import os, sys
sys.path.append(os.environ["GRADEBOOK_ROOT"])
import main

from camelot.core.conf import settings
settings.setup_model()

# }}}

session = Session()

from gradebook.model import Course
for name in session.query(Course.name):
    print name

session.flush()

Exemplo n.º 15
0
import os, sys
sys.path.append(os.environ["GRADEBOOK_ROOT"])
import main

from camelot.core.conf import settings
settings.setup_model()

# }}}

session = Session()

from gradebook.model import (Student,
        Assignment, AssignmentStateChange as ASC)

assignments = list(session.query(Assignment)
        .filter(Assignment.course_id == course_id)
        .filter(Assignment.kind == "homework")
        )

proj_pres, = list(session.query(Assignment)
        .filter(Assignment.course_id == course_id)
        .filter(Assignment.kind == "project")
        .filter(Assignment.number == 0)
        )

proj_report, = list(session.query(Assignment)
        .filter(Assignment.course_id == course_id)
        .filter(Assignment.kind == "project")
        .filter(Assignment.number == 1)
        )
Exemplo n.º 16
0
class PartyCase( ModelThreadTestCase ):
    """Test the build in party - address - contact mechanism model"""
  
    def setUp(self):
        super( PartyCase, self ).setUp()
        from camelot.admin.application_admin import ApplicationAdmin
        self.session = Session()
        self.app_admin = ApplicationAdmin()
        self.person_admin = self.app_admin.get_related_admin( party.Person )
        self.organization_admin = self.app_admin.get_related_admin( party.Organization )
        
    def tearDown(self):
        self.session.expunge_all()
       
    def test_party( self ):
        p = party.Party()
        self.assertFalse( p.name )
        
    def test_geographic_boundary( self ):
        belgium = party.Country.get_or_create( code = u'BE', 
                                               name = u'Belgium' )
        self.assertTrue( unicode( belgium ) )
        city = party.City.get_or_create( country = belgium,
                                         code = '1000',
                                         name = 'Brussels' )
        return city
        
    def test_address( self ):
        city = self.test_geographic_boundary()
        address = party.Address.get_or_create( street1 = 'Avenue Louise',
                                               street2 = None,
                                               city = city )
        self.assertTrue( unicode( address ) )
        return address
    
    def test_party_address( self ):
        city = self.test_geographic_boundary()
        org = party.Organization( name = 'PSF' )
        party_address = party.PartyAddress( party = org )
        party_address.street1 = 'Avenue Louise 5'
        party_address.street2 = 'Boite 4'
        party_address.city = city
        party_address_admin = party.AddressAdmin( self.app_admin, party.PartyAddress )
        self.assertTrue( party_address.address in party_address_admin.get_compounding_objects( party_address ) )
        self.assertTrue( party_address.address in self.session.new )
        # everything should be flushed through the party admin
        org_admin = self.app_admin.get_related_admin( party.Organization )
        org_validator = org_admin.get_validator()
        self.assertTrue( party_address in org_admin.get_compounding_objects( org ) )
        org_admin.flush( org )
        self.assertFalse( party_address.address in self.session.new )
        party_address_admin.refresh( party_address )
        # test hybrid property getters on Party and PartyAddress
        self.assertEqual( party_address.street1, 'Avenue Louise 5' )
        self.assertEqual( party_address.street2, 'Boite 4' )
        self.assertEqual( party_address.city, city )
        self.assertEqual( org.street1, 'Avenue Louise 5' )
        self.assertEqual( org.street2, 'Boite 4' )
        self.assertEqual( org.city, city )        
        self.assertTrue( unicode( party_address ) )
        query = self.session.query( party.PartyAddress )
        self.assertTrue( query.filter( party.PartyAddress.street1 == 'Avenue Louise 5' ).first() )
        self.assertTrue( query.filter( party.PartyAddress.street2 == 'Boite 4' ).first() )
        # if party address changes, party should be updated
        depending_objects = list( party_address_admin.get_depending_objects( party_address ) )
        self.assertTrue( org in depending_objects )
        # if address changes, party address and party should be updated
        address = party_address.address
        address_admin = self.app_admin.get_related_admin( party.Address )
        depending_objects = list( address_admin.get_depending_objects( address ) )
        self.assertTrue( party_address in depending_objects )
        self.assertTrue( org in depending_objects )
        # test hybrid property setters on Party
        org.street1 = 'Rue Belliard 1'
        org.street2 = 'Second floor'
        org.city = None
        # expunge should expunge the related address objects as well, so
        # after an expunge, the session as a whole can be flushed
        org_admin.expunge( org )
        self.session.flush()
        # test hybrid property setters on a new party
        org = party.Organization( name = 'PSF' )
        org.street1 = 'Rue Belliard 1'
        org.street2 = 'Second floor'
        org.city = city
        org_admin.flush( org )
        self.assertEqual( len( org.addresses ), 1 )
        self.assertEqual( org.street1, 'Rue Belliard 1' )
        self.assertEqual( org.street2, 'Second floor' )
        self.assertEqual( org.city, city )
        # test invalidation of org object and refresh it
        self.assertFalse( org_validator.validate_object( org ) )
        org.city = None
        self.assertTrue( org_validator.validate_object( org ) )
        org_admin.refresh( org )
        self.assertFalse( org_validator.validate_object( org ) )
        # removing all the address properties should make the
        # object valid again
        org.street1 = None
        org.street2 = None
        org.city = None
        self.assertFalse( org_validator.validate_object( org ) )
        # removing all address properties of a not yet flushed
        # address should expunge the address
        org = party.Organization( name = 'PSF' )
        org.street1 = 'Rue Belliard 1'
        for address in org.addresses:
            self.assertTrue( address in self.session.new )
        org.street1 = None
        self.assertTrue( address not in self.session )
        self.assertEqual( len(org.addresses), 0 )
        
    def test_person( self ):
        person = party.Person( first_name = u'Robin',
                               last_name = u'The brave' )
        self.assertEqual( person.email, None )
        self.assertEqual( person.phone, None )
        self.assertEqual( person.fax, None )
        self.assertEqual( person.street1, None )
        self.assertEqual( person.street2, None )
        self.assertEqual( person.city, None )
        self.person_admin.flush( person )
        person2 = party.Person( first_name = u'Robin' )
        self.assertFalse( person2.note )
        person2.last_name = u'The brave'
        # gui should warn this person exists
        self.assertTrue( person2.note )
        return person
        
    def test_contact_mechanism( self ):
        contact_mechanism = party.ContactMechanism( mechanism = (u'email', u'*****@*****.**') )
        self.assertTrue( unicode( contact_mechanism ) )
        
    def test_person_contact_mechanism( self ):
        # create a new person
        person = party.Person( first_name = u'Robin',
                               last_name = u'The brave' )
        self.person_admin.flush( person )
        self.assertEqual( person.email, None )
        # set the contact mechanism
        mechanism_1 = (u'email', u'*****@*****.**')
        person.email = mechanism_1
        # the default from and thru dates should be set when
        # setting the party defaults
        self.person_admin.set_defaults( person )
        self.assertTrue( person.contact_mechanisms[0].from_date )
        self.person_admin.flush( person )
        self.assertEqual( person.email, mechanism_1 )
        # change the contact mechanism, after a flush
        mechanism_2 = (u'email', u'*****@*****.**')
        person.email = mechanism_2
        self.person_admin.flush( person )
        self.assertEqual( person.email, mechanism_2 )
        # remove the contact mechanism after a flush
        person.email = ('email', '')
        self.assertEqual( person.email, None )
        self.person_admin.flush( person )
        self.assertEqual( person.email, None )
        admin = party.PartyContactMechanismAdmin( self.app_admin, 
                                                  party.PartyContactMechanism )
        contact_mechanism = party.ContactMechanism( mechanism = mechanism_1 )
        party_contact_mechanism = party.PartyContactMechanism( party = person,
                                                               contact_mechanism = contact_mechanism )
        admin.flush( party_contact_mechanism )
        admin.refresh( party_contact_mechanism )
        list( admin.get_depending_objects( party_contact_mechanism ) )
        #
        # if the contact mechanism changes, the party person should be 
        # updated as well
        #
        contact_mechanism_admin = self.app_admin.get_related_admin( party.ContactMechanism )
        depending_objects = list( contact_mechanism_admin.get_depending_objects( contact_mechanism ) )
        self.assertTrue( person in depending_objects )
        self.assertTrue( party_contact_mechanism in depending_objects )
        #
        # if the party contact mechanism changes, the party should be updated
        # as well
        depending_objects = list( admin.get_depending_objects( party_contact_mechanism ) )
        self.assertTrue( person in depending_objects )
        # delete the person
        self.person_admin.delete( person )
        
    def test_organization( self ):
        org = party.Organization( name = 'PSF' )
        org.email = ('email', '*****@*****.**')
        org.phone = ('phone', '1234')
        org.fax = ('fax', '4567')
        self.organization_admin.flush( org )
        self.assertTrue( unicode( org ) )
        self.assertEqual( org.number_of_shares_issued, 0 )
        query = orm.object_session( org ).query( party.Organization )
        self.assertTrue( query.filter( party.Organization.email == ('email', '*****@*****.**') ).first() )
        self.assertTrue( query.filter( party.Organization.phone == ('phone', '1234') ).first() )
        self.assertTrue( query.filter( party.Organization.fax == ('fax', '4567') ).first() )
        return org
    
    def test_party_relationship( self ):
        person = self.test_person()
        org = self.test_organization()
        employee = party.EmployerEmployee( established_from = org,
                                           established_to = person )
        self.assertTrue( unicode( employee ) )
        
    def test_party_contact_mechanism( self ):
        person = self.test_person()
        party_contact_mechanism = party.PartyContactMechanism( party = person )
        party_contact_mechanism.mechanism = (u'email', u'*****@*****.**')
        party_contact_mechanism.mechanism = (u'email', u'*****@*****.**')
        self.assertTrue( party_contact_mechanism in self.session.new )
        self.assertTrue( party_contact_mechanism.contact_mechanism in self.session.new )
        # flushing trough the party should flush the contact mechanism
        self.person_admin.flush( person )
        self.assertFalse( party_contact_mechanism in self.session.new )
        self.assertFalse( party_contact_mechanism.contact_mechanism in self.session.new )        
        self.assertTrue( unicode( party_contact_mechanism ) )
        query = self.session.query( party.PartyContactMechanism )
        self.assertTrue( query.filter( party.PartyContactMechanism.mechanism == (u'email', u'*****@*****.**') ).first() )
        # party contact mechanism is only valid when contact mechanism is
        # valid
        party_contact_mechanism_admin = self.app_admin.get_related_admin( party.PartyContactMechanism )
        compounding_objects = list( party_contact_mechanism_admin.get_compounding_objects( party_contact_mechanism ) )
        self.assertTrue( party_contact_mechanism.contact_mechanism in compounding_objects )
        party_contact_mechanism_validator = party_contact_mechanism_admin.get_validator()
        self.assertFalse( party_contact_mechanism_validator.validate_object( party_contact_mechanism ) )
        party_contact_mechanism.contact_mechanism.mechanism = None
        self.assertTrue( party_contact_mechanism_validator.validate_object( party_contact_mechanism ) )
        # the party is only valid when the contact mechanism is
        # valid
        party_admin = self.app_admin.get_related_admin( party.Person )
        party_validator = party_admin.get_validator()
        self.assertTrue( party_validator.validate_object( person ) )
        
    def test_party_category( self ):
        org = self.test_organization()
        category = party.PartyCategory( name = u'Imortant' )
        category.parties.append( org )
        self.session.flush()
        self.assertTrue( list( category.get_contact_mechanisms( u'email') ) )
        self.assertTrue( unicode( category ) )