class AmityTestPrintAllocations(unittest.TestCase):
    """This class contains tests for the print_allocations function"""
    def setUp(self):
        "Setup for class initializations"
        self.amity = Amity()

    def test_if_office_exists_before_its_printing_members(self):
        """ Tests if there are existing offices before printing the office
			members """
        self.assertEqual(self.amity.print_allocations('test_file'),
                         'No offices in the system')

    def test_if_filename_contains_unwanted_characters(self):
        """ Tests if the filename contains unwanted characters """
        self.assertEqual(self.amity.print_allocations('test/<>file'), False)
예제 #2
0
class TestAmity(unittest.TestCase):
    """ Test amity """
    def setUp(self):
        self.amity = Amity()
        self.offices = self.amity.offices
        self.living_spaces = self.amity.living_spaces
        self.fellows = self.amity.fellows
        self.staff = self.amity.staff
        self.new_offices = self.amity.create_room("O", "Occulus", "Narnia")
        self.new_living_space = self.amity.create_room("L", 'mombasa')
        self.new_fellow = self.amity.add_person("hum", "musonye", "fellow", "Y")
        self.new_staff = self.amity.add_person("hum", "musonye", "staff", "N")
        self.unallocated_fellows = self.amity.unallocated_fellow
        self.unallocated_staff = self.amity.unallocated_staff

    def test_create_living_space(self):
        """ Tests whether a livingspace(room) is created. """
        initial_room_count = len(self.living_spaces)
        self.amity.create_room("L", 'php')
        new_room_count = len(self.living_spaces)

        self.assertEqual(new_room_count, initial_room_count + 1)

    def test_create_office(self):
        """ Tests whether an office(room) is created. """
        initial_room_count = len(self.offices)
        self.amity.create_room("O", "Camelot")
        new_room_count = len(self.offices)

        self.assertEqual(new_room_count, initial_room_count + 1)

    def test_create_multiple_rooms(self):
        """ Tests whether multiple rooms can be created. """
        initial_room_count = len(self.living_spaces)
        self.amity.create_room("L", "Scalar", "Laravel")
        new_room_count = len(self.living_spaces)

        self.assertEqual(new_room_count, initial_room_count + 2)

    def test_room_already_exists(self):
        """ Test behaiviour of create room, when you create an already existing room """
        self.new_living_space
        msg = self.amity.create_room("L", "mombasa")

        self.assertEqual("Room Already Exists!", msg)

    def test_invalid_room_type(self):
        """ Tests whether message is return when invalid room type param is passed"""
        new_room = self.amity.create_room("S", "Laravel")
        self.assertEqual(new_room, "Inavlid Room Type!")

    def test_vacant_rooms_returned(self):
        """ Tests whether rooms that have remaining slots are returned. """
        new_room = Office('mombasa')
        self.amity.check_vacant_rooms()
        vacant_status = new_room.is_full()

        self.assertFalse(vacant_status)

    def test_is_full_returns_true(self):
        """ Tests whether the system knows when a room is fully occupied. """
        new_room = Office('mombasa')
        new_room.occupants.append(136648)
        new_room.occupants.append(136650)
        new_room.occupants.append(136651)
        new_room.occupants.append(136652)
        new_room.occupants.append(136653)
        new_room.occupants.append(136654)
        vacant_status = new_room.is_full()

        self.assertTrue(vacant_status)

    def test_is_full_returns_false(self):
        """ Tests whether the system knows when a room is not fully occupied. """
        new_room = Office('mombasa')
        new_room.occupants.append(136648)
        new_room.occupants.append(136650)
        new_room.occupants.append(136651)
        vacant_status = new_room.is_full()

        self.assertFalse(vacant_status)

    def test_add_fellow(self):
        """ Tests if a fellow is added successfully added. """
        new_fellow = self.new_fellow

        self.assertEqual("Person Created Successfully!", new_fellow)

    def test_add_staff(self):
        """ Tests if a staff is added successfully added """
        new_staff = self.new_staff

        self.assertEqual("Person Created Successfully!", new_staff)

    def test_new_fellow_in_unallocated(self):
        """ Tests whether a newly created fellow is saved to the unallocated list. """
        unallocated_status = True if len(self.unallocated_fellows) > 0 else False

        self.assertTrue(unallocated_status)

    def test_new_staff_in_unallocated(self):
        """ Tests whether a newly created staff is saved to the unallocated list. """
        unallocated_status = True if len(self.unallocated_staff) > 0 else False

        self.assertTrue(unallocated_status)

    def test_allocate_staff(self):
        """ Tests whether a new staff member is allocated an office. """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))
        unallocated_length = len(self.unallocated_staff)

        self.assertEqual(0, unallocated_length)

    def test_allocate_fellow(self):
        """ Tests whether a new fellow is allocated an office and livingspace. """
        fellow = self.fellows[-1]
        self.amity.allocate_person(str(fellow.employee_id))
        unallocated_length = len(self.unallocated_fellows)

        self.assertEqual(0, unallocated_length)

    def test_if_person_not_found(self):
        """ Tests whether a non-existent person can be allocated a room. """
        non_existent_person = 1000001
        allocated_status = self.amity.allocate_person(str(non_existent_person))

        self.assertEqual("Person not found!", allocated_status)

    def test_if_livingspaces_not_found(self):
        """ Test whether allocate_person works when no living_spaces are created. """
        fellow = self.fellows[-1]
        self.amity.living_spaces = []
        allocated_msg = self.amity.allocate_person(str(fellow.employee_id))

        self.assertIn("LivingSpace not available!", allocated_msg)

    def test_if_offices_not_found(self):
        """ Test whether allocate_person works when no offices are created. """
        fellow = self.fellows[-1]
        self.amity.offices = []
        allocated_msg = self.amity.allocate_person(str(fellow.employee_id))

        self.assertIn("Office not available!", allocated_msg)

    def test_when_staff_wants_lspace(self):
        """
        Tests whether the system returns an error message when
        Staff wants_accomodation = Y
        """
        self.amity.add_person("alexis", "sanchez", "staff", "Y")
        staff = self.staff[-1]
        allocated_msg = self.amity.allocate_person(str(staff.employee_id))

        self.assertIn("Cannot assign LivingSpace to staff!", allocated_msg)

    def test_reallocate_if_person_not_found(self):
        """ Tests whether a non-existent person can be reallocated to a room. """
        non_existent_person = 1000001
        allocated_status = self.amity.reallocate_person(str(non_existent_person), 'mombasa')

        self.assertEqual("Person not found", allocated_status)

    def test_if_new_room_name_exists(self):
        """ Test whether reallocate_person finds new_room_name. """
        fellow = self.fellows[-1]
        self.amity.allocate_person(str(fellow.employee_id))
        reallocated_status = self.amity.reallocate_person(str(fellow.employee_id), 'mogadishu')

        self.assertEqual("Room does not Exist!", reallocated_status)

    def test_reallocate_lspace(self):
        """ Test whether a person can be reallocated from one room to another. """
        fellow = self.fellows[-1]
        self.amity.allocate_person(str(fellow.employee_id))

        self.amity.create_room("L", 'kilifi')

        reallocated_status = self.amity.reallocate_person(str(fellow.employee_id), 'kilifi')

        self.assertIn("Successfully Reallocated", reallocated_status)

    def test_reallocate_office(self):
        """ Test whether a person can be reallocated from one room to another. """
        fellow = self.fellows[-1]
        self.amity.allocate_person(str(fellow.employee_id))

        self.amity.create_room("O", 'kilaguni')

        reallocated_status = self.amity.reallocate_person(str(fellow.employee_id), 'kilaguni')

        self.assertIn("Successfully Reallocated", reallocated_status)

    def test_staff_reallocated_lspace(self):
        """
        Test that error message is returned when staff is reallocated to \
        LivingSpace
        """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))

        reallocated_status = self.amity.reallocate_person(str(staff.employee_id), 'mombasa')

        self.assertIn("Cannot reallocate staff to livingspace!", reallocated_status)

    def test_load_people(self):
        """ Test whether load_people adds people to room from a text file. """
        self.amity.fellows = []
        self.amity.load_people("people")

        self.assertTrue(self.amity.fellows)

    def test_load_people_from_non_existent_file(self):
        """ Tests whether people can be loaded from a non-existent file. """
        load_people = self.amity.load_people("persons")

        self.assertEqual("File: persons, Not Found!", load_people)

    def test_allocations_outputs_file(self):
        """ Tests whether allocations can be printed on file: new_allocations. """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))
        self.amity.print_allocations("new_allocations")
        file_path = os.path.abspath("data/new_allocations.txt")
        file_status = os.path.isfile(file_path)

        self.assertTrue(file_status)

    def test_allocations_outputs_screen(self):
        """ Tests whether allocations can be printed on file: new_allocations. """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))
        data = self.amity.print_allocations()

        self.assertTrue(data)

    def test_output_when_no_room(self):
        """ Test print_allocations when no rooms in the system """
        self.amity.offices = []
        self.amity.living_spaces = []

        data = self.amity.print_allocations()

        self.assertIn("No Rooms Found.", data)

    def test_output_to_file(self):
        """ Tests whether the unallocated can be printed on file: new_unallocated. """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))
        self.amity.print_unallocated("new_unallocated")
        file_path = os.path.abspath("data/new_unallocated.txt")
        file_status = os.path.isfile(file_path)

        self.assertTrue(file_status)

    def test_unallocated_outputs_screen(self):
        """ Tests whether the unallocated can be printed on file: new_unallocated. """
        staff = self.staff[-1]
        self.amity.allocate_person(str(staff.employee_id))
        data = self.amity.print_unallocated()

        self.assertTrue(data)

    def test_print_non_existent_room(self):
        """ Test whether a non-existent room can be printed on screen. """
        print_room = self.amity.print_room("arkham")

        self.assertIn("Room not found!", print_room)

    def test_when_no_occupants_in_room(self):
        """ Test whether a room with no occupants can be printed on screen. """
        print_room = self.amity.print_room("mombasa")

        self.assertIn("No occupants in room", print_room)

    def test_print_correct_occupants(self):
        """ Test whether a room and its occupants can be printed on screen. """
        fellow = self.fellows[-1]
        self.amity.allocate_person(str(fellow.employee_id))
        print_room = self.amity.print_room("mombasa")

        self.assertIn("Hum Musonye", print_room)

    def test_save_state_creates_db(self):
        """ Test whether save_state creates a SQLite database. """
        self.amity.save_state("test")
        file_path = os.path.abspath("test.db")
        file_status = os.path.isfile(file_path)

        self.assertTrue(file_status)

    def test_non_existent_db(self):
        """ Tests how load_state behaves when passed a nn existent db name. """
        load_state = self.amity.load_state("amity_lagos")

        self.assertEqual("Database amity_lagos.db not found!", load_state)

    def test_load_test(self):
        """ Test whether load_state persists data from db to amity system. """
        self.amity.add_person("bat", "man", "fellow", "Y")
        self.amity.save_state("test_load")
        self.amity.load_state("test_load")

        is_loaded = True if len(self.amity.fellows) > 1 else False

        self.assertTrue(is_loaded)
class AllocationTestCase(unittest.TestCase):
    """ tests the allocation of rooms to persons """

    def test_allocation_to_rooms(self):
        """ tests the allocation of persons to rooms """
        self.fellow = Person.create(
            'Jee Gikera', 'fellow', wants_accomodation='Y')
        self.staff = Person.create('Chidi Nnadi', 'staff')
        office_room = Office('valhalla')
        living_room = LivingSpace('blue')
        # store person instances for testing
        fellow_only.append(self.fellow)
        persons.append(self.staff)
        persons.append(self.fellow)

        office_results = self.staff.assign_office_space(office_room)
        living_results = self.fellow.assign_living_space(living_room)
        office_room.assign_person(self.staff)
        living_room.assign_person(self.fellow)
        self.assertTrue(self.staff.has_office())
        self.assertTrue(self.fellow.has_living_space())
        self.assertIsInstance(office_results, Office)
        self.assertIsInstance(living_results, LivingSpace)
        self.assertIsNotNone(living_room)
        self.assertIsNotNone(office_room)
        self.assertFalse(living_room.is_occupied())
        self.assertFalse(office_room.is_occupied())
        self.office = Office('GreenHouse')
        self.living = LivingSpace('BlueMoon')
        self.amity = Amity()

        ospace = self.amity.allocate_office_space(self.fellow)
        lspace = self.amity.allocate_living_space(self.fellow)
        allocated = self.office.get_occupants()
        self.assertEquals(self.staff.has_living_space(), False)
        self.assertEquals(self.fellow.has_living_space(), True)
        self.assertIsNotNone(allocated)
        self.assertIsNotNone(ospace)
        self.assertIsNotNone(lspace)

    def test_getting_room_occupants(self):
        """ tests getting a given room's occupants """
        self.amity = Amity()
        office_results = self.amity.allocate_office_space(
            file_path, is_a_file=True)
        living_results = self.amity.allocate_living_space(
            file_path, is_a_file=True)
        office_roomies = office_results[0].get_occupants()
        living_roomies = living_results[0].get_occupants()
        self.assertIsNotNone(office_roomies)
        self.assertIsNotNone(living_roomies)

    def test_getting_all_allocations(self):
        """ tests getting all allocations to the building """
        self.amity = Amity()
        self.amity.allocate_living_space(file_path, is_a_file=True)
        self.amity.allocate_office_space(file_path, is_a_file=True)
        allocations = self.amity.get_allocations()
        print_allocation = self.amity.print_allocations()
        self.assertIsNotNone(allocations)
        self.assertTrue(print_allocation)

    def test_unallocated(self):
        """ test getting unallocated people if any """
        amity = Amity()
        amity.allocate_office_space(file_path, is_a_file=True)
        unalloc = amity.get_unallocated()
        unallocated = amity.unallocated
        # the rooms are currently 10, each taking 4 occupants,
        # therefore we don't have unallocated persons
        self.assertIsNotNone(unalloc)
        self.assertIsNotNone(unallocated)
class AllocationTestCase(unittest.TestCase):
    """ tests the allocation of rooms to persons """
    def test_allocation_to_rooms(self):
        """ tests the allocation of persons to rooms """
        self.fellow = Person.create('Jee Gikera',
                                    'fellow',
                                    wants_accomodation='Y')
        self.staff = Person.create('Chidi Nnadi', 'staff')
        office_room = Office('valhalla')
        living_room = LivingSpace('blue')
        # store person instances for testing
        fellow_only.append(self.fellow)
        persons.append(self.staff)
        persons.append(self.fellow)

        office_results = self.staff.assign_office_space(office_room)
        living_results = self.fellow.assign_living_space(living_room)
        office_room.assign_person(self.staff)
        living_room.assign_person(self.fellow)
        self.assertTrue(self.staff.has_office())
        self.assertTrue(self.fellow.has_living_space())
        self.assertIsInstance(office_results, Office)
        self.assertIsInstance(living_results, LivingSpace)
        self.assertIsNotNone(living_room)
        self.assertIsNotNone(office_room)
        self.assertFalse(living_room.is_occupied())
        self.assertFalse(office_room.is_occupied())
        self.office = Office('GreenHouse')
        self.living = LivingSpace('BlueMoon')
        self.amity = Amity()

        ospace = self.amity.allocate_office_space(self.fellow)
        lspace = self.amity.allocate_living_space(self.fellow)
        allocated = self.office.get_occupants()
        self.assertEquals(self.staff.has_living_space(), False)
        self.assertEquals(self.fellow.has_living_space(), True)
        self.assertIsNotNone(allocated)
        self.assertIsNotNone(ospace)
        self.assertIsNotNone(lspace)

    def test_getting_room_occupants(self):
        """ tests getting a given room's occupants """
        self.amity = Amity()
        office_results = self.amity.allocate_office_space(file_path,
                                                          is_a_file=True)
        living_results = self.amity.allocate_living_space(file_path,
                                                          is_a_file=True)
        office_roomies = office_results[0].get_occupants()
        living_roomies = living_results[0].get_occupants()
        self.assertIsNotNone(office_roomies)
        self.assertIsNotNone(living_roomies)

    def test_getting_all_allocations(self):
        """ tests getting all allocations to the building """
        self.amity = Amity()
        self.amity.allocate_living_space(file_path, is_a_file=True)
        self.amity.allocate_office_space(file_path, is_a_file=True)
        allocations = self.amity.get_allocations()
        print_allocation = self.amity.print_allocations()
        self.assertIsNotNone(allocations)
        self.assertTrue(print_allocation)

    def test_unallocated(self):
        """ test getting unallocated people if any """
        amity = Amity()
        amity.allocate_office_space(file_path, is_a_file=True)
        unalloc = amity.get_unallocated()
        unallocated = amity.unallocated
        # the rooms are currently 10, each taking 4 occupants,
        # therefore we don't have unallocated persons
        self.assertIsNotNone(unalloc)
        self.assertIsNotNone(unallocated)
예제 #5
0
import os
import sys
import inspect

currentdir = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

from amity import Amity

# exit gracefully when the text file to read is missing
if __name__ == "__main__":
    try:
        arg1 = sys.argv[1]
    except IndexError:
        print("Usage: python sample.py <text file>")
        sys.exit(1)

amity = Amity()
amity.allocate_living_space(sys.argv[1], is_a_file=True)
amity.allocate_office_space(sys.argv[1], is_a_file=True)

amity.get_allocations()
amity.print_allocations()
print amity.get_unallocated()
예제 #6
0
class TestAmityFunctionality(unittest.TestCase):
    '''
    The self.amity Class here is used to hold the mian functionality
    of the self.amity Room Allocation system. It imports and makes calls
    to all other classes and manages them to create necessary instances
    and performs the necessary logic. This Test Class thus tests
    all the logic approporately.
    '''
    def setUp(self):
        self.amity = Amity()

    def test_amity_class_initialises_with_nothing(self):
        self.assertEquals(len(self.amity.rooms), 0)
        self.assertEquals(len(self.amity.people), 0)
        self.assertEquals(len(self.amity.fellows), 0)
        self.assertEquals(len(self.amity.staff), 0)

    # create room method test functionality begins here
    def test_returns_error_when_non_string_is_addded(self):
        self.assertEqual(self.amity.create_room(0, 2),
                         'Error. Invalid room type initial.',
                         msg='Room name and initial must only be strings.')
        self.assertEqual(self.amity.create_room('w', 'WorkSpace'),
                         'Error. Invalid room type initial.',
                         msg='Enter O or L for room type inital.')

    def test_create_room_method(self):
        with patch("amity.rooms.room.Office"):
            self.amity.create_room("o", "Lime")
            self.assertIn("Lime", self.amity.offices['available'])
        with patch("amity.rooms.room.LivingSpace"):
            self.amity.create_room('l', 'python')
            self.assertIn('Python', self.amity.living_spaces['available'])

    def test_create_room_increases_rooms_list_by_one(self):
        room_count_before = len(self.amity.rooms)
        with patch("amity.rooms.room.Office"):
            self.amity.create_room("o", "Lime")
            room_count_after = len(self.amity.rooms)
            self.assertEquals((room_count_after - room_count_before), 1)
            self.amity.create_room('o', 'oculus')
            room_count_after_two = len(self.amity.rooms)
            self.assertAlmostEquals((room_count_after_two - room_count_before),
                                    2)

    def test_living_space_can_only_be_created_once(self):
        with patch('amity.rooms.room.LivingSpace'):
            self.amity.create_room('l', 'ruby')
            result = self.amity.create_room('l', 'ruby')
            self.assertEqual(result, 'Room already exists.')

    def test_office_can_only_be_created_once(self):
        with patch('amity.rooms.room.Office'):
            self.amity.create_room('o', 'orange')
            result = self.amity.create_room('o', 'orange')
            self.assertEqual(result, 'Room already exists.')

    def test_room_creation_when_successful(self):
        with patch('amity.rooms.room.Office'):
            result = self.amity.create_room('o', 'krypton')
            self.assertEqual(result, 'Room Krypton created.')
        with patch('amity.rooms.room.LivingSpace'):
            result = self.amity.create_room('l', 'haskell')
            self.assertEqual(result, 'Room Haskell created.')

    # Print allocations method test begins here
    def test_returns_no_allocations_if_no_rooms_created(self):
        self.assertEqual(self.amity.print_allocations(),
                         'Error. No rooms within system.')

    # add_person method testing begins here

    def test_returns_error_if_no_rooms_within_system(self):
        result = self.amity.validate_person('Jackie', 'Maribe', 'Fellow', 'Y')
        self.assertEqual(result, 'There are no rooms in the system.')

    def test_validation_of_people_names(self):
        self.amity.create_room('o', 'lime')
        res = self.amity.validate_person('Jackie', 45, 'Fellow', 'y')
        self.assertTrue(res)
        self.assertEqual(res, 'Wrong type for name.')
        res2 = self.amity.validate_person('J6327', 'Maribe', 'Fellow', 'Y')
        self.assertTrue(res2)
        self.assertEqual(res2, 'Non-Alphabetical names added')

    def test_validation_of_people_types(self):
        self.amity.create_room('o', 'cyan')
        res = self.amity.validate_person('alex', 'graham', 'worker', 'y')
        self.assertTrue(res)
        self.assertEqual(res, 'Invalid Person Type')

    def test_wants_accomodation_is_either_y_or_n(self):
        self.amity.create_room('o', 'lilac')
        res = self.amity.validate_person('seralynnette', 'nduta', 'Fellow',
                                         'Yes')
        self.assertTrue(res)
        self.assertEqual(res, 'Wants accomodation not Y or N')

    def test_validation_if_person_fellow_and_wants_accomodation(self):
        '''
        Both a living space and office must exist for a fellow who
        wants accomodation.
        '''
        self.amity.create_room('o', 'pyrex')
        res = self.amity.validate_person('wycliffe', 'wangondu', 'Fellow', 'Y')
        self.assertTrue(res)
        self.assertEqual(res, 'No Living space for fellow requiring both.')

    def test_passes_validation_and_creates_person(self):
        # Since there are only two rooms: one of each Living Space and Office
        # and person wants accomodation
        # we are sure the rooms allocated are as created.
        self.amity.create_room('o', 'clandy')
        self.amity.create_room('l', 'treetop')
        res = self.amity.validate_person('myanmar', 'wakesho', 'Fellow', 'y')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        for room in self.amity.rooms:
            if room.room_name == 'Clandy':
                self.assertIn('Myanmar Wakesho', room.occupants)
                self.assertEqual(len(room.occupants), 1)
            if room.room_name == 'treetop':
                self.assertIn('Myanmar Wakesho', room.occupants)
                self.assertEqual(len(room.occupants), 1)

    def test_person_objects_are_created(self):
        self.amity.create_room('o', 'mars')
        self.amity.create_room('l', 'earth')
        res = self.amity.validate_person('justine', 'kariuki', 'Fellow', 'y')
        person = self.amity.generate_identifier(res)
        for person in self.amity.people:
            if person.full_name == 'Justine Kariuki':
                self.assertEqual(person.person_type, 'Fellow')
                self.assertEqual(person.identifier, 'F1')

        res2 = self.amity.validate_person('alec', 'kambua', 'Staff', 'n')
        person = self.amity.generate_identifier(res2)
        for person in self.amity.people:
            if person.full_name == 'Alec Kambua':
                self.assertEqual(person.person_type, 'Staff')
                self.assertEqual(person.identifier, 'S1')

    def test_get_identifier_if_no_people_added(self):
        self.assertEqual(self.amity.get_identifier('Lydiah', 'Kan'),
                         'No people added')

    def test_get_identifier_if_people_added(self):
        self.amity.create_room('o', 'yellow')
        self.amity.create_room('l', 'blue')
        res = self.amity.validate_person('brandon', 'balagu', 'Fellow', 'y')
        res = self.amity.generate_identifier(res)
        self.assertEqual(self.amity.get_identifier('brandon', 'balagu'), 'F1')

    # Test Reallocate Person starts here

    def test_reallocate_person(self):
        self.amity.create_room('o', 'Jupiter')
        self.amity.create_room('o', 'Pluto')
        res = self.amity.validate_person('isaac', 'kimani', 'staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_person('S1', [])
        self.assertEqual(res, "Error. Please enter valid room name.")

    def test_reallocate_person_when_room_does_not_exist(self):
        self.amity.create_room('o', 'Mars')
        self.amity.create_room('o', 'Venus')
        res = self.amity.validate_person('Nduta', 'Nungari', 'staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_person('S1', 'Neptune')
        self.assertEqual(res, "Room does not exist.")

    def test_reallocate_person_when_person_accomodate_is_N(self):
        self.amity.create_room('o', 'Mars')
        self.amity.create_room('l', 'Venus')
        res = self.amity.validate_person('Xander', 'Akura', 'Fellow', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_person('F1', 'Venus')
        self.assertEqual(res, 'Fellow does not want accomodation')
        for room in self.amity.rooms:
            if room.room_name == 'Venus':
                self.assertNotIn('Xander Akura', room.occupants)

    def test_reallocate_to_same_room(self):
        self.amity.create_room('o', 'Mars')
        res = self.amity.validate_person('michelle', 'wanjiru', 'Fellow', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_person('F1', 'Mars')
        self.assertEqual(res, 'cant reallocate to same room')

    def test_reallocate_to_same_room_if_person_id_non_exitent(self):
        self.amity.create_room('o', 'Mars')
        self.amity.create_room('o', 'Venus')
        res = self.amity.validate_person('serallynnette', 'wanjiku', 'Staff',
                                         'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_person('Staff1', 'Mars')
        self.assertEqual(res, 'Invalid person id.')

    def test_reallocate_person_works(self):
        self.amity.create_room('o', 'valhalla')
        res = self.amity.validate_person('seralynnette', 'wanjiku', 'Staff',
                                         'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        self.amity.create_room('o', 'narnia')
        res = self.amity.reallocate_person('S1', 'narnia')
        self.assertEqual(res, 'Person reallocated to Narnia')
        for room in self.amity.rooms:
            if room.room_name == 'Valhalla':
                self.assertNotIn('Seralynnette Wanjiku', room.occupants)
            if room.room_name == 'Narnia':
                self.assertIn('Seralynnette Wanjiku', room.occupants)

    def test_reallocate_unallocated(self):
        self.amity.create_room('o', 'prayar')
        res = self.amity.validate_person('Austin', 'Mugage', 'staff')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.reallocate_unallocated('s65', 'Prayar')
        self.assertEqual(res, 'Person ID does not exist.')

    # test_print_room_works

    def test_print_room_if_no_rooms(self):
        res = self.amity.print_room('Jupite')
        self.assertEqual(res, 'No rooms exist at the moment.')

    def test_if_room_exists(self):
        self.amity.create_room('o', 'jupite')
        res = self.amity.print_room('SOHK')
        self.assertEqual(res, 'Room does not exist.')

    # test print unallocated
    def test_print_unallocated_if_all_allocated(self):
        self.amity.create_room('o', 'lyon')
        res = self.amity.validate_person('Lyon', 'Witherspoon', 'Staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.print_unallocated()
        self.assertEqual(res, 'No unallocated people as per now.')

    def test_print_unallocated_if_exisiting(self):
        self.amity.create_room('o', 'Witherspoon')
        res = self.amity.validate_person('Lyon', 'Witherspoon', 'Staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        self.amity.unallocated_persons.append('Person Name')
        res = self.amity.print_unallocated()
        self.assertTrue(res, 'Some people unallocated.')

    # save state functionality

    def test_save_state(self):
        self.amity.create_room('o', 'Witherspoon')
        res = self.amity.validate_person('Lyon', 'Witherspoon', 'Staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        self.assertFalse(os.path.exists('default_db_self.amity.sqlite'))

    def save_state_works(self):
        self.amity.create_room('o', 'Witherspoon')
        res = self.amity.validate_person('Lyon', 'Witherspoon', 'Staff', 'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.save_state()
        self.assertEqual(res, True)

    # additional tests
    def test_returns_correct_message(self):
        self.amity.create_room('o', 'hOGWARTS')
        res = self.amity.validate_person('Bonnieface', 'Ntarangwi', 'Staff',
                                         'n')
        person = self.amity.generate_identifier(res)
        self.amity.allocate_room(person)
        res = self.amity.print_allocations()
        self.assertEqual(res, 'Print to screen')
        res2 = self.amity.print_allocations('test_bonnie')
        self.assertEqual(res2, 'Print to file')

    # test database loaded
    def test_database_loaded(self):
        self.amity.create_room('o', 'Hogwarts')
        self.amity.create_room('l', 'scala')
        self.amity.save_state()
        res = self.amity.load_state('default_amity_db')
        self.assertEqual(res, 'Database Loaded.')
import os
import sys
import inspect
currentdir = os.path.dirname(os.path.abspath(
    inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

from amity import Amity


# exit gracefully when the text file to read is missing
if __name__ == "__main__":
    try:
        arg1 = sys.argv[1]
    except IndexError:
        print ("Usage: python sample.py <text file>")
        sys.exit(1)

amity = Amity()
amity.allocate_living_space(sys.argv[1], is_a_file=True)
amity.allocate_office_space(sys.argv[1], is_a_file=True)

amity.get_allocations()
amity.print_allocations()
print amity.get_unallocated()
예제 #8
0
파일: run_app.py 프로젝트: hmusonye/CP1
class ScreenOut(cmd.Cmd):
    """main class"""

    os.system('clear')
    fig_font = Figlet(font='poison', justify='left', width=200)
    print("\n")
    print(colored(fig_font.renderText('( AMITY )'),\
         'green', attrs=['bold']))

    intro = colored('Version 1.0\t\t Enter "quit" to exit \n',
                    'green',
                    attrs=['bold'])

    nice = colored('(amity) ~ ', 'cyan', attrs=['blink'])
    prompt = nice

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.amity = Amity()

    @docopt_cmd
    def do_create_room(self, args):
        """Usage: create_room <room_type> <room_name>..."""
        room_type = args['<room_type>']
        room_names = args['<room_name>']

        msg = self.amity.create_room(room_type, *room_names)
        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg += '  ✔'
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_add_person(self, args):
        """Usage: add_person <fname> <lname> <role> [<wants_accomodation>]"""
        fname = args['<fname>']
        lname = args['<lname>']
        role = args['<role>']
        wants_accomodation = args['<wants_accomodation>']

        try:
            if wants_accomodation.upper() not in ['Y', 'N']:
                msg = "Invalid accomodation parameter! Please use Y or N  ✘"
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)

            if role.upper() not in ['FELLOW', 'STAFF']:
                msg = "Invalid role parameter! Please use FELLOW or STAFF  ✘"
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)

            else:
                msg = self.amity.add_person(fname, lname, role,
                                            wants_accomodation)
                msg += '  ✔'
                msg = colored(msg, 'green', attrs=['bold', 'dark'])
                print(msg)

        except AttributeError:
            msg = "Please indicate if person wants accomodation!  ✘"
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_allocate_person(self, args):
        """Usage: allocate_person <person_id>"""
        person_id = args['<person_id>']
        msg = self.amity.allocate_person(person_id)
        if "!" not in msg:
            msg += '  ✔'
            msg = colored(msg, 'yellow', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_reallocate_person(self, args):
        """Usage: reallocate_person <person_id> <new_room_name>"""
        person_id = args['<person_id>']
        room = args['<new_room_name>']
        msg = self.amity.reallocate_person(person_id, room)
        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg += '  ✔'
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_load_people(self, arg):
        """Usage: load_people"""
        msg = self.amity.load_people('people')
        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg += '  ✔'
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_print_allocations(self, args):
        """Usage: print_allocations [--o=filename.txt]"""
        if args['--o']:
            filename = args['--o']
            msg = self.amity.print_allocations(filename)
            if "!" in msg:
                msg += '  ✘'
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)
            else:
                msg += '  ✔'
                msg = colored(msg, 'green', attrs=['bold', 'dark'])
                print(msg)
        else:
            msg = self.amity.print_allocations()
            if "!" in msg:
                msg += '  ✘'
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)
            else:
                msg = colored(msg, 'yellow', attrs=['bold', 'dark'])
                print(msg)

    @docopt_cmd
    def do_print_unallocated(self, args):
        """Usage: print_unallocated [--o=filename.txt]"""
        if args['--o']:
            filename = args['--o']
            msg = self.amity.print_unallocated(filename)
            if "!" in msg:
                msg += '  ✘'
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)
            else:
                msg += '  ✔'
                msg = colored(msg, 'green', attrs=['bold', 'dark'])
                print(msg)
        else:
            msg = self.amity.print_unallocated()
            if "!" in msg:
                msg += '  ✘'
                msg = colored(msg, 'red', attrs=['bold', 'dark'])
                print(msg)
            else:
                msg = colored(msg, 'yellow', attrs=['bold', 'dark'])
                print(msg)

    @docopt_cmd
    def do_print_room(self, args):
        """Usage: print_room <room_name>"""
        room_name = args['<room_name>']
        msg = self.amity.print_room(room_name)

        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg += '  ✔'
            msg = colored(msg, 'yellow', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_save_state(self, args):
        """Usage: save_state [--db=sqlite_database]"""
        db = args['--db']
        msg = self.amity.save_state(db)
        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg += '  ✔'
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    @docopt_cmd
    def do_load_state(self, args):
        """Usage: load_state [<sqlite_database>]"""
        db = args['<sqlite_database>']
        msg = self.amity.load_state(db)
        if "!" in msg:
            msg += '  ✘'
            msg = colored(msg, 'red', attrs=['bold', 'dark'])
            print(msg)
        else:
            msg = colored(msg, 'green', attrs=['bold', 'dark'])
            print(msg)

    def do_quit(self, arg):
        """Quits out of Interactive Mode."""

        os.system('clear')
        bye = Figlet(font='jazmine')
        delay_print('\n\n' + \
                colored(bye.renderText('Bye ...'), 'yellow', attrs=['bold']))
        exit()