def setUp(self):
     amity_obj = Amity()
     self.personA = Fellow("Malik Wahab", "M", "Y")
     self.personB = Staff("Joe Jack", "M")
     amity_obj.persons = self.personA
     amity_obj.persons = self.personB
     self.roomallocation = RoomAllocation(amity_obj)
     self.livingA = LivingSpace("Spata", "M")
     self.officeB = Office("Trafford")
     self.officeA = Office("Mars")
     self.roomallocation.create_room(self.livingA)
     self.roomallocation.create_room(self.officeA)
     self.roomallocation.create_room(self.officeB)
class Test(unittest.TestCase):
    def setUp(self):
        self.office = Office()

    def test_office_is_not_full(self):
        result = self.office.isFull()
        self.assertEqual(result, False, msg="The office is now full")
    def __init__(self, Room_name="", Room_type=""):
        self.Room_name = Room_name
        self.Room_type = Room_type

        #Create a variable that holds the instance of the room type created.

        if self.Room_type == "OFFICE":
            self.Room_instance = Office(self.Room_name)

            Storage.total_no_of_rooms += 6
            #Increment number of total room spaces by 4 for every office created.
        elif self.Room_type == "LIVINGSPACE":
            self.Room_instance = LivingSpace(self.Room_name)

            Storage.total_no_of_rooms += 4
            #Increment number of total room spaces by 6 for every living space created.

        else:
            #Do nothing if room is neither office or livingspace
            self.Room_instance = LivingSpace(self.Room_name)
            Storage.total_no_of_rooms += 4
Beispiel #4
0
 def create_room(self, room_name, room_type):
     """A method for creating new rooms of one of 2 types (Office or Living Space) in the Dojo"""
     if type(room_name) == str and type(room_type) == str:
         if room_name in list(self.all_rooms.keys()):
             return ' A room called {} already exists!\n'.format(room_name)
         else:
             if room_type.lower().strip() == 'office':
                 new_office = Office(room_name)
                 self.total_number_of_rooms += 1
                 self.number_of_offices += 1
                 self.office_spaces[room_name] = new_office
                 self.all_rooms[room_name] = new_office
                 return ' An office called ' + room_name + ' has been successfully created!'
             elif room_type.lower().strip() == 'living space':
                 new_living_space = LivingSpace(room_name)
                 self.total_number_of_rooms += 1
                 self.number_of_living_spaces += 1
                 self.living_spaces[room_name] = new_living_space
                 self.all_rooms[room_name] = new_living_space
                 return ' A living space called ' + room_name + ' has been successfully created!'
             else:
                 return ' Enter a valid room type!'
     else:
         raise TypeError(' Arguments must both be strings')
Beispiel #5
0
 def setUp(self):
     self.office = Office('Blue')
     self.staff1 = Staff('Will')
Beispiel #6
0
class OfficeTest(unittest.TestCase):
    def setUp(self):
        self.office = Office('Blue')
        self.staff1 = Staff('Will')

    def test_office_has_max_capacity_six(self):
        self.assertEqual(self.office.capacity, 6)

    def test_office_properties(self):
        self.assertEqual(self.office.name, 'Blue')
        self.assertEqual(self.office.type, 'Office')

    def test_no_members_yet(self):
        self.assertEqual(len(self.office.members), 0)

    def test_assert_office_is_not_full(self):
        self.assertFalse(self.office.is_full())
        self.assertTrue(self.office.is_empty())

    def test_office_can_accept_person_objects(self):
        self.office.add_person(self.staff1)
        self.assertFalse(self.office.is_empty())
        self.assertFalse(self.office.is_full())
        self.assertEqual(self.office.available_spaces(), 5)

    def test_office_can_fill_up(self):
        self.office.add_person(Staff('Atukwase Sylvestre'))
        self.office.add_person(Staff('Murungi Patricia'))
        self.office.add_person(Fellow('Patience Mukami', True))
        self.office.add_person(Staff('Irene Mulyagonja'))
        self.office.add_person(Staff('Annie Myles'))
        self.office.add_person(Staff('John Katureebe'))
        self.office.add_person(Staff('George Williams'))

        self.assertEqual(len(self.office.members), 6)
        self.assertTrue(self.office.is_full())

    def test_add_person_in_available_room(self):
        response = self.office.add_person(Fellow('Kadongo Moses'))
        self.assertTrue(response)
class TestRoomAllocation(unittest.TestCase):

    def setUp(self):
        amity_obj = Amity()
        self.personA = Fellow("Malik Wahab", "M", "Y")
        self.personB = Staff("Joe Jack", "M")
        amity_obj.persons = self.personA
        amity_obj.persons = self.personB
        self.roomallocation = RoomAllocation(amity_obj)
        self.livingA = LivingSpace("Spata", "M")
        self.officeB = Office("Trafford")
        self.officeA = Office("Mars")
        self.roomallocation.create_room(self.livingA)
        self.roomallocation.create_room(self.officeA)
        self.roomallocation.create_room(self.officeB)

    def test_create_room(self):
        self.roomallocation.create_room(self.livingA)
        self.assertIn("spata", self.roomallocation.amity.rooms)

    def test_create_person(self):
        fellow = Fellow("Jose Morinho", "M", "Y")
        self.roomallocation.create_person(fellow)
        self.assertTrue(fellow.is_allocated("livingspace"))

    def test_creat_person_two(self):
        self.roomallocation.remove_room(self.officeA.get_id())
        self.roomallocation.remove_room(self.officeB.get_id())
        status = self.roomallocation.create_person(self.personB)
        self.assertFalse(status[0])

    def test_create_person_two(self):
        fellow = Fellow("Jose Morinho", "M", "Y")
        self.roomallocation.create_person(fellow)
        self.assertTrue(fellow.is_allocated("office"))

    def test_allocate_office(self):
        self.roomallocation.allocate_office(self.personB.identifier)
        self.assertTrue(self.personB.is_allocated("office"))

    def test_allocate_office_two(self):
        self.roomallocation.allocate_office(self.personB.identifier)
        self.assertIn(self.personB.room_name["office"], ['mars', 'trafford'])

    def test_allocate_livingspace(self):
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        self.assertTrue(self.personA.is_allocated("livingspace"))

    def test_allocate_livingspace_two(self):
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        self.assertIn(self.personA.identifier, self.livingA.occupants)

    def test_allocate_livingspace_three(self):
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        self.assertEqual("spata", self.personA.room_name["livingspace"])

    def test_allocate_livingspace_four(self):
        with self.assertRaises(KeyError):
            self.roomallocation.allocate_livingspace("ahmed")

    def test_allocate_room(self):
        with self.assertRaises(NoRoomError):
            self.roomallocation.allocate_room(self.personA.identifier, {})

    def test_allocate_room_two(self):
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        with self.assertRaises(PersonAllocatedError):
            self.roomallocation.allocate_room(self.personA.identifier,
                                              {'spata': self.livingA})

    def test_rellocate_person(self):
        livingB = LivingSpace("Black", "M")
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        self.roomallocation.allocate_office(self.personA.identifier)
        self.roomallocation.create_room(livingB)
        self.roomallocation.rellocate_person(self.personA.identifier,
                                             livingB.get_id())
        self.assertEqual("black", self.personA.room_name["livingspace"])

    def test_rellocate_person_four(self):
        with self.assertRaises(KeyError):
            self.roomallocation.rellocate_person(self.personA.identifier, 'om')

    def test_rellocate_person_three(self):
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        self.roomallocation.allocate_office(self.personA.identifier)
        with self.assertRaises(PersonInRoomError):
            self.roomallocation.rellocate_person(self.personA.identifier,
            self.personA.room_name["office"])

    def test_rellocate_person_two(self):
        with self.assertRaises(KeyError):
            self.roomallocation.rellocate_person("malik", 'spata')

    def test_remove_person(self):
        person_id = self.personA.identifier
        self.roomallocation.remove_person(person_id)
        self.assertIsNone(self.roomallocation.amity.persons.get(person_id))

    def test_remove_person_two(self):
        person_id = self.personA.identifier
        self.roomallocation.allocate_office(self.personA.identifier)
        self.roomallocation.allocate_livingspace(self.personA.identifier)
        room = self.roomallocation.amity \
            .rooms[self.personA.room_name["office"]]
        self.roomallocation.remove_person(person_id)
        self.assertNotIn(person_id, room.occupants)

    def test_remove_person_three(self):
        with self.assertRaises(KeyError):
            self.roomallocation.remove_person('invalidname')

    def test_remove_room(self):
        room_id = self.livingA.get_id()
        self.roomallocation.remove_room(room_id)
        self.assertIsNone(self.roomallocation.amity.rooms.get(room_id))

    def test_remove_room_two(self):
        room_id = self.livingA.get_id()
        occupants = self.livingA.get_occupants()
        self.roomallocation.remove_room(room_id)
        for i in occupants:
            occupant = occupants[i]
            self.assertEqual(9, occupant.get_allocation("livingspace"))

    def test_remove_room_three(self):
        with self.assertRaises(KeyError):
            self.roomallocation.remove_room('notthere')

    def test_load_persons_from_text(self):
        status = self.roomallocation.load_persons_from_text('names.txt')
        self.assertNotEqual([], status)

    def test_select_random(self):
        a_dict = {"one": 1, "two": 2, "three": 3, "four": 4}
        random = self.roomallocation.select_random(a_dict)
        self.assertIn(random, a_dict.values())

    def test_get_unallocated(self):
        fellow1 = Fellow("Jose Morinho", "M", "Y")
        fellow2 = Fellow("Wayne Rooney", "M", "Y")
        fellow3 = Fellow("Rio Fedinand", "M", "Y")
        fellow4 = Fellow("Micheal Carrick", "M", "Y")
        fellow5 = Fellow("David Degea", "M", "Y")
        fellow6 = Fellow("Steve Maccoy", "M", "Y")
        fellow7 = Fellow("Steve Jobs", "M", "Y")
        self.roomallocation.create_person(fellow1)
        self.roomallocation.create_person(fellow2)
        self.roomallocation.create_person(fellow3)
        self.roomallocation.create_person(fellow4)
        self.roomallocation.create_person(fellow5)
        self.roomallocation.create_person(fellow6)
        try:
            self.roomallocation.create_person(fellow7)
        except NoRoomError:
            pass
        self.assertIn(fellow7, self.roomallocation.rmprint.
                      get_unallocated()[1].values())

    def test_get_unallocated_two(self):
        fellow1 = Fellow("Jose Morinho", "M", "Y")
        self.roomallocation.create_person(fellow1)
        office_id = fellow1.room_name.get('office')
        self.roomallocation.remove_room(office_id)
        self.assertIn(fellow1, self.roomallocation.rmprint.
                      get_unallocated()[0].values())

    def test_print_persons(self):
        del self.roomallocation.amity.persons[self.personB.identifier]
        persons_string = self.roomallocation.rmprint.print_persons()
        expected_string = "List of Persons with Id\n"
        expected_string += (self.personA.name + " fellow " +
                            self.personA.identifier + "\n")
        self.assertEqual(persons_string, expected_string)

    def test_print_person(self):
        person_string = self.roomallocation.rmprint.print_person(self.personA)
        expected_string = "MALIK WAHAB FELLOW Y\n"
        self.assertEqual(person_string, expected_string)

    def test_print_person_two(self):
        person_string = self.roomallocation.rmprint.print_person(self.personB)
        expected_string = "JOE JACK STAFF \n"
        self.assertEqual(person_string, expected_string)

    def test_print_room(self):
        self.livingA.add_occupant(self.personA)
        room_string = self.roomallocation.rmprint.print_room(self.livingA.get_id())
        expected_string = "\n--Spata(livingspace)--\n"
        expected_string += "MALIK WAHAB FELLOW Y\n"
        self.assertEqual(room_string, expected_string)

    def test_build_allocation_string(self):
        allocation_string = self.roomallocation.rmprint.build_allocation_string()
        rooms = self.roomallocation.amity.rooms
        expected_string = ""
        for room_id in rooms:
            expected_string += self.roomallocation.rmprint.print_room(room_id)
        self.assertEqual(allocation_string, expected_string)

    def test_build_unallocated_string(self):
        self.roomallocation.remove_person(self.personB.identifier)
        unallocated_string = self.roomallocation.rmprint.build_unallocation_string()
        expected_string = "\n--Unallocated for Office-- \n"
        expected_string += "MALIK WAHAB FELLOW Y\n"
        expected_string += "\n--Unallocated for LivingSpace-- \n"
        expected_string += "MALIK WAHAB FELLOW Y\n"
        self.assertEqual(unallocated_string, expected_string)

    def test_print_allocation_to_file(self):
        self.roomallocation.rmprint.print_allocation_to_file("test/test" +
                                                     "_allocation_to_file.txt")
        rooms = self.roomallocation.amity.rooms
        expected_string = ""
        for room_id in rooms:
            expected_string += self.roomallocation.rmprint.print_room(room_id)
        allocation_string_from_file = ""
        with open("test/test_allocation_to_file.txt", 'r') as allocation_line:
            allocation_string_from_file += allocation_line.read()
        os.remove("test/test_allocation_to_file.txt")
        self.assertEqual(allocation_string_from_file, expected_string)

    def test_print_unallocated_to_file(self):
        self.roomallocation.remove_person(self.personB.identifier)
        self.roomallocation.rmprint \
            .print_unallocated_to_file('test/test_unallocated_to_file.txt')
        expected_string = "\n--Unallocated for Office-- \n"
        expected_string += "MALIK WAHAB FELLOW Y\n"
        expected_string += "\n--Unallocated for LivingSpace-- \n"
        expected_string += "MALIK WAHAB FELLOW Y\n"
        with open("test/test_unallocated_to_file.txt", 'r') as allocation_line:
            unallocated_string_from_file = allocation_line.read()
        os.remove('test/test_unallocated_to_file.txt')
        self.assertEqual(expected_string, unallocated_string_from_file)

    def test_save_to_database(self):
        db = AllocationDb('test/test_save.db')
        self.roomallocation.save_to_database(db)
        rooms = db.get_rooms()
        os.remove('test/test_save.db')
        self.assertIn('spata', rooms)

    def test_save_to_database_two(self):
        db = AllocationDb('test/test_save.db')
        self.roomallocation.save_to_database(db)
        persons = db.get_persons()
        os.remove('test/test_save.db')
        self.assertIn(self.personA.identifier, persons)

    def test_load_from_database(self):
        db = AllocationDb('test/test_save.db')
        fellow = Fellow("Jose Morinho", "M", "Y")
        staff = Staff("Alex Fergie", "M")
        self.roomallocation.create_person(fellow)
        self.roomallocation.create_person(staff)
        self.roomallocation.save_to_database(db)
        del self.roomallocation.amity.persons[self.personA.identifier]
        self.roomallocation.remove_room('spata')
        self.roomallocation.load_from_database(db)
        self.assertIn(self.personA.identifier,
                      self.roomallocation.amity.persons)
Beispiel #8
0
 def __init__(self):
     self.engine = ''
     self.fellow = Fellow()
     self.staff = Staff()
     self.living_space = LivingSpace()
     self.office = Office()
Beispiel #9
0
class Amity(object):

    def __init__(self):
        self.engine = ''
        self.fellow = Fellow()
        self.staff = Staff()
        self.living_space = LivingSpace()
        self.office = Office()

    def connect_db(self, db_name=None):
        if db_name is not None:
            name = 'sqlite:///' + db_name[:db_name.index('.')] + '.db'
        else:
            name = 'sqlite:///amity.db'
        # db_name = db_name[:db_name.index('.')] or 'amity'
        # return create_engine(db_name+'.db')
        return create_engine(name)

    def create_tables(self):
        engine = self.connect_db()

        # check if the tables exist then drop them all if they exist
        if engine.dialect.has_table(engine.connect(), "user"):
            User.__table__.drop(engine)
        if engine.dialect.has_table(engine.connect(), "room"):
            Room.__table__.drop(engine)

        Base.metadata.create_all(engine)

    def load_state(self):
        '''copy data from the database to the application'''
        engine = self.connect_db()

        print("Please Wait... This may take some few minutes.")
        # do something
        Session = sessionmaker(bind=engine)
        Session.configure(bind=engine)
        session = Session()

        print("\tReading data from the database")
        # populate the various lists and dicts
        self.retrieve_data_from_db(session)

        session.commit()
        session.flush()

        print("Load State successfully completed")

    def retrieve_data_from_db(self, session):
        query_room = session.query(Room).all()
        query_user = session.query(User).all()
        fellows = [
            user.person_name for user in query_user
            if user.type_person == 'fellow']
        staffs = [
            user.person_name for user in query_user
            if user.type_person == 'staff']

        offices = {}
        livingspaces = {}
        query_room = session.query(Room).all()
        for room in query_room:
            livingspace_occupants = []
            office_occupants = []
            if room.room_type.lower() == 'office':
                office_occupants.append(room.occupant1)
                office_occupants.append(room.occupant2)
                office_occupants.append(room.occupant3)
                office_occupants.append(room.occupant4)
                office_occupants.append(room.occupant5)
                office_occupants.append(room.occupant6)
                # remove all '' entries
                office_occupants = [
                    ocupant for ocupant in office_occupants if ocupant != '']

                offices[room.room_name] = office_occupants

            else:
                livingspace_occupants.append(room.occupant1)
                livingspace_occupants.append(room.occupant2)
                livingspace_occupants.append(room.occupant3)
                livingspace_occupants.append(room.occupant4)

                # remove all '' entries
                livingspace_occupants = [
                    ocupant for ocupant in livingspace_occupants
                    if ocupant != '']
                livingspaces[room.room_name] = livingspace_occupants
        # load data from db
        text = self.fellow.load_fellows(fellows)
        text = text + '\n%s' % self.staff.load_staffs(staffs)
        text = text + \
            '\n%s' % self.living_space.load_livingspaces(livingspaces)
        text = text + '\n%s' % self.office.load_offices(offices)

        print(text)

    def save_state(self, db=None):
        engine = self.connect_db(db)
        print("Please Wait... This may take some few minutes.")
        self.create_tables()

        Session = sessionmaker(bind=engine)
        Session.configure(bind=engine)
        session = Session()

        print("\tInitiating database population....")
        # populate table users
        # populate table rooms
        self.order_data_ready_for_saving(session)
        print("\tFinalizing database population....")

        session.commit()
        session.flush()
        print("Save State successfully completed.")

    def order_data_ready_for_saving(self, session):
        people = []
        people.extend(list(Fellow.fellow_names))
        people.extend(list(Staff.staff_names))
        ordered_users = []
        for person in people:
            if person is not None and person != 'None':
                user = User()
                user.person_name = person
                if person in list(Fellow.fellow_names):
                    user.type_person = 'fellow'
                elif person in list(Staff.staff_names):
                    user.type_person = 'staff'
                ordered_users.append(user)

        session.add_all(ordered_users)

        Total_rooms = {}
        Total_rooms.update(Office.office_n_occupants)
        Total_rooms.update(LivingSpace.room_n_occupants)
        ordered_rooms = []
        for key, value in list(Total_rooms.items()):
            room = Room()
            room.room_name = key
            room.occupant1 = '' if len(value) < 1 else value[0]
            room.occupant2 = '' if len(value) < 2 else value[1]
            room.occupant3 = '' if len(value) < 3 else value[2]
            room.occupant4 = '' if len(value) < 4 else value[3]
            if room.room_name in LivingSpace.room_n_occupants:
                room.room_type = 'livingspace'
            else:
                room.room_type = 'office'
                room.occupant5 = '' if len(value) < 5 else value[4]
                room.occupant6 = '' if len(value) < 6 else value[5]
            ordered_rooms.append(room)

        session.add_all(ordered_rooms)

    def load_people(self, filename='people.txt'):
        '''loads people into the database'''
        with open(filename, 'r') as input_file:
            people = input_file.readlines()
            data = []
            for persn in people:
                persn = persn.split(' ')
                if persn:
                    wants_accomodation = 'n'
                    person_name = persn[0]
                    if 'STAFF' in persn:
                        type_person = 'staff'
                    else:
                        type_person = 'fellow'

                    if len(persn) > 2:
                        ps = persn[2]
                        if '\n' in ps:
                            wants_accomodation = ps[:ps.index('\n')].lower()
                        else:
                            wants_accomodation = ps.lower()

                    arg_dict = {
                        "person_name": person_name,
                        "type_person": type_person,
                        "wants_accomodation": wants_accomodation
                    }
                data.append(arg_dict)
        for entry in data:
            ret_val = Person().add_person(
                person_name=entry["person_name"],
                type_person=entry["type_person"],
                want_accomodation=entry["wants_accomodation"])
            if ret_val == 'None':
                print ('No Rooms Available')
            else:
                print(ret_val)

    def get_allocations(self, filename=None):
        '''Display allocated rooms and print to a file if a file is provided'''
        allocated_offices = self.compute_rooms(
            Office.office_n_occupants, 'allocated')
        allocated_livingSpaces = self.compute_rooms(
            LivingSpace.room_n_occupants, 'allocated')

        response_offices = 'No File Saved'
        response_livingspaces = 'No File Saved'
        if filename is not None:
            response_offices = Amity().print_file(
                filename, 'RnO-Office', allocated_offices)
            response_livingspaces = Amity().print_file(
                filename, 'RnO-Livin', allocated_livingSpaces)

        if type(allocated_offices) and type(allocated_livingSpaces) is dict:
            allocated_offices.update(allocated_livingSpaces)
        return [allocated_offices, response_offices, response_livingspaces]

    def get_unallocated(self, filename=None):
        '''Display unallocated rooms and print to a file
          if filename is provided'''
        allocated_offices = self.compute_rooms(
            Office.office_n_occupants, 'unallocated')
        allocated_livingSpaces = self.compute_rooms(
            LivingSpace.room_n_occupants, 'unallocated')

        response_office = 'No File Saved'
        response_livingspaces = 'No File Saved'
        if filename is not None:
            response_office = Amity().print_file(
                filename, 'Empty-Office', allocated_offices)
            response_livingspaces = Amity().print_file(
                filename, 'Empty-Livin', allocated_livingSpaces)

        if type(allocated_offices) and type(allocated_livingSpaces) is list:
            allocated_offices.extend(allocated_livingSpaces)
        return [allocated_offices, response_office, response_livingspaces]

    def compute_rooms(self, rooms, return_type):
        '''Compute allocated rooms and unallocated rooms'''
        allocated = {key: value for key,
                     value in rooms.items() if len(value) > 0}
        unallocated = [key for key, value in rooms.items() if len(value) < 1]

        if return_type == 'allocated':
            return allocated
        return unallocated

    def get_all_unallocated_people(self, filename=None):
        fellows = list(Fellow.fellow_names)
        staff = list(Staff.staff_names)

        occupants = []
        for key, value in LivingSpace.room_n_occupants.items():
            occupants.extend(value)

        for key, value in Office.office_n_occupants.items():
            occupants.extend(value)

        set_occupants = set(occupants)
        fellow_occupants = set(fellows) - set_occupants
        staff_occupants = set(staff) - set_occupants

        response_fellows = 'No File Saved'
        response_staff = 'No File Saved'
        if filename is not None:
            response_fellows = Amity().print_file(
                filename, 'unallo_fellows', fellow_occupants)
            response_staff = Amity().print_file(
                filename, 'unallo_staff', staff_occupants)

        return [fellow_occupants, response_fellows,
                staff_occupants, response_staff]

    def print_file(self, filename, type, data):
        '''Assign .txt extension'''
        filename = filename + '-' + type + '.txt'
        try:
            with open(filename, 'w') as file:
                temp = ''
                if 'RnO' in type:
                    # Print room names and Occupants dict
                    for key, value in data.items():
                        temp = 'Room Name: ' + key + \
                            '  Occupants:' + str(value) + \
                            '\n\r'
                        file.write(temp)
                elif 'Empty' in type:
                    # Print empty rooms list
                    temp = 'Empty Rooms:' + str(data) + '\n\r'
                    file.write(temp)
                elif 'unallo_' in type:
                    temp = 'Unallocated people\n' + str(data)
                    file.write(temp)
                file.close()
                return '"' + filename + '"" successfully saved'
        except:
            return 'Failed to save ' + filename + ' successfully.'
 def setUp(self):
     self.office = Office()