def setUp(self): self.engine = create_engine('sqlite:///:memory:') session = sessionmaker(self.engine) session.configure(bind=self.engine) self.session = session() sys.stdout = StringIO() self.amity = Amity() self.Base = declarative_base()
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)
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 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 setUp(self): """setting up resources/dependencies these tests rely on to run.""" self.amity_object = Amity() self.office_available = self.amity_object.create_office( 'mordor', 'Office') self.living_space_available = self.amity_object.create_living_space( 'st. catherine', 'LivingSpace') self.new_staff_added = self.amity_object.add_staff( 'David', 'Mukiibi', 'Staff') self.new_fellow_added = self.amity_object.add_fellow( 'Timothy', 'Wikedzi', 'Fellow') self.people_exist_in_room = self.amity_object.display_people_in_room( 'mordor')
class AmityTestPrintUnallocated(unittest.TestCase): """This class contains tests for the print_unallocated function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_if_system_has_people_before_printing(self): """ Tests if the system has people before printing them members """ self.assertEqual(self.amity.print_unallocated('test_file'), 'No people found in the system') def test_if_filename_contains_unwanted_characters(self): """ Tests if the filename contains unwanted characters """ self.assertEqual(self.amity.print_unallocated('test/<>file'), False)
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)
def setUp(self): self.amity = Amity() self.amity.prepopulate() self.parser = self.amity.create_parser() args = self.parser.parse_args(["input.txt"]) self.amity.inputfile = args.inputfile self.amity.inputfile_reader() self.amity.allocate()
class AmityTestLoadPeople(unittest.TestCase): """ This class tests all cases associated with load_people function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_load_people_handles_invalid_path(self): "Tests if a file path is valid" wrong_path = '/wrongfilepath.txt' status = self.amity.load_people(wrong_path) self.assertEqual('Invalid filepath.', status) def test_if_load_people_filepath_loads_file(self): "Tests if file is loaded" empty_filepath = 'files/empty_file.txt' status = self.amity.load_people(empty_filepath) self.assertEqual('The file has no contents', status)
class AmityTestSaveState(unittest.TestCase): """ This class contains tests for the save_state function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_if_database_name_contains_unwanted_characters(self): """ Tests if the database name contains unwanted characters """ self.assertEqual(self.amity.save_state('db/<>name'), False)
def do_print_unallocated(self, arg): """"Usage: print_unallocated [<filename>]""" filename = arg['<filename>'] list_return = Amity().get_all_unallocated_people(filename) print('Unallocated Fellows : ' + str(list_return[0])) print(list_return[1]) print('Unallocated Staffs: ' + str(list_return[2])) print(list_return[3]) print('=' * 75)
class AmityTestPrintRoom(unittest.TestCase): """ This class contains tests for the print_room function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_if_room_name_is_valid(self): """ Tests if room name is a valid name in the system """ self.assertEqual(self.amity.print_room('test_room'), 'Room was not found')
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)
class AmityTestCreateRoom(unittest.TestCase): """ This class tests all cases associated with create_room function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_if_room_is_office_or_living_space(self): "Tests if the type of room given is either a living space or an office" add_room = self.amity.create_room(['SHIRE', 'OFFIC']) self.assertEqual(add_room, 'You can only create OFFICE or a LIVING_SPACE') def tests_if_office_roomname_exists(self): "Tests that if office room name exists" add_room = self.amity.create_room(['SHIRE', 'OFFICE']) add_room = self.amity.create_room(['SHIRE', 'OFFICE']) self.assertEqual(add_room, 'One of the rooms entered exits') def tests_if_living_space_exists(self): "Tests if living space name does not exist" add_room = self.amity.create_room(['RUBY', 'LIVING_SPACE']) add_room = self.amity.create_room(['RUBY', 'LIVING_SPACE']) self.assertEqual(add_room, 'One of the rooms entered exits')
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)
class TestAmity(unittest.TestCase): def setUp(self): self.amity = Amity() self.amity.prepare_amity() def tearDown(self): self.amity = None def test_amity_is_initialised_properly(self): self.assertEquals(len(self.amity.offices), 10) self.assertEquals(len(self.amity.living), 10) self.assertGreater(len(self.amity.people), 0) def test_unallocated_fellows_are_returned(self): unallocated_fellows = self.amity.get_unallocated_fellows() for i in unallocated_fellows: self.assertIsInstance(i, Fellow) self.assertFalse(i.allocated) def test_unallocated_staff_are_returned(self): unallocated_staff = self.amity.get_unallocated_staff() for i in unallocated_staff: self.assertFalse(i.allocated)
def setUp(self): """ Creates the context on which tests will be run. """ # Create users for the test and write them to file users = ">Anthony Nandaa\n#Eric Gichuri\n#Mahad Walusimbi\n>Godson Ukpere\n##Kevin Ndungu\n>Joshua Mwaniki\n" alloFile = open('data/input.txt', 'w+') alloFile.write(users) alloFile.close() # Create rooms for the test and write them to file spaces = "+Heroku\n\tThomas Nyambati\n\tJeremy Kithome\n\tCollin Mutembei\n\tBrian Koech\n+Sound Cloud\n+Node\n+Digital Ocean\n\tGertrude Nyenyeshi\n\tStacey A.\n-Staff Room\n-Office 1\n-Office 2\n-Office 3\n-Office 4\n-Office 5\n" roomsFile = open('data/allocated.txt', 'w+') roomsFile.write(spaces) roomsFile.close() # Initialize amity campus self.campus = Amity() self.campus.prePopulate()
def do_print_empty_rooms(self, arg): """Usage: print_empty_rooms [<filename>]""" filename = arg['<filename>'] list_return = Amity().get_unallocated(filename) if type(list_return[0]) is list: print(list_return[0]) else: for key, value in list_return[0].items(): print('\tRoom Name: ' + key) print('\t' + '-' * 50) print('\tOccupants: ' + str(value)) print('\n') print('Office: ' + list_return[1]) print('Living Space: ' + list_return[2]) print('=' * 75)
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)
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.')
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)
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()
class AmityTest(unittest.TestCase): def setUp(self): self.amity = Amity() self.fellow = Fellow() self.Staff = Staff() self.office = Office() self.livingspace = LivingSpace() def test_add_person_fellow(self): self.amity.fellows = [{"id":"F16", "name":"Maryanne Waceke","role":"fellow" ,"office":"camelot"}] original_length = len(self.amity.fellows) self.amity.add_person("Jake", "Mwai", "fellow", "yes") self.assertTrue(len(self.amity.fellows) > original_length) def test_add_person_staff(self): self.amity.staff = [] original_length = len(self.amity.staff) self.amity.add_person("Sally", "Irungu", "staff") self.assertTrue(len(self.amity.staff) > original_length) def test_add_person_takes_either_role_of_staff_or_fellow(self): self.amity.staff = [] original_length = len(self.amity.staff) self.assertEqual(self.amity.add_person("harry", "kimani", 2), "Please enter valid role.") def test_add_person_takes_either_yes_or_no_for_wants_accomodaton(self): self.amity.fellows = [] original_length = len(self.amity.fellows) with self.assertRaises(ValueError): self.amity.add_person("harry", "kimani", "fellow", 3) def test_add_person_does_not_allocate_staff_accomodation(self): self.amity.staff = [] original_length = len(self.amity.staff) self.amity.add_person("Stella", "Murimi", "staff", "yes") self.assertEqual(self.amity.staff[0]["living_space"], None) def test_create_room_one_room(self): self.amity.offices = [] original_length = len(self.amity.offices) self.amity.create_room("living_space", "narnia") self.assertTrue(len(self.amity.offices) > original_length) def test_create_room_more_rooms(self): self.amity.offices = [] original_length = len(self.amity.offices) self.amity.create_room("living_space", "narnia", "topaz", "emerald") self.assertEqual(len(self.amity.offices), original_length+3) def test_create_room_takes_either_living_space_or_office_for_type(self): # self.amity.offices = [{"name": "camelot", "no_of_members": 1, "max_members": 6}] # self.amity.living_spaces = [{"name": "emerald", "no_of_members": 1, "max_members": 4}] # offices_original_length = len(self.amity.offices) # living_spaces_original_length = len(self.amity.living_spaces) # self.amity.create_room("sitting_room", "topaz") # self.assertEqual(len(self.amity.offices), offices_original_length) self.assertEqual(self.amity.create_room("sitting_room", "narnia"),"Please input valid room type") def test_create_room_only_takes_strings_as_room_names(self): self.assertEqual(self.amity.create_room("office", 1, 2), "Please enter valid room names.") # def test_allocate_office(self): # pass def test_allocate_living_space_works(self): self.amity.living_spaces = [ {"name": "emerald", "no_of_members": 1, "max_members": 4}] original_occupants = self.amity.living_spaces[0]["no_of_members"] self.amity.allocate_living_space("F120", "emerald") self.assertTrue( self.amity.living_spaces[0]["no_of_members"] > original_occupants) def test_allocate_living_space_doesnt_allocate_staff(self): # self.amity.living_spaces = [ # {"name": "emerald", "no_of_members": 1, "max_members": 4}] # original_occupants = self.amity.living_spaces[0]["no_of_members"] # self.amity.allocate_living_space("S12", "emerald") # self.assertEqual( # self.amity.living_spaces[0]["no_of_members"], original_occupants) self.assertEqual(self.amity.allocate_living_space("S12", "emerald"), "Staff cannot be allocated living space.") def test_allocate_living_space_doesnt_allocate_beyond_maximum(self): self.amity.living_spaces = [ {"name": "emerald", "no_of_members": 4, "max_members": 4}] # original_occupants = self.amity.living_spaces[0]["no_of_members"] # self.amity.allocate_living_space("F120", "emerald") # self.assertEqual( # self.amity.living_spaces[0]["no_of_members"], original_occupants) self.assertEqual(self.amity.allocate_living_space("F120", "emerald"), "Room full.") def test_reallocate_office_works(self): self.amity.offices = [{"name": "camelot", "no_of_members": 1, "max_members": 6}, { "name": "hogwarts", "no_of_members": 0, "max_members": 6}] self.amity.fellows = [{"id":"F16", "name":"Maryanne Waceke","role":"fellow" ,"office":"camelot"}] original_camelot_occupants = self.amity.offices[0]["no_of_members"] original_hogwarts_occupants = self.amity.offices[1]["no_of_members"] self.amity.reallocate_office("F16", "hogwarts") self.assertTrue(self.amity.offices[0]["no_of_members"]<original_camelot_occupants) self.assertTrue(self.amity.offices[1]["no_of_members"]>original_hogwarts_occupants)
def setUp(self): "Setup for class initializations" self.amity = Amity()
-i, --interactive Interactive Mode -h, --help Show this screen and exit. """ import sys import cmd import os sys.path.append('./app_classes') from docopt import docopt, DocoptExit from termcolor import cprint, colored from amity import Amity amity = Amity() def docopt_cmd(func): """ This decorator is used to simplify the try/except block and pass the result of the docopt parsing to the called action. """ def fn(self, arg): try: opt = docopt(fn.__doc__, arg) except DocoptExit as e: # The DocoptExit is thrown when the args do not match. # We print a message to the user and the usage block. print('\n') print('Invalid Command! Use the below syntax:')
class AmityTest(unittest.TestCase): def setUp(self): self.building = Amity() def tearDown(self): self.building = None def test_populate_offices(self): ''' Test whether the populate method populates the building with office rooms ''' self.assertTrue(len(self.building.office_rooms), 10) def test_populate_living(self): ''' Test whether the populate method populates the building with living rooms ''' self.assertEqual(len(self.building.living_rooms), 10) def test_create_staff(self): ''' Test create_occupants method ''' self.assertEqual(len(self.building.staff), 32) def test_create_fellows(self): ''' Test create_occupants method ''' fellows = len(self.building.boarding_fellows + self.building.non_boarding_fellows) self.assertEqual(fellows, 82) def test_allocate(self): ''' Tests allocate method ''' self.assertEqual(len(self.building.get_allocations()), 20) def test_get_available_room(self): ''' Tests getting available rooms ''' self.assertEqual(len(self.building.get_available_rooms('LIVING')), 0) def test_get_unallocated(self): ''' Tests getting unallocated staff ''' self.assertTrue( len(self.building.get_unallocated_occupants()), 38) def test_print_allocated(self): self.assertEqual(len(self.building.print_allocated()), 100) def test_analyse_allocations(self): result = self.building.analyze_allocations() self.assertTrue('total rooms' in result) self.assertTrue('allocated rooms' in result) self.assertTrue('total occupants' in result) self.assertEqual(result['total rooms'], 20) self.assertEqual(result['total occupants'], 114) self.assertEqual(result['allocated occupants'], 100)
def test_parsing_file(self): persons = Amity.get_people_from_file(file_path) self.assertEquals(len(persons), 76) self.assertIsInstance(persons[random.randint(0, 30)], Person)
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)
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()
def setUp(self): self.amity = Amity()
class TestAmity(unittest.TestCase): def setUp(self): self.amity = Amity() self.amity.prepopulate() self.parser = self.amity.create_parser() args = self.parser.parse_args(["input.txt"]) self.amity.inputfile = args.inputfile self.amity.inputfile_reader() self.amity.allocate() def tearDown(self): del self.amity.rooms['office'] del self.amity.rooms['living'] self.amity.people = [] def test_script_with_empty_args(self): with self.assertRaises(SystemExit): self.parser.parse_args([]) def test_initial_rooms_in_amity(self): self.assertEqual(len(self.amity.rooms[ 'living']), 10, msg="Amity should be preloaded with 10 living spaces") self.assertEqual(len( self.amity.rooms['office']), 10, msg="Amity should be preloaded with 10 offices") def test_number_of_persons_from_input(self): self.assertEquals(len(self.amity.people), 64) def test_members_of_room(self): self.assertLessEqual( len(self.amity.rooms['office'][0].get_members()), 6) self.assertLessEqual( len(self.amity.rooms['living'][0].get_members()), 4) def test_current_size_of_room(self): self.assertLessEqual(self.amity.rooms['office'][0].current_size(), 6) self.assertLessEqual(self.amity.rooms['living'][9].current_size(), 4) def test_unallocated(self): self.assertGreaterEqual(len(self.amity.unallocated['living']), 0) self.assertGreaterEqual(len(self.amity.unallocated['office']), 0) def test_total_number_of_romms_in_Amity(self): self.assertEquals(len(self.amity.get_rooms()), 20) @patch('sys.stdout', new_callable=StringIO) def test_print_result(self, mock_out): result_str = "Result:" self.amity.print_result() self.assertIn(result_str, mock_out.getvalue()) @patch('sys.stdout', new_callable=StringIO) def test_print_unallocated(self, mock_out): result_str = "After Allocation, the following could not be allocated" self.amity.print_unallocated() self.assertIn(result_str, mock_out.getvalue())
class AmityTestAddPerson(unittest.TestCase): """ This class tests all cases associated with add_person function """ def setUp(self): "Setup for class initializations" self.amity = Amity() def test_add_person(self): "Test that person is added" add_person = self.amity.add_person('Charles', 'Mac', 'Fellow', 'Y') self.assertEqual(add_person, 'Please create offices and living_spaces first.') self.amity.create_room(['SHIRE', 'OFFICE']) self.amity.create_room(['RUBY', 'LIVING_SPACE']) self.amity.add_person('Charles', 'Mac', 'STAFF', 'N') self.assertEqual(len(self.amity.all_people), 1) def test_if_person_exists(self): "Test if the person exists" self.amity.create_room(['SHIRE', 'OFFICE']) self.amity.create_room(['RUBY', 'LIVING_SPACE']) add_person = self.amity.add_person('Charles', 'Mac', 'Fellow', 'Y') add_person = self.amity.add_person('Charles', 'Mac', 'Fellow', 'Y') self.assertEqual(add_person, 'Another user exists with the same name') def test_add_person_with_accomodation_when_no_rooms_have_been_created( self): "Tests if there are living rooms and offices before adding a fellow who wants accomodation" add_person = self.amity.add_person('Charles', 'Mac', 'Fellow', 'Y') self.assertEqual(add_person, 'Please create offices and living_spaces first.') def test_add_person_with_accomodation_when_no_rooms_have_been_created( self): "Tests if there are offices before adding a fellow without accomodation" add_person = self.amity.add_person('Charles', 'Mac', 'Fellow', 'N') self.assertEqual(add_person, 'Please create offices first.') def test_rejects_when_staff_wants_accomodation(self): "Tests if the system denies staff accomodation." self.amity.create_room(['SHIRE', 'OFFICE']) self.amity.create_room(['RUBY', 'LIVING_SPACE']) add_person = self.amity.add_person('Charles', 'Mac', 'STAFF', 'Y') self.assertEqual(add_person, 'No accomodation for staff') def test_if_optional_args_for_wants_accomodation_is_valid(self): "Tests if optional argument for add_person is Y or N" self.amity.create_room(['SHIRE', 'OFFICE']) self.amity.create_room(['RUBY', 'LIVING_SPACE']) add_person = self.amity.add_person('Charles', 'Mac', 'STAFF', 'R') self.assertEqual(add_person, 'No such option. Use either Y or N') def test_if_person_role_is_valid(self): "Tests if the role is either staff or fellow " self.amity.create_room(['SHIRE', 'OFFICE']) self.amity.create_room(['RUBY', 'LIVING_SPACE']) add_person = self.amity.add_person('Charles', 'Mac', 'STAF', 'N') self.assertEqual(add_person, 'Your role is undefined')
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 AmityTests(unittest.TestCase): def setUp(self): """setting up resources/dependencies these tests rely on to run.""" self.amity_object = Amity() self.office_available = self.amity_object.create_office( 'mordor', 'Office') self.living_space_available = self.amity_object.create_living_space( 'st. catherine', 'LivingSpace') self.new_staff_added = self.amity_object.add_staff( 'David', 'Mukiibi', 'Staff') self.new_fellow_added = self.amity_object.add_fellow( 'Timothy', 'Wikedzi', 'Fellow') self.people_exist_in_room = self.amity_object.display_people_in_room( 'mordor') def test_office_created_successfully(self): """testing successful creation of an office""" self.amity_object.offices.append(self.office_available) final_no = len(self.amity_object.offices) self.assertEqual(1 <= final_no, bool(final_no)) # with self.assertRaises(Exception): # self.office_available() def test_office_name_created_with_aplhabets_only(self): # will need help on this test self.amity_object.offices.append(self.office_available) if isinstance(self.office_available.room_name, str) == False: self.assertTrue() else: pass def test_living_space_created_with_alphabets_only(self): pass def test_fellow_name_created_with_alphabets_only(self): pass def test_staff_name_created_with_alphabets_only(self): pass def test_living_space_created_successfully(self): """testing successful creation of a living space""" self.amity_object.living_spaces.append(self.living_space_available) space_created = len(self.amity_object.living_spaces) self.assertTrue(1 <= space_created, bool(space_created)) def test__staff_added_successfully(self): """ testing successful addition of staff to an office""" # self.amity_object.add_staff('david', 'Staff') people_in_andela = len(self.amity_object.all_people_in_amity) self.assertTrue(people_in_andela > 0, people_in_andela) def test_fellow_added_successfully(self): """testing successful addition of a fellow to an office""" # self.amity_object.add_fellow('david', 'Fellow') people_in_andela = len(self.amity_object.all_people_in_amity) self.assertTrue(people_in_andela > 0, people_in_andela) def test_room_name_is_not_empty(self): pass def test_loading_data_from_db_works_if_db_has_data(self): pass def test_loading_data_from_db_returns_appropriately_if_db_has_no_data( self): pass def test_printing_room_occupants_works(self): pass def test_printing_unallocated_people_works(self): pass def test_reallocating_a_person_works(self): pass def tets_fellow_added_successfully_to_living_space(self): pass def test_people_in_room_exist(self, room_name): """this test is to confirm that people really do exist in the specified room.""" # its still confusing me, but am yet to work it out. # on second thought i need help on this # self.amity_object.display_people_in_room(room_name) for k in self.amity_object.offices: if room_name == k.room_name: self.pipo_exist = len(k.office_occupants) self.assertTrue(True, self.pipo_exist > 0)
def setUp(self): self.amity = Amity() self.fellow = Fellow() self.Staff = Staff() self.office = Office() self.livingspace = LivingSpace()
class TestAllocationFromFile(unittest.TestCase): def setUp(self): """ Creates the context on which tests will be run. """ # Create users for the test and write them to file users = ">Anthony Nandaa\n#Eric Gichuri\n#Mahad Walusimbi\n>Godson Ukpere\n##Kevin Ndungu\n>Joshua Mwaniki\n" alloFile = open('data/input.txt', 'w+') alloFile.write(users) alloFile.close() # Create rooms for the test and write them to file spaces = "+Heroku\n\tThomas Nyambati\n\tJeremy Kithome\n\tCollin Mutembei\n\tBrian Koech\n+Sound Cloud\n+Node\n+Digital Ocean\n\tGertrude Nyenyeshi\n\tStacey A.\n-Staff Room\n-Office 1\n-Office 2\n-Office 3\n-Office 4\n-Office 5\n" roomsFile = open('data/allocated.txt', 'w+') roomsFile.write(spaces) roomsFile.close() # Initialize amity campus self.campus = Amity() self.campus.prePopulate() def tearDown(self): """ Performs housekeeping to clean up test files after tests have been executed. """ os.remove('data/input.txt') os.remove('data/allocated.txt') def test_prepopulate(self): """ Expects 4 living spaces and 6 office rooms. """ self.assertEqual(len(self.campus.livingRooms), 4) self.assertEqual(len(self.campus.officeRooms), 6) def test_unallocated_people(self): """ Expect unallocateed people to be 6. """ uFile = open('data/input.txt') unallocated = [] for line in uFile.readlines(): unallocated.append(line) self.assertEqual(len(unallocated), 6) def test_fellows_allocated_living(self): """ Expect fellows allocated living spaces to be 6. """ aFile = open('data/allocated.txt') allocated = [] for line in aFile.readlines(): if (line[0] == '\t'): allocated.append(line) self.assertEqual(len(allocated), 6) def test_allocate_through_app(self): """ Expects exception when allocation is performed on a full room. """ # Expect the first room (Heroku) to have 4 occupants heroku = self.campus.livingRooms[0] self.assertEqual(len(heroku.occupants), 4) # Expect the fourth room (Digital Ocean) to have 2 occupants docean = self.campus.livingRooms[3] self.assertEqual(len(docean.occupants), 2) # Expect OverflowException because heroku is full aFellow = Fellow("Martin Nate") with self.assertRaises(OverflowException): heroku.addFellow(aFellow) # Expect TypeError when staff added to living space staffer = Staff("Hellen Maina") with self.assertRaises(TypeError): heroku.addFellow(staffer)
class TestAmity(unittest.TestCase): def setUp(self): self.engine = create_engine('sqlite:///:memory:') session = sessionmaker(self.engine) session.configure(bind=self.engine) self.session = session() sys.stdout = StringIO() self.amity = Amity() self.Base = declarative_base() # Base.metadata.create_all(self.engine) # self.panel = Panel(1, 'ion torrent', 'start') # self.session.add(self.panel) # self.session.commit() def test_type_of_amity(self): self.assertIsInstance(Amity(), object) @patch('amity.Amity.connect_db') def test_create_tables(self, mock_connect_db): mock_connect_db.return_value = self.engine self.amity.create_tables() # assert table user exists self.assertTrue(self.engine.dialect.has_table( self.engine.connect(), "user")) # assert table room exists self.assertTrue(self.engine.dialect.has_table( self.engine.connect(), "room")) @patch('amity.Amity.connect_db') @patch('amity.Amity.retrieve_data_from_db') def test_load_state(self, mock_connect_db, mock_retrieve_data_from_db): mock_connect_db.return_value = self.engine mock_retrieve_data_from_db.return_value = True self.amity.load_state() printed = sys.stdout.getvalue() self.assertIn( "Please Wait... This may take some few minutes.", printed) self.assertIn("\tReading data from the database", printed) self.assertIn("Load State successfully completed", printed) self.assertIn('', printed) def test_retrieve_data_from_db(self): class User(self.Base): '''class mapper for table user''' __tablename__ = 'user' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) person_name = Column(String(30)) type_person = Column(String(30)) class Room(self.Base): '''class mapper for table room''' __tablename__ = 'room' id = Column(Integer, Sequence('room_id_seq'), primary_key=True) room_type = Column(String(20)) room_name = Column(String(30)) occupant1 = Column(String(30), ForeignKey('user.id')) occupant2 = Column(String(30), ForeignKey('user.id')) occupant3 = Column(String(30), ForeignKey('user.id')) occupant4 = Column(String(30), ForeignKey('user.id')) occupant5 = Column(String(30), ForeignKey('user.id')) occupant6 = Column(String(30), ForeignKey('user.id')) self.Base.metadata.create_all(self.engine) if self.engine.dialect.has_table(self.engine.connect(), "user"): print('user') test_User = Table("user", MetaData(self.engine), autoload=True) sample_data = {'person_name': 'andela-jkariuki', 'type_person': 'fellow'} test_User.insert().execute(sample_data) elif self.engine.dialect.has_table(self.engine.connect(), "room"): test_Room = Table("room", MetaData(self.engine), autoload=True) sample_data = {'room_name': 'php', 'room_type': 'livingspace', 'occupant1': 'Morris', 'occupant2': 'Migwi'} test_Room.insert().execute(sample_data) self.amity.retrieve_data_from_db(self.session) self.assertIn('andela-jkariuki', Fellow.fellow_names) self.assertNotIn('php', list(LivingSpace.room_n_occupants.keys())) @patch('amity.Amity.connect_db') @patch('amity.Amity.create_tables') @patch('amity.Amity.order_data_ready_for_saving') def test_save_state(self, mock_connect_db, mock_create_tables, mock_order_data_ready_for_saving): mock_connect_db.return_value = self.engine mock_create_tables.return_value = True mock_order_data_ready_for_saving.return_value = True sys.stdout = StringIO() self.amity.save_state() printed = sys.stdout.getvalue() self.assertIn( "Please Wait... This may take some few minutes.", printed) self.assertIn("\tInitiating database population....", printed) self.assertIn("\tFinalizing database population....", printed) self.assertIn("Save State successfully completed.", printed) @patch('app.fellow.Fellow.fellow_names') @patch('app.staff.Staff.staff_names') @patch.dict('app.office.Office.office_n_occupants', {'Round_Table': ['Sass', 'Joshua', 'Jeremy'], 'Krypton': ['Percila', 'Kimani', 'Whitney'], 'Valhala': ['Migwi'] }) @patch.dict('app.livingspace.LivingSpace.room_n_occupants', {'php': ['Andela1', 'andela2', 'Mr know it all'], 'amity': ['chiemeka', 'mayowa', 'chioma'], 'm55': ['adeleke'] }) def test_order_data_ready_for_saving(self, mock_fellow_names, mock_staff_names): class User(self.Base): '''class mapper for table user''' __tablename__ = 'user' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) person_name = Column(String(30)) type_person = Column(String(30)) class Room(self.Base): '''class mapper for table room''' __tablename__ = 'room' id = Column(Integer, Sequence('room_id_seq'), primary_key=True) room_type = Column(String(20)) room_name = Column(String(30)) occupant1 = Column(String(30), ForeignKey('user.id')) occupant2 = Column(String(30), ForeignKey('user.id')) occupant3 = Column(String(30), ForeignKey('user.id')) occupant4 = Column(String(30), ForeignKey('user.id')) occupant5 = Column(String(30), ForeignKey('user.id')) occupant6 = Column(String(30), ForeignKey('user.id')) self.Base.metadata.create_all(self.engine) mock_fellow_names.__iter__.return_value = ['chiemeka', 'mayowa', 'Andela1', 'andela2', 'adeleke'] mock_staff_names.__iter__.return_value = ['Sass', 'Joshua', 'Jeremy', 'chioma', 'Mr know it all'] self.amity.order_data_ready_for_saving(self.session) self.session.commit() self.session.flush() # check if table user exists all_rooms = {} all_users = [] if self.engine.dialect.has_table(self.engine.connect(), "user"): test_User = Table("user", MetaData(self.engine), autoload=True) all_users = test_User.select().execute() print(all_rooms) elif self.engine.dialect.has_table(self.engine.connect(), "room"): test_Room = Table("room", MetaData(self.engine), autoload=True) all_rooms = test_Room.select().execute() print(all_users) self.assertNotIn(frozenset({'Valhala': ['Migwi']}), all_rooms) self.assertNotIn(['Mr know it all', 'adeleke'], all_users) def test_print_file(self): data = {'The_Key': 'The value'} sample_text = 'Room Name: The_Key Occupants:The value \n\r' with patch("builtins.open", mock_open(read_data=sample_text)) as mock_file: self.amity.print_file('sample', 'allocated', data) mock_file.assert_called_with('sample-allocated.txt', 'w') # mock_file.write.assert_called_once_with(sample_text, 'w') assert open('sample-allocated.txt', 'w').read() == sample_text @patch('app.person.Person.add_person') def test_load_people(self, mock_add_person): sample_read_text = 'andela-dmigwi FELLOW Y' mock_add_person.return_value = 'Successful' with patch("builtins.open", mock_open(read_data=sample_read_text)) as mock_file: self.amity.load_people() # assert open("people.txt", 'r').readlines() == sample_read_text mock_file.assert_called_with("people.txt", 'r') printed = sys.stdout.getvalue() self.assertIn('Successful', printed) @patch('amity.Amity.compute_rooms') @patch('amity.Amity.print_file') def test_get_allocations(self, mock_print_file, mock_compute_rooms): mock_compute_rooms.return_value = {'Amity': ['Eston Mwaura']} mock_print_file.return_value = 'Successful' room_details = self.amity.get_allocations('test.txt') office_details = {'Amity': ['Eston Mwaura']} livingspace_details = 'Successful' self.assertIn(office_details, room_details) self.assertIn(livingspace_details, room_details) @patch('amity.Amity.compute_rooms') @patch('amity.Amity.print_file') def test_get_unallocated(self, mock_print_file, mock_compute_rooms): mock_compute_rooms.return_value = ['Amity'] mock_print_file.return_value = 'Successful' room_details = self.amity.get_unallocated('sample.txt') response_office = ['Amity', 'Amity'] response_livingspace = 'Successful' self.assertIn(response_office, room_details) self.assertIn(response_livingspace, room_details) def test_compute(self): rooms = {'m55': ['Aubrey, Chiemeka', 'Mayowa'], 'Amity': [], 'Dojo': ['Migwi', 'Elsis']} computed = self.amity.compute_rooms(rooms, 'allocated') rooms_1 = {'m55': ['Aubrey, Chiemeka', 'Mayowa'], 'Dojo': ['Migwi', 'Elsis']} self.assertEqual(computed, rooms_1) computed = self.amity.compute_rooms(rooms, 'unallocated') self.assertEqual(computed, ['Amity']) @patch.dict('app.office.Office.office_n_occupants', {'Dojo': ['Njira']}) @patch.dict('app.livingspace.LivingSpace.room_n_occupants', {'Valhala': ['Edwin']}) @patch('app.staff.Staff.staff_names') @patch('app.fellow.Fellow.fellow_names') def test_get_all_unallocated_people(self, mock_fellow_names, mock_staff_names): mock_fellow_names.__iter__.return_value = ['Lolo', 'Edwin'] mock_staff_names.__iter__.return_value = ['Eston', 'Njira'] check = self.amity.get_all_unallocated_people() self.assertIn('Lolo', check[0]) self.assertIn('Eston', check[2])
def setUp(self): self.building = Amity()
from random import random from spaces.living import Living from spaces.office import Office from custom import utilities from amity import Amity from people.fellow import Fellow from people.staff import Staff campus = Amity() campus.prePopulate() # useful vars rangeError = 'Range error: *** Please select a number that is within the range' valueError = 'Value error: *** Please enter a number in digit form ***\n' file_path = utilities.getPath('data/') while (True): utilities.mainMenu() answer = raw_input('Enter a number between 0 - 5 to select a menu.\n') try: # catch non integer input from the user answer = int(answer) # catch int that are outside the range in the menu if ((answer < 0) or (answer > 5)): utilities.clearScreen() print rangeError, ' 0 - 5 ***\n' continue except ValueError: utilities.clearScreen()
# implemented importation on different lines from amity import Amity import sys print "\twelcome to Amity" print amity_system = Amity() list_of_rooms = {} list_of_people = {} living_rooms = [] office_rooms = [] switch = False def allocations(amity, living_rooms, office_rooms): while True: option = int(raw_input("please select an option\ \n 1. enter data file\ \n 2. print members in a room\ \n 8. to quit\ \n input : ")) if option == 8: break elif option == 1: try: list_of_people = amity.get_data_file() except IOError: print("File does not exist") list_of_people = amity.get_data_file() if list_of_people:
def test_type_of_amity(self): self.assertIsInstance(Amity(), object)