Пример #1
0
 def setUp(self):
     self.living_space = LivingSpace("Swift")
     self.office = Office("Scala")
     self.fellow = Fellow("Mike Jon")
     self.fellow2 = Fellow("Lucas Chan", "Y")
     self.staff = Staff("Rick Man")
     self.amity = Amity()
    def load_from_database(self, allocation_db_obj):
        """Load database information to create a new application state
        reset Amity to the new state

        Arguments
            allocation_db_obj: database connection to be use to save data
        """
        persons = allocation_db_obj.get_persons()
        rooms = allocation_db_obj.get_rooms()
        amity = Amity()

        for i in persons:
            person = persons[i]
            if isinstance(person, Fellow):
                livingspace_allocation = person.room_name.get("livingspace")
                office_allocation = person.room_name.get("office")
                if livingspace_allocation:
                    livingspace = rooms[livingspace_allocation]
                    livingspace.add_occupant(person)
                if office_allocation:
                    office = rooms[office_allocation]
                    office.add_occupant(person)
            else:
                office_allocation = person.room_name.get("office")
                if office_allocation:
                    office = rooms[office_allocation]
                    office.add_occupant(person)
            amity.add_person(person)
        for i in rooms:
            amity.add_room(rooms[i])

        # update the amity object
        self.amity = amity
Пример #3
0
 def setUp(self):
     self.amity = Amity()
     self.amity.all_people = []
     self.amity.all_rooms = []
     self.amity.office_allocations = defaultdict(list)
     self.amity.lspace_allocations = defaultdict(list)
     self.amity.fellows_list = []
     self.amity.staff_list = []
Пример #4
0
 def setUp(self):
     self.amity = Amity()
     self.amity.rooms = []
     self.amity.offices = []
     self.amity.living_spaces = []
     self.amity.people = []
     self.amity.fellows = []
     self.amity.staff = []
     self.amity.waiting_list = []
     self.amity.office_waiting_list = []
     self.amity.living_space_waiting_list = []
    def test_personfactor_assigns_ordered_id_to_person_when_created(self):
        person = PersonFactory.create("fellow", "Femi", 25, "M", wants_residence="Y", level="D1")
        Amity.add_object_to_dictionary(person)
        self.assertEqual(person.id, "000001")

        person = PersonFactory.create("fellow", "Bob", 26, "Y", wants_residence="N", level="D4")
        self.assertEqual(person.id, "000002")

        person = PersonFactory.create("staff", "Seni", 50, "M", job_title="Director of Operations", department="Operations")
        self.assertEqual(person.id, "000001")

        person = PersonFactory.create("staff", "Michael", 26, "Y", job_title="Trainer", department="Training")
        self.assertEqual(person.id, "000002")
 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 rellocate_person(self, person_id, new_room_id):
        """Rellocate person to the room specified.

        Raises:
            KeyError

        Arguments
            person_id: Id of person to be rellocated
            new_room_id: room to be relocated to

        """
        try:
            person_obj = self.amity.persons[person_id]
        except KeyError:
            raise KeyError("Invalid Person Id provided")
        try:
            new_room_obj = self.amity.rooms[new_room_id]
        except KeyError:
            raise KeyError("Invalid Room Id provided")
        room_type = Amity.get_room_type(new_room_obj)
        old_room_name = person_obj.room_name.get(room_type)
        try:
            new_room_obj.add_occupant(person_obj)
        except (RoomIsFullError, PersonInRoomError) as err:
            raise err
        else:
            if old_room_name:
                old_room_obj = self.amity.rooms[old_room_name]
                del old_room_obj.occupants[person_obj.identifier]
            person_obj.room_name[room_type] = new_room_obj.get_id()
    def allocate_room(self, person_id, room_dict):
        """Allocate a random room from the supplied room dictionary
           to person of specified id

        Raises:
            KeyError
            PersonInRoomError

        Arguments
            person_id: id pf person object to be allocated to a random room
            room_dict: a dictionary object of type room

        Return:
            boolean: true on successful allocation

        """
        person_obj = self.amity.persons[person_id]
        no_of_rooms = len(room_dict.keys())
        if no_of_rooms < 1:
            raise NoRoomError
        i = 0
        while i <= no_of_rooms:
            i += 1
            room_obj = RoomAllocation.select_random(room_dict)
            if not room_obj.is_full():
                break
            if i == no_of_rooms:
                raise NoRoomError("No free room to allocate Person")
        room_type = Amity.get_room_type(room_obj)
        if person_obj.is_allocated(room_type):
            raise PersonAllocatedError
        else:
            room_obj.add_occupant(person_obj)
            person_obj.room_name[room_type] = room_obj.get_id()
            return True
Пример #9
0
    def do_reallocate(self, args):
        """Usage: reallocate <person_identifier> <new_room_name>
        """

        ID = args['<person_identifier>']
        room_name = args['<new_room_name>'].capitalize()
        print Amity().reallocate(ID, room_name)
Пример #10
0
    def setUp(self):
        self.test_db = "temp"
        self.db = AmityDb(self.test_db)
        self.amity = Amity()

        # Create_rooms
        self.amity.create_room("Snow", "O")
        self.amity.create_room("Scala", "O")
        self.amity.create_room("Shire", "L")
        self.amity.create_room("Swift", "L")

        # Add_people to rooms
        self.amity.add_person("John", "Doe", "Fellow")
        self.amity.add_person("Tom", "Harry", "Fellow", "Y")
        self.amity.add_person("Jim", "Jones", "Staff")
        self.amity.add_person("Guy", "Fawkes", "Staff")
Пример #11
0
    def do_print_allocations(self, args):
        """Usage: print_allocations [<filename>]

        Options:
        -o, filename  Print to file
        """
        filename = args['<filename>'] if args['<filename>'] else None
        Amity().print_allocations(filename)
Пример #12
0
    def do_save_state(self, args):
        """Usage: save_state [--db=sqlite_database]

        Options:
        -d,--db=sqlite_database  Save state to database 
        """
        savefile = args['--db']
        print Amity().save_state(savefile)
Пример #13
0
 def do_create_room(self, args):
     """Usage: create_room <room_type> <room_name>...
     """
     room_names = []
     for room in args["<room_name>"]:
         room = room.capitalize()
         room_names.append(room)
     room_type = args['<room_type>'].lower()
     print Amity().create_room(room_names, room_type)
 def setUp(self):
     self.fellowA = Fellow("Malik Wahab", "M", "Y")
     self.fellowB = Fellow("Ose Oko", "F", "N")
     self.staffA = Staff("Joe Jack", "M")
     self.staffB = Staff("Nengi Adoki", "F")
     self.officeA = Office("Moon")
     self.officeB = Office("Mecury")
     self.livingA = LivingSpace("Spata", "M")
     self.livingB = LivingSpace("Roses", "F")
     self.amity = Amity()
     self.amity.rooms = self.livingB
Пример #15
0
 def do_add_person(self, args):
     """
     Usage: 
     add_person <firstname> <surname> <designation> [<wants_accommodation>]
     """
     firstname = args["<firstname>"].capitalize()
     surname = args['<surname>'].capitalize()
     designation = args['<designation>'].lower()
     resident = args['<wants_accommodation>'].upper(
     ) if args['<wants_accommodation>'] else 'N'
     print Amity().add_person(firstname, surname, designation, resident)
Пример #16
0
class AddPersonTest(unittest.TestCase):
    def setup(self):
        self.amity = Amity()
        self.create_room("valhalla", "office")
        self.create_room("php", "living_space")

    def test_add_person(self):
        """fxn test add persons"""

        self.setup()
        self.assertEqual(len(self.amity.all_people),
                         2,
                         msg="Two People should be added")

    def test_add_staff(self):
        """fxn test add staff"""

        self.setup()
        self.amity.add_person("oliver", "Staff")
        staff = [
            staff for staff in self.amity.all_people
            if staff["job_type"] == "staff"
        ]
        self.assertEqual(len(staff), 1)

    def test_add_fellow(self):
        """fxn test add staff"""

        self.setup()
        self.amity.add_person("hms", "Fellow")
        fellow = [
            fellow for fellow in self.amity.all_people
            if fellow["job_type"] == "fellow"
        ]
        self.assertEqual(len(fellow), 1)

    def test_check_job_type(self):
        """fxn to check job type argument"""

        self.setup()
class TestAmity(unittest.TestCase):
    """docstring for Test"""

    #Create instance of Amity
    def setUp(self):
        self.amity = Amity()

    @patch('app.storage')
    def test_room_creation(self, test_storage):
        test_storage.list_of_all_rooms.return_value = ["CAMELOT", "NARNIA"]
        result = Mock()
        result.room_name.return_value = "HOGWARDS"
        print test_storage.list_of_all_rooms.return_value
        self.result = self.amity.createRoom(result.room_name.return_value)
        print self.amity.room_name
        print test_storage.list_of_all_rooms.return_value

        if self.result != "Room created successfully!!":
            self.assertNotEqual(self.amity.room_name,
                                "",
                                msg="Cannot create empty room")

            self.assertNotIn(self.amity.room_name,
                             test_storage.list_of_all_rooms.return_value,
                             msg="Room with that name already exist.")
            print test_storage.list_of_all_rooms.return_value
        else:
            self.assertIn(self.amity.room_name,
                          test_storage.list_of_all_rooms.return_value,
                          msg="Room with that name already exist.")

    # def test_room_allocation(self):
    # 	self.result = self.amity.allocateRoom("","")

    # 	if self.result != "Room allocation successfully!!":

    # 		self.assertIn(self.amity.jobType.upper(),["FELLOW","STAFF"],msg = "Cannot allocate room to person whom is not STAFF or FELLOW.")

    # 		self.assertNotEqual(self.amity.name,"",msg = "Cannot allocate empty person a room")

    # 		self.assertIn(self.amity.name, self.amity.list_of_unallocated_people, msg = "Person must be in waiting list!!")

    # 		self.assertIn(self.amity.wantsRoom.upper(),["Y","YE","YES","N","NO"], msg = "Use YES or NO to select if you want room allocation")

    def test_load_people(self):
        pass

    def test_save_state(self):
        pass

    def test_load_state(self):
        pass
    def remove_room(self, room_id):
        """Remove a specified room from amity
        render all person in room unallocated

        Arguments
            room_id - id of room to be remove from amity

        """
        room = self.amity.rooms[room_id]
        room_type = Amity.get_room_type(room)
        persons = room.occupants
        for i in persons:
            person = persons[i]
            del person.room_name[room_type]
        del self.amity.rooms[room_id]
    def print_persons(self):
        """Print a list of persons in amity.

        Returns
            String: names and identifier of persons in Amity

        """
        persons = self.amity.persons
        persons_string = "List of Persons with Id\n"
        for i in persons:
            person = persons[i]
            persons_string += (person.name + " " +
                               Amity.get_person_type(person) + " " +
                               person.identifier + "\n")
        return persons_string
    def print_room(self, room_id):
        """Build the string of a room with the persons in it.

        Arguments:
            room_id - id of room to print

        """
        room = self.amity.rooms[room_id]
        room_string = ""
        room_type = Amity.get_room_type(room)
        room_string += "\n--" + room.name + "(" + room_type + ")--\n"
        persons = room.occupants
        for i in persons:
            room_string += self.print_person(persons[i])
        return room_string
    def print_person(self, person_obj):
        """Build a string of person object printing out the name.

        Arguments:
            person_obj - person to printed to file

        Returns:
            string: of the persons name, person_type and accomodation status
        """
        name = person_obj.name.upper()
        want_accomodation = ""
        person_type = Amity.get_person_type(person_obj)
        if person_type == "fellow":
            want_accomodation = person_obj.wants_accom
        return (name + ' ' + person_type.upper() + ' ' +
                want_accomodation + "\n")
Пример #22
0
    def test_executer_can_add_people_to_room(self):
        amity = Amity()

        room = RoomFactory.create("Moon", 4)
        Amity.add_object_to_dictionary(amity, room)
        Amity.modify_dictionary_element(amity, "room", "000001", "purpose", "office")

        person = PersonFactory.create("fellow", "Femi", 25, "M", wants_residence="Y", level="D1")
        Amity.add_object_to_dictionary(amity, person)

        Executor.assign_occupant_to_room(person, room)
        self.assertIn(person.id, room.occupants)
        self.assertEqual(room.occupant_count, 1)
        self.assertEqual(amity.rooms["000001"].occupants, person)
Пример #23
0
    def test_executer_can_add_people_to_room(self):
        amity = Amity()

        room = RoomFactory.create("Moon", 4)
        Amity.add_object_to_dictionary(amity, room)
        Amity.modify_dictionary_element(amity, "room", "000001", "purpose",
                                        "office")

        person = PersonFactory.create("fellow",
                                      "Femi",
                                      25,
                                      "M",
                                      wants_residence="Y",
                                      level="D1")
        Amity.add_object_to_dictionary(amity, person)

        Executor.assign_occupant_to_room(person, room)
        self.assertIn(person.id, room.occupants)
        self.assertEqual(room.occupant_count, 1)
        self.assertEqual(amity.rooms["000001"].occupants, person)
Пример #24
0
 def do_print_unallocated(self, args):
     """Usage: print_unallocated [<filename>]
     """
     filename = args['<filename>'] if args['<filename>'] else None
     Amity().print_unallocated(filename)
class AmitySpaceAllocation(cmd.Cmd):
    f = Figlet(font='slant')
    dojo = Amity()
    # Makes the interface look better
    print(Fore.GREEN + f.renderText('Amity Space Allocation ')).center(10)
    print(Fore.YELLOW + ('Type help to get a list of commands')).center(70)
    print(Fore.YELLOW +
          ('Type a command to get the arguments it requires')).center(70)

    prompt = '(amity) '
    file = None

    @docopt_cmd
    def do_create_room(self, arg):
        """Usage: create_room <room_type> <room_name>..."""
        try:
            room_type = str(arg['<room_type>'])
            room_list = arg['<room_name>']
            if len(room_list) == 1:
                self.dojo.create_room({
                    "room_type": room_type,
                    "room_name": str(room_list[0])
                })
            else:
                self.dojo.create_room({
                    "room_type": room_type,
                    "room_name": room_list
                })
        except TypeError:
            print(colored("The Values shoud be strings"))

    @docopt_cmd
    def do_add_person(self, arg):
        """Usage: add_person <fname> <lname> <role> [<accomodation>]  
        """
        try:
            first_name = str(arg['<fname>'])
            last_name = str(arg['<lname>'])
            role = str(arg['<role>'])
            accomodation = arg['<accomodation>']

        except TypeError:
            print("You have to pass names")
        if accomodation == None:
            wants_accomodation = 'N'
        else:
            wants_accomodation = accomodation
        self.dojo.create_person(first_name, last_name, role,
                                wants_accomodation)

    @docopt_cmd
    def do_load_people(self, arg):
        """Usage: load_people <file_name>
        """
        file_name = arg['<file_name>']
        file_name = file_name + ".txt"
        self.dojo.load_people(file_name)

    @docopt_cmd
    def do_print_allocations(self, arg):
        """Usage: print_allocations [<file_name>]
        """
        file_name = arg['<file_name>']
        if file_name:
            file_name = file_name + ".txt"
            self.dojo.print_allocations(file_name)
        else:
            self.dojo.print_allocations()

    @docopt_cmd
    def do_print_unallocated(self, arg):
        """Usage: print_unallocated [<file_name>]
        """
        file_name = arg['<file_name>']
        if file_name:
            file_name = file_name + ".txt"
            self.dojo.print_unallocated(file_name)
        else:
            self.dojo.print_unallocated()

    @docopt_cmd
    def do_print_room(self, arg):
        """Usage: print_room <room_name>

        """
        room_name = arg['<room_name>']
        self.dojo.print_room(room_name)

    @docopt_cmd
    def do_save_state(self, arg):
        """Usage: save_state [<database_name>]"""

        db_name = arg['<database_name>']
        if db_name:
            self.dojo.save_state(db_name)
        else:
            self.dojo.save_state('amity')

    @docopt_cmd
    def do_load_state(self, arg):
        """Usage: load_state <database_name> 

        """

        db_name = str(arg['<database_name>'])
        self.dojo.load_state(db_name)

    @docopt_cmd
    def do_reallocate(self, arg):
        """Usage: reallocate <id> <room_to> """

        id = arg['<id>']
        room_to = arg["<room_to>"]
        self.dojo.reallocate(id, room_to)

    def do_quit(self, arg):
        """Quits out of Interactive Mode."""
        exit()
Пример #26
0
class AmityApp(cmd.Cmd):
	intro = cprint(figlet_format("Amity Room!!!", font="cosmike"),\
				"yellow")
	prompt = "Amity --> "

	amity = Amity()

	@app_exec
	def do_create_room(self, arg):
		"""Creates a new room
		Usage: create_room <room_name> <room_type>
		"""
		room_name = arg["<room_name>"]
		room_type = arg["<room_type>"]
		self.amity.create_room(room_name, room_type)

	@app_exec
	def do_add_person(self, arg):
		"""
		Adds a person and allocates rooms if available
		Usage: add_person <person_name> <person_description> [--wants_accommodation=N]
		"""
		person_description= arg["<person_description>"]
		wants_accommodation = arg["--wants_accommodation"]
		if wants_accommodation is None:
			wants_accommodation = "N"

		person_name= arg["<person_name>"]
		self.amity.add_person(person_name, person_description, wants_accommodation=wants_accommodation)



	@app_exec
	def do_print_room(self, arg):
		"""
		Prints all the people in a given rooms
		Usage: print_room <room_name>
		"""
		self.amity.print_room(arg["<room_name>"])

	@app_exec
	def do_print_allocations(self, arg):
		"""
		Prints all offices and the people in them.
		Usage: print_allocations [--o=filename]
		"""
		filename = arg["--o"] or ""
		self.amity.print_allocations(filename)

	@app_exec
	def do_print_unallocated(self, arg):
		"""
		Prints all the people that don't have rooms
		Usage: print_unallocated [--o=filename]
		"""
		filename = arg["--o"] or ""
		self.amity.print_unallocated(filename)

	@app_exec
	def do_load_people(self, arg):
		"""
		Loads people from a text file to the app.
		Usage: load_people <filename>
		"""
		self.amity.load_people(arg["<filename>"])
		print("File loaded.")

	@app_exec
	def do_reallocate_person(self, arg):
		"""
		Reallocates person
		Usage: reallocate_person <person_name> <new_room>
		"""
		person_name = arg["<person_name>"]
		new_room = arg["<new_room>"]
		self.amity.reallocate_person(person_name, new_room)

	@app_exec
	def do_load_state(self, arg):

		"""
		Loads data from the specified db into the app.
		Usage: load_state <filename>
		"""
		self.amity.load_state(arg["<filename>"])

	@app_exec
	def do_save_state(self, arg):
		"""
		Persists app data into the given db
		Usage: save_state [--db_name=sqlite_db]
		"""
		db = arg['--db_name']
		if db:
			self.amity.save_state(db)
		else:
			self.amity.save_state()


	@app_exec
	def do_quit(self, arg):
		"""
		Exits the app.
		Usage: quit
		"""
		exit()
 def test_get_person_type_three(self):
     self.assertIsNone(Amity.get_person_type({}))
Пример #28
0
 def Setup(self):
     self.amity = Amity()
Пример #29
0
 def setup(self):
     self.amity = Amity()
     self.create_room("valhalla", "office")
     self.create_room("php", "living_space")
Пример #30
0
    def test_amity_can_add_people_to_room(self):
        amity = Amity()

        room = RoomFactory.create("Moon", 4)
        Amity.add_object_to_dictionary(amity, room)
        Amity.modify_dictionary_element(amity, "room", "000001", "purpose",
                                        "office")

        person1 = PersonFactory.create("fellow",
                                       "Femi",
                                       25,
                                       "M",
                                       wants_residence="Y",
                                       level="D1")
        Amity.add_object_to_dictionary(amity, person1)

        Amity.assign_occupant_to_room(amity, person1, room)

        person2 = PersonFactory.create("staff",
                                       "Bob",
                                       20,
                                       "F",
                                       job_title="Facilitator",
                                       department="Learning and Development")
        Amity.add_object_to_dictionary(amity, person2)

        Amity.assign_occupant_to_room(amity, person2, room)

        self.assertIn(person1.id, room.occupants)
        self.assertIn(person2.id, room.occupants)
        # pdb.set_trace()
        self.assertEqual(room.occupant_count, 2)
        self.assertEqual(amity.rooms["000001"].occupants, {
            '000001': person1,
            '000002': person2
        })
 def setUp(self):
     self.amity = Amity()
Пример #32
0
    def test_amity_can_add_people_to_room(self):
        amity = Amity()

        room = RoomFactory.create("Moon", 4)
        Amity.add_object_to_dictionary(amity, room)
        Amity.modify_dictionary_element(amity, "room", "000001", "purpose", "office")

        person1 = PersonFactory.create("fellow", "Femi", 25, "M", wants_residence="Y", level="D1")
        Amity.add_object_to_dictionary(amity, person1)

        Amity.assign_occupant_to_room(amity, person1, room)

        person2 = PersonFactory.create("staff", "Bob", 20, "F", job_title="Facilitator", department="Learning and Development")
        Amity.add_object_to_dictionary(amity, person2)

        Amity.assign_occupant_to_room(amity, person2, room)

        self.assertIn(person1.id, room.occupants)
        self.assertIn(person2.id, room.occupants)
        # pdb.set_trace()
        self.assertEqual(room.occupant_count, 2)
        self.assertEqual(amity.rooms["000001"].occupants, {'000001': person1, '000002': person2})
Пример #33
0
class TestAmity(unittest.TestCase):
    def setUp(self):
        self.amity = Amity()

    def test_create_room(self):
        '''test to confirm a room has been created'''
        rooms = self.amity.all_rooms
        # making sure the rooms are empty
        self.assertEqual(len(rooms), 0)
        self.amity.create_room('haskel', 'livingspace')
        # checking to see if rooms have been added
        self.assertEqual(len(rooms), 1)

    def test_office_is_created(self):
        '''test to confirm an office is created'''
        office = self.amity.office_rooms
        self.assertEqual(len(office), 0)
        self.amity.create_room('valhalla', 'office')
        self.assertEqual(len(office), 1)

    def test_living_space_is_created(self):
        '''test to confirm that living space is created'''
        livingspace = self.amity.livingspaces
        self.assertEqual(len(livingspace), 0)
        self.amity.create_room('php', 'livingspace')
        self.assertEqual(len(livingspace), 1)

    def test_fellow_is_created(self):
        '''tesst to confirm a fellow is created'''
        self.amity.create_room('valhalla', 'office')
        fellow = self.amity.fellows
        self.assertEqual(len(fellow), 0)
        self.amity.add_person('chironde', 'fellow')
        self.assertEqual(len(fellow), 1)

    def test_staff_is_created(self):
        '''test to confirm staff is created'''
        self.amity.create_room('hogwarts', 'office')
        staff = self.amity.staff
        self.assertEqual(len(staff), 0)
        self.amity.add_person('njira', 'staff')
        self.assertEqual(len(staff), 1)

    def test_people_are_added_to_all_peole_list(self):
        '''test if all people are added to the people list
        regardles wether they are fellows or staff '''
        everyone = self.amity.all_people
        self.assertEqual(len(everyone), 0)
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('njira', 'staff')
        self.amity.add_person('joy', 'fellow', 'Y')
        self.assertEqual(len(everyone), 2)

    def test_person_is_allocated_a_room(self):
        '''test if a person has been reallocated to a specified room'''
        self.amity.create_room('occulus', 'office')
        self.amity.add_person('rehema', 'fellow')
        person = self.amity.fellows[0]
        roomname = person.office.name
        self.assertEqual(roomname, 'occulus')

    def test_a_room_has_a_person(self):
        '''test a that rooms take in people'''
        self.amity.create_room('cyan', 'office')
        self.amity.add_person('jackie', 'fellow')
        office = self.amity.office_rooms[0]
        person = office.members[0]
        person_name = person.name
        self.assertEqual(person_name, 'jackie')

    def test_a_person_has_been_reallocated(self):
        '''test that a person has been reallocated to a different room'''
        self.amity.create_room('mordor', 'office')
        self.amity.add_person('joshua', 'staff')
        staff = self.amity.staff[0]
        office_name = staff.office.name
        self.assertEqual(office_name, 'mordor')
        self.amity.create_room('winterfell', 'office')
        self.amity.reallocate_person('joshua', 'winterfell')
        new_office_name = staff.office.name
        self.assertEqual(new_office_name, 'winterfell')

    def test_a_person_has_been_removed_from_a_room_after_reallocation(self):
        '''test that a person has been removed
        from a room after reallocation'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.add_person('rehema', 'fellow')
        office = self.amity.office_rooms[0]
        members = office.members
        self.assertEqual(len(members), 1)
        self.amity.create_room('Occulus', 'office')
        self.amity.reallocate_person('rehema', 'Occulus')
        office = self.amity.office_rooms[0]
        members = office.members
        self.assertEqual(len(members), 0)

    def test_print_allocations_to_terminal(self):
        '''test that allocated people are printed to the terminal'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.add_person('valt honks', 'fellow', 'Y')
        self.amity.print_allocations(None)

    def test_print_allocations_file(self):
        '''test that allocated people are printed to a file'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.add_person('valt honks', 'fellow', 'Y')
        self.amity.print_allocations('allocations.txt')

    def test_people_without_rooms_are_added_to_unallocated_list(self):
        '''test that people without rooms are added to unallocated list'''
        unallocated = self.amity.unallocated
        self.assertEqual(len(unallocated), 0)
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam gaamwa', 'fellow')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.add_person('tom shitonde', 'fellow', 'Y')
        self.amity.print_un_allocated(None)
        unallocated = self.amity.unallocated
        self.assertEqual(len(unallocated), 2)

    def test_print_unallocated_people_to_terminal(self):
        '''test that unallocated people are printed to a the terminal'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.add_person('valt honks', 'fellow', 'Y')
        self.amity.print_un_allocated(None)

    def test_print_unallocated_people_to_a_file(self):
        '''test that unallocated people are printed to a file'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.add_person('valt honks', 'fellow', 'Y')
        self.amity.print_un_allocated('unallocated.txt')

    def test_members_of_a_room_are_printed(self):
        '''test that members of a room are printed'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam gaamwa', 'fellow')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.print_room('hogwarts')

    def test_people_are_added_to_allocated_(self):
        '''test that alloacted people are added to a list'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        allocated = self.amity.allocated
        self.assertEqual(len(allocated), 0)
        self.amity.add_person('sam gaamwa', 'fellow')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.print_allocations(None)
        self.assertEqual(len(allocated), 3)

    def test_fellow_are_allocated_to_allocated_list(self):
        '''test that an allocated staff is added to allocated list'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'fellow')
        self.amity.print_allocations(None)
        allocated = self.amity.allocated
        fellow = allocated[0]
        self.assertIsInstance(fellow, Fellow)

    def test_fellow_are_allocated_to_unallocated_list(self):
        '''test that the person in an unallocated list is a fellow'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        self.amity.add_person('sam maina', 'fellow')
        self.amity.print_un_allocated(None)
        unallocated = self.amity.unallocated
        fellow = unallocated[0]
        self.assertIsInstance(fellow, Fellow)

    def test_unalloacted_people_are_added_to_unallocated_list(self):
        '''test that fellows without living space are added to a list'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        unallocated = self.amity.unallocated
        self.assertEqual(len(unallocated), 0)
        self.amity.add_person('sam gaamwa', 'fellow')
        self.amity.add_person('sam maina', 'staff')
        self.amity.add_person('tom wilkins', 'fellow')
        self.amity.print_un_allocated(None)
        self.assertEqual(len(unallocated), 2)

    def test_load_people_from_file(self):
        '''test that people are added from a list and given a room'''
        self.amity.create_room('hogwarts', 'office')
        self.amity.create_room('php', 'livingspace')
        staff_list = self.amity.staff
        fellows_list = self.amity.fellows
        self.assertEqual(len(staff_list), 0)
        self.assertEqual(len(fellows_list), 0)
        self.amity.load_people("test_people.txt")
        self.assertEqual(len(staff_list), 3)
        self.assertEqual(len(fellows_list), 4)
Пример #34
0
class ClassAmitySuccessTest(unittest.TestCase):
    def setUp(self):
        self.amity = Amity()
        self.amity.all_people = []
        self.amity.all_rooms = []
        self.amity.office_allocations = defaultdict(list)
        self.amity.lspace_allocations = defaultdict(list)
        self.amity.fellows_list = []
        self.amity.staff_list = []

    def test_add_person(self):
        self.amity.add_person("awesome", "fellow", "y")
        self.assertEqual(len(self.amity.all_people), 1)

    def test_add_person_failure(self):
        self.amity.add_person("angie", "staff")
        people_names = [people.person_name for people in self.amity.all_people]
        self.assertIn("angie", people_names)
        msg = self.amity.add_person("angie", "staff")
        self.assertEqual(
            msg, "sorry, this user already exists.please choose another name")

    def test_room_added_to_list(self):
        self.amity.create_room("purple", "office")
        self.assertEqual(len(self.amity.all_rooms), 1)

    def test_room_with_same_name_not_created(self):
        self.amity.create_room("purple", "office")
        r_names = [r.room_name for r in self.amity.all_rooms]
        self.assertIn("purple", r_names)
        msg = self.amity.create_room("purple", "office")
        self.assertEqual(
            msg, "sorry, room already exists!please choose another name")

    def test_office_allocation(self):
        self.amity.add_person("Angie", "Staff", "Y")
        for room, occupants in self.amity.office_allocations:
            self.assertIn("Angie", self.amity.office_allocations[occupants])

    def test_lspace_allocation(self):
        self.amity.add_person("Angie", "fellow", "Y")
        for room, occupants in self.amity.lspace_allocations:
            self.assertIn("Angie", self.amity.lspace_allocations[occupants])

    def test_reallocate_person(self):
        self.amity.create_room("blue", "office")
        self.amity.add_person("angie", "staff")
        print(self.amity.office_allocations)
        self.amity.reallocate_person("angie", "blue")
        self.assertIn("angie", self.amity.office_allocations["blue"])

    def test_person_is_removed_from_old_room(self):
        self.amity.create_room("blue", "office")
        self.amity.add_person("angie", "staff")
        self.assertIn("angie", self.amity.office_allocations["blue"])
        self.amity.create_room("yellow", "office")
        self.amity.reallocate_person("angie", "yellow")
        self.assertNotIn("angie", self.amity.office_allocations["blue"])

    def test_load_from_file(self):
        dirname = os.path.dirname(os.path.realpath(__file__))
        self.amity.load_people(os.path.join(dirname, "test.txt"))
        self.assertEqual(len(self.amity.fellows_list), 4)
        self.assertEqual(len(self.amity.staff_list), 3)

    def test_it_prints_unallocated(self):
        self.amity.print_unallocated('test_print')
        self.assertTrue(os.path.isfile('test_print.txt'))
        os.remove('test_print.txt')

    def test_it_saves_state(self):
        self.amity.save_state('test.db')
        self.assertTrue(os.path.isfile('test.db.db'))
        os.remove('test.db.db')
 def test_get_person_type(self):
     self.assertEqual(Amity.get_person_type(self.fellowA), 'fellow')
 def test_get_person_type_two(self):
     self.assertEqual(Amity.get_person_type(self.staffB), 'staff')
Пример #37
0
 def do_print_room(self, args):
     """Usage: print_room <room_name>
     """
     room_name = args['<room_name>'].capitalize()
     Amity().print_room(room_name)
Пример #38
0
 def do_load_people(self, args):
     """Usage: load_people <doc>
     """
     doc = args['<doc>']
     print Amity().load_people(doc)
Пример #39
0
class AmityModelTests(unittest.TestCase):
    def setUp(self):
        """Set up Amity ()"""
        self.amity = Amity()

    def tearDown(self):
        del self.amity

    def test_create_office(self):
        '''tests it creates office'''
        new_office = self.amity.create_room("office", "medical")
        self.assertEqual(new_office, "MEDICAL office created successfully")

    def test_create_living_space(self):
        '''tests it creates living space'''
        new_living_space = self.amity.create_room("Livingspace", "Mara")
        self.assertEqual(new_living_space,
                         "MARA living space created successfully")

    def test_wrong_room_type(self):
        '''tests error message if wrong room type is put'''
        new_wrong_room_type = self.amity.create_room("Something Wrong",
                                                     "Wrong Room")
        self.assertEqual(new_wrong_room_type,
                         "invalid entry. Please enter office or living space")

    def test_staff_cannot_be_allocated_living_space(self):
        staff_to_living = self.amity.add_person("Kevin", "Kamau", "Staff", "Y")
        self.assertEqual(staff_to_living,
                         "Staff cannot be allocated Living Space")

    def test_wrong_designation(self):
        person_wrong_des = self.amity.add_person("Evalyn", "Kyalo", "Watchman")
        self.assertEqual(person_wrong_des,
                         "Incorrect entry. Please enter staff or fellow")

    def test_reallocate_person(self):
        self.amity.create_room("Office", "Jamuhuri")
        self.amity.add_person("James", "Kabue", "Staff")
        self.amity.create_room("Office", "Madaraka")
        test_reallocate = self.amity.reallocate_person("James", "Kabue",
                                                       "Madaraka")
        self.assertEqual(test_reallocate,
                         "JAMES KABUE reallocated to MADARAKA office")

    def test_reallocate_to_the_same_room(self):
        self.amity.create_room("Office", "Bagdad")
        self.amity.add_person("Alex", "Simanzi", "Staff")
        test_reallocate = self.amity.reallocate_person("Alex", "Simanzi",
                                                       "Bagdad")
        self.assertEqual(test_reallocate, "Cannot reallocate to the same room")

    def test_reallocate_to_the_non_existent_room(self):
        self.amity.create_room("Office", "Bagdad")
        self.amity.add_person("Alex", "Simanzi", "Staff")
        test_reallocate = self.amity.reallocate_person("Alex", "Simanzi",
                                                       "Israel")
        self.assertEqual(test_reallocate, "Room does not exist")
Пример #40
0
 def do_load_state(self, args):
     """Usage: load_state <load_file> 
     """
     load_file = args['<load_file>']
     print Amity().load_state(load_file)
 def test_get_room_type(self):
     self.assertEqual(Amity.get_room_type(self.livingA), 'livingspace')
Пример #42
0
 def setUp(self):
     """Set up Amity ()"""
     self.amity = Amity()
 def test_get_room_type_two(self):
     self.assertEqual(Amity.get_room_type(self.officeA), 'office')
Пример #44
0
class AmityTestCase(unittest.TestCase):
    """Test cases for Amity class"""
    def setUp(self):
        self.living_space = LivingSpace("Swift")
        self.office = Office("Scala")
        self.fellow = Fellow("Mike Jon")
        self.fellow2 = Fellow("Lucas Chan", "Y")
        self.staff = Staff("Rick Man")
        self.amity = Amity()

    def test_rooms_are_added_successfully(self):
        """Tests offices of living spaces are created"""

        self.amity.create_room("Scala", "O")
        self.amity.create_room("Go", "L")
        self.assertEqual(len(self.amity.list_of_rooms), 2)

    def test_office_is_created_successfully(self):
        """Tests offices are created"""

        office = self.amity.create_room("Office", "O")
        self.assertIsInstance(office, Office)

    def test_living_space_is_created_successfully(self):
        """Tests living_spaces are created"""

        l_space = self.amity.create_room("Keja", "L")
        self.assertIsInstance(l_space, LivingSpace)

    def test_living_space_does_not_exceed_four_people(self):
        """Tests living space does not exceed capacity"""

        self.amity.list_of_rooms.append(self.living_space)
        self.living_space.occupants = ["Tom", "Dick", "Harry", "Johny"]
        self.amity.allocate_room(self.fellow, "Y")
        self.assertEqual(len(self.amity.unallocated_members), 1)
        self.assertEqual(len(self.living_space.occupants), 4)

    def test_office_does_not_exceed_six_people(self):
        """Tests office does not exceed capacity"""

        self.amity.list_of_rooms.append(self.office)
        self.office.occupants = [
            "alpha", "beta", "charlie", "delta", "echo", "foxtrot"
        ]
        self.amity.allocate_room(self.staff, "N")
        self.assertEqual(len(self.amity.unallocated_members), 1)
        self.assertEqual(len(self.office.occupants), 6)

    def test_staff_is_not_allocated_living_space(self):
        """Tests staff members can only be in offices"""

        self.amity.list_of_rooms.append(self.living_space)
        self.amity.allocate_room(self.staff, "N")
        self.assertEqual(len(self.amity.list_of_rooms[0].occupants), 0)
        self.assertEqual(len(self.amity.unallocated_members), 1)

    def test_duplicate_rooms_are_not_added(self):
        """Tests rooms with same name are not allowed"""

        self.amity.list_of_rooms.append(self.living_space)
        self.assertEqual(self.amity.create_room("Swift", "L"),
                         "Room already exists")

    def test_fellow_gets_office_by_default(self):
        """Tests fellow is created and allocated room"""

        self.amity.list_of_rooms.append(self.office)
        self.amity.add_person("Tom", "Riley", "Fellow")
        self.assertTrue(self.amity.list_of_rooms[0].occupants[0].person_name ==
                        "Tom Riley".upper())

    def test_staff_member_is_added_successfully(self):
        """Tests staff member is created and allocated room"""

        self.amity.list_of_rooms.append(self.office)
        self.amity.add_person("Rick", "James", "Staff")
        self.assertEqual(len(self.amity.allocated_members), 1)

    def test_people_are_loaded_from_file_successfully(self):
        """Tests ii accepts data from file"""

        with patch("builtins.open", mock_open(read_data="sample text")) as m:
            self.amity.load_people("file")

        m.assert_called_with("file", 'r')

    def test_for_invalid_person_role(self):
        """Tests invalid person role is not allowed"""

        res = self.amity.add_person("Guy", "Ross", "Invalid")
        self.assertEqual(res, "Invalid is not a valid person role")

    def test_members_are_added_to_waiting_list_if_no_rooms(self):
        """Tests unallocated people are added to waiting list"""

        self.amity.add_person("Roomless", "Man", "Fellow", "Y")
        self.amity.add_person("Roomless", "Woman", "Staff")
        self.amity.add_person("Random", "Person", "Fellow")
        self.assertEqual(len(self.amity.unallocated_members), 3)

    def test_members_are_added_to_waiting_list_if_rooms_full(self):
        """Tests members who miss rooms are added to waiting list"""

        self.living_space.occupants += ["one", "two", "three", "four"]
        self.office.occupants += ["one", "two", "three", "four", "five", "six"]
        self.amity.add_person("Molly", "Sue", "Fellow", "Y")
        self.amity.add_person("Ledley", "Moore", "Staff")
        self.assertEqual(len(self.amity.unallocated_members), 2)

    def test_fellow_gets_office_and_living_space_if_wants_room(self):
        """Tests fellow who wants accomodation gets a living space"""

        self.amity.list_of_rooms.append(self.living_space)
        self.amity.list_of_rooms.append(self.office)
        self.amity.add_person("Martin", "Luther", "Fellow", "Y")
        self.assertTrue(self.amity.allocated_members[0].person_name ==
                        "Martin Luther".upper())
        self.assertEqual(self.amity.list_of_rooms[0].occupants[0].person_name,
                         "MARTIN LUTHER")
        self.assertEqual(self.amity.list_of_rooms[1].occupants[0].person_name,
                         "MARTIN LUTHER")

    def test_cannot_reallocate_non_existent_person(self):
        """Tests members not allocated cannot be reallocated"""

        self.amity.list_of_rooms.append(self.living_space)
        res = self.amity.reallocate_person("No Name", "Swift")
        self.assertEqual(res, "Person not found")

    def test_cannot_reallocate_non_existent_room(self):
        """Tests reallocation only allows valid rooms"""

        self.amity.allocated_members.append(self.staff)
        res = self.amity.reallocate_person("Rick Man", "Inexistent")
        self.assertEqual(res, "Room not found")

    def test_cannot_reallocate_to_same_room(self):
        """
        Tests person cannot be reallocated to
        the same room
        """

        self.amity.list_of_rooms.append(self.office)
        self.amity.list_of_rooms[0].occupants.append(self.fellow)
        self.amity.allocated_members.append(self.fellow)
        res = self.amity.reallocate_person("Mike Jon", "Scala")
        self.assertEqual(res, "Person is already in room")

    def test_cannot_reallocate_staff_to_living_space(self):
        """Tests staff cannot be reallocated to livingspace"""

        self.amity.list_of_rooms += [self.office, self.living_space]
        self.amity.allocated_members.append(self.staff)
        self.amity.list_of_rooms[0].occupants.append(self.staff)
        res = self.amity.reallocate_person("Rick Man", "Swift")
        self.assertEqual(res, "Staff cannot be allocated living space")

    def test_cannot_reallocate_person_to_full_room(self):
        """Tests person cannot be reallocated a full room"""

        self.amity.list_of_rooms.append(self.living_space)
        self.amity.add_person("Fellow", "One", "Fellow", "Y")
        self.amity.add_person("Fellow", "Two", "Fellow", "Y")
        self.amity.add_person("Fellow", "Three", "Fellow", "Y")
        self.amity.add_person("Fellow", "Four", "Fellow", "Y")
        self.amity.list_of_rooms.append(self.office)
        self.amity.allocated_members.append(self.fellow)
        res = self.amity.reallocate_person("Mike Jon", "Swift")
        self.assertEqual(res, "Room is full")

    def test_person_is_reallocated_successfully(self):
        """Tests reallocate person works"""

        self.amity.list_of_rooms += [self.office, self.living_space]
        self.amity.allocated_members.append(self.fellow)
        self.amity.list_of_rooms[0].occupants.append(self.fellow)
        self.amity.reallocate_person("Mike Jon", "Swift")
        # Assert the person is transfered to new room
        self.assertEqual(self.amity.list_of_rooms[1].occupants[0].person_name,
                         "Mike Jon")
        # Assert the person is removed from former room
        self.assertTrue(len(self.amity.list_of_rooms[0].occupants) == 0)

    def test_cannot_print_inexistent_room(self):
        """
        Tests print_room raises alert if there
        are no occupants
        """

        res = self.amity.print_room("None")
        self.assertEqual(res, "Room does not exist")

    def test_print_room_works(self):
        """
        Tests print room returns
        the names of occupants
        """

        self.amity.list_of_rooms.append(self.office)
        self.amity.list_of_rooms[0].occupants += \
            [self.fellow, self.fellow2, self.staff]

        res = self.amity.print_room("Scala")
        self.assertEqual(res, "Print room successful")

    def test_print_allocations_raises_alert_if_no_rooms(self):
        """Tests alert is raised if no allocations available"""

        self.assertEqual(self.amity.print_allocations(None), "No rooms")

    def test_print_allocations_to_screen_works(self):
        """Tests allocations are printed to screen"""

        self.amity.list_of_rooms += [self.office, self.living_space]
        self.amity.add_person("Carla", "Bruni", "Staff")
        self.amity.add_person("Peter", "Pan", "Fellow")
        self.amity.add_person("Mike", "Ross", "Fellow", "Y")
        self.amity.add_person("Hype", "Mann", "Fellow")
        res = self.amity.print_allocations(None)
        self.assertEqual(res, "Print allocations successful")

    def test_allocations_are_written_to_file(self):
        """Tests if allocations are saved to file"""

        self.amity.list_of_rooms += [self.office, self.living_space]
        self.amity.allocated_members += [self.staff, self.fellow, self.fellow2]
        self.amity.list_of_rooms[0].occupants.append(self.staff)
        self.amity.list_of_rooms[0].occupants.append(self.fellow)
        self.amity.list_of_rooms[0].occupants.append(self.fellow2)
        self.amity.list_of_rooms[1].occupants.append(self.fellow2)

        m = mock_open()
        with patch('builtins.open', m):
            self.amity.print_allocations("file")
        m.assert_called_with("file", 'w')

    def test_print_unallocated_people_works(self):
        """Tests unallocated people are printed to screen"""

        self.amity.unallocated_members += [
            self.fellow, self.fellow2, self.staff
        ]
        res = self.amity.print_unallocated(None)
        self.assertEqual(res, "Print unallocations successful")

    def test_it_prints_unallocated_people_to_file(self):
        """Tests if unallocated people are saved to file"""

        self.amity.unallocated_members += [
            self.staff, self.fellow, self.fellow2
        ]

        m = mock_open()
        with patch('builtins.open', m):
            self.amity.print_unallocated("file")
        m.assert_called_with("file", 'w')

    def test_load_state_from_invalid_path_raises_error(self):
        """Tests load state does not accept invalid path"""

        res = self.amity.load_people("invalid path")
        self.assertEqual(res, "Error. File not found")

    def test_cannot_save_blank_data_to_db(self):
        """Tests blank data is not saved to db"""

        res = self.amity.save_state(None)
        self.assertEqual(res, "No data")

    def tearDown(self):
        del self.living_space
        del self.office
        del self.fellow
        del self.fellow2
        del self.staff
        del self.amity
Пример #45
0
class TestAmity(unittest.TestCase):
    '''
    This class tests all the funtionality of the amity famility allocation
    system. It has only focussed on the amity module since the class amity
    interacts with all the other modules and performs all the logical
    functioning of the application
    '''
    def setUp(self):
        self.amity = Amity()

    def test_returns_error_if_input_is_nonalphabetical(self):
        self.assertIn('123 is an invalid name type!',
                      self.amity.create_room(['123'], 'office'))

    def test_create_room(self):
        self.amity.create_room(["Pink"], "office")
        self.amity.create_room(['Blue'], 'livingspace')
        self.assertIn("Pink", Room.rooms['office'])
        self.assertIn('Blue', Room.rooms['livingspace'])

    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_correct_message_room_creation(self):
        res = self.amity.create_room(["Pink"], "office")
        self.assertIn('There are 1 offices and 0 livingspaces in the system.',
                      res)
        self.assertIn('Enter a valid room type.(office|livingspace)',
                      self.amity.create_room(["Orange"], "ofice"))

    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_create_room_increments_rooms_by_one(self):
        self.assertEqual(len(Room.rooms['office']), 0)
        self.amity.create_room(["Orange"], "office")
        self.assertEqual(len(Room.rooms['office']), 1)

    @patch.dict('app.room.Room.rooms', {
        "office": {
            'Yellow': []
        },
        "livingspace": {}
    })
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_create_room_duplicate_rooms(self):
        self.assertIn('A room with that name exists. Select another name',
                      self.amity.create_room(['Yellow'], 'office'))

    ''' This section tests the functionality of adding a person to the
    system, allocation of rooms and reallocation of a person from one room
    to another'''

    def test_only_alphabetical_names_allowed(self):
        self.assertIn('Invalid name format. Alphabets only',
                      self.amity.add_person('1234', 'Menjo', 'fellow'))
        self.assertIn('Invalid name format. Alphabets only',
                      self.amity.add_person('Menjo', '1234', 'fellow'))

    def test_restriction_on_job_designation(self):
        self.assertIn('Enter a valid designation',
                      self.amity.add_person('Charlie', 'Kip', 'worker'))

    def test_restriction_on_residence(self):
        self.assertIn('Respond with Y or N for residence',
                      self.amity.add_person('Charlie', 'Kip', 'fellow', 'R'))

    def test_new_person_gets_ID(self):
        self.amity.add_person('Mary', 'Chepkoech', 'staff')
        self.assertIn('ST01', Person.people['staff'])
        self.amity.add_person('Kevin', 'Leo', 'fellow', 'Y')
        self.assertIn('FE01', Person.people['fellow'])

    @patch.dict(
        'app.room.Room.rooms', {
            "office": {
                'Yellow': {
                    "Room_name": 'Yellow',
                    "Max_occupants": 6,
                    "Total_occupants": 0,
                    "Occupants": []
                }
            },
            "livingspace": {}
        })
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 1)
    @patch.object(Amity, "livingspaces", 0)
    def test_add_person_adds_person_to_lists(self):
        self.amity.add_person('Mary', 'Chepkoech', 'staff')
        self.amity.add_person('Kevin', 'Leo', 'fellow', 'Y')
        self.assertIn('Mary Chepkoech', Person.people['staff']['ST01']['Name'])
        self.assertIn('Kevin Leo', Person.people['fellow']['FE01']['Name'])

    @patch.dict(
        'app.room.Room.rooms', {
            "office": {
                'Brown': {
                    "Room_name": 'Brown',
                    "Max_occupants": 6,
                    "Total_occupants": 0,
                    "Occupants": []
                }
            },
            "livingspace": {
                'Beige': {
                    "Room_name": 'Beige',
                    "Max_occupants": 4,
                    "Total_occupants": 0,
                    "Occupants": []
                }
            }
        })
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 1)
    @patch.object(Amity, "livingspaces", 1)
    def test_person_is_allocated_room_after_creation(self):
        self.amity.add_person('Sophie', 'Njeri', 'fellow', 'Y')
        self.assertIn('FE01', Room.rooms['office']['Brown']['Occupants'])
        self.assertIn('FE01', Room.rooms['livingspace']['Beige']['Occupants'])

    def test_reallocate_person(self):
        self.amity.create_room(['Brown'], 'office')
        self.amity.create_room(['Beige'], 'livingspace')
        self.amity.add_person('Sophie', 'Njeri', 'fellow', 'Y')
        self.amity.create_room(["Orange"], "office")
        self.amity.reallocate('FE01', 'Orange')
        self.assertIn('FE01', Room.rooms['office']['Orange']['Occupants'])

    @patch.dict(
        'app.room.Room.rooms', {
            "office": {
                'Brown': {
                    "Room_name": 'Brown',
                    "Max_occupants": 6,
                    "Total_occupants": 0,
                    "Occupants": []
                }
            },
            "livingspace": {
                'Beige': {
                    "Room_name": 'Beige',
                    "Max_occupants": 4,
                    "Total_occupants": 0,
                    "Occupants": []
                }
            }
        })
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 1)
    @patch.object(Amity, "livingspaces", 1)
    def test_reallocation_to_nonexistent_room(self):
        self.amity.add_person('Sophie', 'Njeri', 'fellow', 'Y')
        self.assertIn('No such room exists',
                      self.amity.reallocate('FE01', 'Orange'))

    # Tests the print_room functionality
    def test_print_room_nonexistent_room(self):
        self.assertIn('No such room exists', self.amity.print_room('Orange'))

    def test_print_room_with_no_occupants(self):
        self.amity.create_room(['Brown'], 'office')
        self.assertEqual(self.amity.print_room('Brown'), 'No occupants.')

    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_print_room_with_occupants(self):
        self.amity.create_room(['Brown'], 'office')
        self.amity.add_person('Sophie', 'Njeri', 'fellow')
        self.assertIn('FE01 Sophie Njeri', self.amity.print_room('Brown'))

    # Tests the printing of unallocated persons
    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    @patch.object(Amity, "unallocated_people", [])
    def test_empty_unallocated(self):
        self.assertEqual(self.amity.print_unallocated(),
                         'There are no unallocated people')

    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_unallocated_with_entries(self):
        self.amity.add_person('Sophie', 'Njeri', 'fellow')
        self.assertIn('Sophie Njeri', self.amity.print_unallocated())

    # Tests for the print allocations begin here
    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    def test_print_allocations_with_no_rooms(self):
        self.assertEqual(self.amity.print_allocations(),
                         'There are no rooms in the system at the moment.')

    @patch.dict('app.room.Room.rooms', {"office": {}, "livingspace": {}})
    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    @patch.dict(
        'app.room.Room.rooms', {
            "office": {
                'Brown': {
                    "Room_name": 'Brown',
                    "Max_occupants": 6,
                    "Total_occupants": 0,
                    "Occupants": ['ST01']
                }
            },
            "livingspace": {}
        })
    @patch.dict(
        'app.person.Person.people', {
            "staff": {
                'ST01': {
                    'Name': 'Mary Chepkoech',
                    'Resident': 'N'
                }
            },
            "fellow": {}
        })
    @patch.object(Amity, "offices", 1)
    @patch.object(Amity, "livingspaces", 0)
    def test_print_allocations_with_occupants_in_rooms(self):
        res = self.amity.print_allocations()
        self.assertIn('ST01 Mary Chepkoech', res['off_occupants'])

    # Tests for the load people method begins here

    @patch.dict('app.person.Person.people', {"staff": {}, "fellow": {}})
    def test_load_people(self):
        if os.path.exists('app'):
            os.chdir('app')
        self.amity.load_people('test.txt')
        assert (Person.people['staff'] > 1)

    # Tests for the database
    def test_save_state(self):
        if os.path.exists('app'):
            os.chdir('app')
        self.assertEqual(self.amity.save_state('savefile.db'),
                         'The current data has been saved to the database.')

    @patch.object(Room, "rooms", {"office": {}, "livingspace": {}})
    @patch.object(Person, "people", {"staff": {}, "fellow": {}})
    @patch.object(Amity, "offices", 0)
    @patch.object(Amity, "livingspaces", 0)
    @patch.object(Amity, "available_rooms", [])
    @patch.object(Amity, "unallocated_people", [])
    def test_load_state(self):
        if os.path.exists('app'):
            os.chdir('app')
        self.assertEqual(
            self.amity.load_state('new_infile.db'),
            "Data has been successfully loaded from the database.")
 def test_get_room_type_thee(self):
     self.assertIsNone(Amity.get_room_type({}))
class TestAmity(unittest.TestCase):

    def setUp(self):
        self.fellowA = Fellow("Malik Wahab", "M", "Y")
        self.fellowB = Fellow("Ose Oko", "F", "N")
        self.staffA = Staff("Joe Jack", "M")
        self.staffB = Staff("Nengi Adoki", "F")
        self.officeA = Office("Moon")
        self.officeB = Office("Mecury")
        self.livingA = LivingSpace("Spata", "M")
        self.livingB = LivingSpace("Roses", "F")
        self.amity = Amity()
        self.amity.rooms = self.livingB

    def test_init(self):
        amity = Amity()
        self.assertEqual(amity.rooms, {})

    def test_add_room(self):
        self.amity.rooms = self.livingA
        self.assertIn("spata", self.amity.rooms)

    def test_add_room_two(self):
        with self.assertRaises(TypeError):
            self.amity.rooms = "spata"

    def test_ad_room_two(self):
        with self.assertRaises(SameNameRoomError):
            self.amity.add_room(self.livingB)

    def test_get_rooms(self):
        self.amity.rooms = self.livingA
        room_dict = {'roses': self.livingB, 'spata': self.livingA}
        self.assertEqual(self.amity.rooms, room_dict)

    def test_get_persons_two(self):
        self.amity.persons = self.fellowA
        self.amity.persons = self.staffA
        self.amity.persons = self.fellowB
        self.amity.persons = self.staffB
        self.assertIn(self.staffB.identifier, self.amity.persons)

    def test_get_person(self):
        self.amity.add_person(self.fellowA)
        self.assertEqual(self.amity.persons[self.fellowA.identifier],
                         self.fellowA)

    def test_get_offices(self):
        self.amity.rooms = self.officeA
        self.amity.rooms = self.officeB
        self.amity.rooms = self.livingA
        office_dict = {"moon": self.officeA, "mecury": self.officeB}
        self.assertEqual(office_dict, self.amity.get_offices())

    def test_get_livingspaces(self):
        self.amity.rooms = self.officeA
        self.amity.rooms = self.officeB
        self.amity.rooms = self.livingA
        living_dict = {"spata": self.livingA}
        self.assertEqual(living_dict, self.amity.get_livingspaces("M"))

    def test_get_all_livingspaces(self):
        self.amity.rooms = self.officeA
        self.amity.rooms = self.officeB
        self.amity.rooms = self.livingA
        living_dict = {"spata": self.livingA, "roses": self.livingB}
        self.assertEqual(living_dict, self.amity.get_livingspaces())

    def test_add_person(self):
        self.amity.persons = self.fellowA
        self.assertIn(self.fellowA.identifier, self.amity.persons)

    def test_add_person_two(self):
        with self.assertRaises(TypeError):
            self.amity.persons = "malik wahab"

    def test_get_room_type(self):
        self.assertEqual(Amity.get_room_type(self.livingA), 'livingspace')

    def test_get_room_type_two(self):
        self.assertEqual(Amity.get_room_type(self.officeA), 'office')

    def test_get_room_type_thee(self):
        self.assertIsNone(Amity.get_room_type({}))

    def test_get_person_type(self):
        self.assertEqual(Amity.get_person_type(self.fellowA), 'fellow')

    def test_get_person_type_two(self):
        self.assertEqual(Amity.get_person_type(self.staffB), 'staff')

    def test_get_person_type_three(self):
        self.assertIsNone(Amity.get_person_type({}))
Пример #48
0
        except SystemExit:
            # The SystemExit exception prints the usage for --help
            # We do not need to do the print here.

            return

        return func(self, opt)

    fn.__name__ = func.__name__
    fn.__doc__ = func.__doc__
    fn.__dict__.update(func.__dict__)
    return fn


amity = Amity()


class MyInteractive (cmd.Cmd):
    intro = 'Welcome to my amity space allocation program!' \
        + ' (type help for a list of commands.)'
    prompt = '(Amity Space Allocation) '
    file = None

    @docopt_cmd
    def do_create_room(self, args):
        """Usage: create_room <room_type> (<room_names>)..."""
        room_type = args["<room_type>"]
        room_names = args["<room_names>"]
        for room_name in room_names:
            amity.create_room(room_type, room_name)
Пример #49
0
class AmityTestCase(unittest.TestCase):
    """ Tests for amity """
    def setUp(self):
        self.amity = Amity()
        self.amity.rooms = []
        self.amity.offices = []
        self.amity.living_spaces = []
        self.amity.people = []
        self.amity.fellows = []
        self.amity.staff = []
        self.amity.waiting_list = []
        self.amity.office_waiting_list = []
        self.amity.living_space_waiting_list = []

    # ... Tests for create_room ...#

    def test_create_room_add_room_successfully(self):
        """ Test that room was created successfully """
        self.amity.create_room(["Hogwarts"], "office")
        self.assertEqual("Hogwarts", self.amity.rooms[0].room_name)

    def test_create_room_duplicates(self):
        """ Test that room can only be added once """
        self.amity.create_room(["Hogwarts"], "office")
        self.assertIn("Hogwarts", [i.room_name for i in self.amity.rooms])
        length_of_rooms = len(self.amity.rooms)
        self.amity.create_room(["Hogwarts"], "office")
        self.assertEqual(len(self.amity.rooms), length_of_rooms)

    # ... Tests for add_person ...#

    def test_add_person_add_fellow(self):
        """ Test that fellow was added successfully """
        self.amity.create_room(["BlueRoom"], "Office")
        person = self.amity.add_person("Robley", "Gori", "fellow", "N")
        p_id = self.amity.people[0].person_id
        self.assertIn(
            "Robley Gori of id " + str(p_id) + " has been added to "
            "the system", person)

    def test_add_person_add_staff(self):
        """ Test that staff was added successfully """

        self.amity.create_room(["Maathai"], "LivingSpace")
        person = self.amity.add_person("Robley", "Gori", "fellow", "Y")
        p_id = self.amity.people[0].person_id
        self.assertIn(
            "Robley Gori of id " + str(p_id) + " has been added to "
            "the system", person)

    def test_add_person_add_person_to_office(self):
        """ Test that person is successfully added to office """

        self.amity.create_room(["red"], "Office")
        self.amity.add_person("Jack", "Line", "staff", "N")
        person = self.amity.add_person("Robley", "Gori", "fellow", "N")
        self.assertIn("", person)

    def test_add_person_add_fellow_to_living_space(self):
        """ Test that fellow is successfully added to living space """
        self.amity.create_room(["blue"], "Office")
        self.amity.add_person("Jack", "Line", "staff", "N")
        person = self.amity.add_person("Robley", "Gori", "fellow", "N")
        self.assertIn("", person)

    def test_add_person_add_staff_to_living_space(self):
        """ Test that staff cannot be added to living space """
        self.amity.create_room(["Maathai"], "LivingSpace")
        person = self.amity.add_person("Robley", "Gori", "staff", "Y")
        self.assertIn("Staff cannot be allocated a living space!", person)

    def test_add_person_add_person_full_office(self):
        """ Test that person is added to waiting list if offices are full """
        self.amity.create_room(["PinkRoom"], "Office")
        self.amity.load_people("people.txt")

        person = self.amity.add_person("Jackline", "Maina", "Fellow", "Y")
        self.assertIn(
            "Jackline Maina has been added to the office waiting "
            "list", person)

    def test_add_person_add_fellow_full_living_space(self):
        """ Test that fellow is added to waiting list if living spaces are \
        full """
        self.amity.create_room(["Maathai"], "LivingSpace")
        self.amity.add_person("Flevian", "Kanaiza", "Fellow", "Y")
        self.amity.add_person("Robley", "Gori", "Fellow", "Y")
        self.amity.add_person("Jus", "Machungwa", "Fellow", "Y")
        self.amity.add_person("Angela", "Mutava", "Fellow", "Y")
        person = self.amity.add_person("Jackline", "Maina", "Fellow", "Y")
        self.assertIn(
            "Jackline Maina has been added to the living space "
            "waiting list", person)

    # ... Tests for reallocate person ...#

    def test_reallocate_person_reallocates_person(self):
        """ Tests that person is reallocated """
        self.amity.create_room(["PinkRoom"], "Office")
        self.amity.add_person("Robley", "Gori", "fellow", "N")
        p_id = self.amity.people[0].person_id
        person = self.amity.reallocate_person(p_id, "ConferenceCentre")
        self.assertIn(
            "Sorry. Room ConferenceCentre does not exist in the "
            "system.", person)

    # ... Tests for load people ...#

    def test_load_people_loads_people_from_txt_file(self):
        """ Tests that people are successfully loaded from a txt file """
        self.amity.load_people("people.txt")
        self.assertTrue("Data successfully loaded to amity!")

    # ... Tests for print allocations ...#

    def test_print_allocations_prints_allocations_to_screen(self):
        """To test if method prints allocations to screen."""
        self.amity.create_room(["red"], "office")
        self.amity.load_people("people.txt")
        self.amity.print_allocations()
        self.assertTrue("These are the rooms and there allocations")

    def test_print_allocations_prints_allocations_to_txt_file(self):
        """To test if method prints allocations to txt file."""
        self.amity.create_room(["red"], "office")
        self.amity.load_people("people.txt")
        self.amity.print_allocations("files/allocations.txt")
        self.assertTrue("Data has been dumped to file")

    # ... Tests for unallocated rooms ...#

    def test_print_unallocated_prints_unallocated_people_to_screen(self):
        """To test if method prints unallocated people to screen."""
        self.amity.load_people("people.txt")
        self.amity.load_people("people.txt")
        self.amity.print_unallocated()
        self.assertTrue("These are the people in the waiting list")

    def test_print_unallocated_prints_unallocated_people_to_txt_file(self):
        """To test if method prints unallocated people to txt file."""
        self.amity.load_people("people.txt")
        self.amity.print_unallocated("files/unallocated.txt")
        self.assertTrue("Data has been dumped to file")

    # ... Tests for print room ...#

    def test_print_room_prints_all_people_in_room_name_to_screen(self):
        """ It tests that all people in a room name are printed to screen """
        self.amity.create_room(["red"], "office")
        self.amity.load_people("people.txt")
        self.amity.print_room("red")
        self.assertTrue("red")

    # ... Tests for save state ...#

    def test_save_state_adds_data_to_database(self):
        """ Test to affirm that data from the application is successfully \
        added to the database """
        self.amity.save_state()
        self.assertTrue("Data successfully saved to database!")

    # ... Tests for load state ...#

    def test_load_state_successfully_loads_data_from_database(self):
        """ Test that data is successfully loaded from database """
        self.amity.save_state("amity.db")
        self.assertTrue("Data successfully loaded to amity!")