def setUp(self): visit_address = Address(house_number='75', route='Montrose Street', city='Glasgow', post_code='G1 1XJ') begin_date = datetime.date(2017, 2, 1) end_date = begin_date + datetime.timedelta(days=1) self.example_problem = Problem(**{ Problem.METADATA: Metadata(area=Area(key=23), begin=begin_date, end=end_date, version=distutils.version.StrictVersion('1.0.0')), Problem.CARERS: [ Problem.CarerShift(carer=Carer(sap_number='123456', position='Senior Carer', address=Address(house_number='Flat 6, Room C, 6', route='Blackfriars', city='Glasgow', post_code='G1 1QW')), diaries=[Diary( date=begin_date, shift_pattern_key='123', events=[AbsoluteEvent( begin=datetime.datetime(begin_date.year, begin_date.month, begin_date.day, hour=8), end=datetime.datetime(begin_date.year, begin_date.month, begin_date.day, hour=17, minute=30))])]) ], Problem.VISITS: [ Problem.LocalVisits(service_user='******', visits=[ Problem.LocalVisit( date=begin_date, time=datetime.time(13, 0, 0), duration=datetime.timedelta(minutes=30)) ]) ], Problem.SERVICE_USERS: [ ServiceUser(key='1234657', address=visit_address, location=Location(latitude=55.8619711, longitude=-4.2452754)) ] })
def from_json(json_array): """Returns an object created from rows""" if not json_array: raise RuntimeError('Location service returned no results') result_set = [] for row in json_array: if 'lon' not in row or 'lat' not in row: raise RuntimeError('Geographic system coordinates not found') if 'address' not in row: raise RuntimeError('Address not found') result_set.append({ Result.LOCATION: Location(longitude=row['lon'], latitude=row['lat']), Result.ADDRESS: Address(**row['address']), Result.POINT_OF_INTEREST: PointOfInterest(**row) }) if len(result_set) == 1: return Result(result_set=result_set[0]) return Result(result_set=result_set)
def from_json(json): """Create object from dictionary""" user_id = int(json.get(Visit.SERVICE_USER, None)) address_json = json.get(Visit.ADDRESS, None) address = Address.from_json(address_json) if address_json else None date_json = json.get(Visit.DATE, None) date = rows.model.datetime.try_parse_iso_date( date_json) if date_json else None time_json = json.get(Visit.TIME, None) time = rows.model.datetime.try_parse_iso_time( time_json) if time_json else None duration_json = json.get(Visit.DURATION, None) duration = rows.model.datetime.try_parse_duration( duration_json) if duration_json else None return Visit( **{ Visit.KEY: json.get(Visit.KEY, None), Visit.SERVICE_USER: user_id, Visit.DATE: date, Visit.TIME: time, Visit.DURATION: duration, Visit.CARER_COUNT: 1, Visit.ADDRESS: address })
def test_simple_address(self): expected_address = Address(house_number='44', city='Glasgow', road='James Weir Avenue', post_code='G199 ODR') for text in [ '0/2, 44, James Weir Avenue, Glasgow, G199 ODR', '., 44, James Weir Avenue, Glasgow, G199 ODR', 'Flat "O" alpha not numeral , 44, James Weir Avenue, Glasgow, G199 ODR', '., 44, James Weir Avenue, Glasgow, G199 ODR', '0/1, 44, James Weir Avenue, Glasgow, G199 ODR', '., 44, James Weir Avenue, Glasgow, G199 ODR', '0, 44, James Weir Avenue, Glasgow, G199 ODR', '44 James Weir Avenue, Glasgow, G199 ODR', '0/2, 44 James Weir Avenue, Glasgow, G199 ODR', 'Flat 3/3, The Observatory, 44 James Weir Avenue, ..., ..., ..., Glasgow, G199 ODR' ]: actual_address = Address.parse(text) self.assertEqual(expected_address, actual_address)
def test_service_not_available(self): """should handle situations where network service is not available""" http_mock = unittest.mock.Mock(spec=requests) http_mock.request.side_effect = requests.ConnectionError() address = Address(house_number=-1, road='', city='None') location_service = AddressLocationFinder(http_client=http_mock) result = location_service.find(address) self.assertTrue(result.is_faulted) self.assertTrue(isinstance(result.exception, requests.ConnectionError))
def test_network_timeout(self): """should handle situations where network service did not return result within a certain timeout""" address = Address(house_number=1, road='Montrose Street', city='Glasgow') location_service = AddressLocationFinder(timeout=0.01) result = location_service.find(address) self.assertTrue(result.is_faulted) self.assertTrue(isinstance(result.exception, requests.ConnectionError))
def test_multiple_locations_found(self): """should find multiple coordinates of a vogue location""" address = Address(house_number=1, road='Montrose Street', city='Glasgow') location_service = AddressLocationFinder() result = location_service.find(address) self.assertFalse(result.is_faulted) self.assertIsNotNone(result.result_set) self.assertTrue(isinstance(result.result_set, list)) self.assertTrue(len(result.result_set) > 1)
def from_json(json): """Converts object from dictionary""" address_json = json.get(Carer.ADDRESS, None) address = Address(**address_json) if address_json else None return Carer( **{ Carer.KEY: json.get(Carer.KEY), Carer.ADDRESS: address, Carer.POSITION: json.get(Carer.POSITION), Carer.MOBILITY: json.get(Carer.MOBILITY), Carer.SAP_NUMBER: json.get(Carer.SAP_NUMBER), Carer.SKILLS: json.get(Carer.SKILLS) })
def test_location_found(self): """should find coordinates of an exact location""" address = Address(house_number=75, road='Montrose Street', city='Glasgow') location_service = AddressLocationFinder() result = location_service.find(address) self.assertFalse(result.is_faulted) self.assertIsNotNone(result.result_set) self.assertTrue('location' in result.result_set) self.assertEqual(result.result_set['location'], Location(longitude='-4.245461', latitude='55.862235'))
def test_location_not_found(self): """should handle situations where location was not found""" address = Address(house_number=99999, road='Montrose Street', city='Glasgow') location_service = AddressLocationFinder() result = location_service.find(address) self.assertFalse(result.is_faulted) self.assertTrue(isinstance(result.result_set, list)) for row in result.result_set: self.assertTrue('poi' in row) self.assertIsNotNone(row['poi'].tags) for tag in row['poi'].tags: self.assertTrue(tag.label == 'way' or tag.label == 'highway')
def __load(path, acc): try: with open(path, 'r') as file_stream: try: pairs = json.load(file_stream) if pairs: for raw_address, raw_location in pairs: acc[Address(**raw_address)] = Location( **raw_location) return True except (RuntimeError, json.decoder.JSONDecodeError) as ex: logging.error( 'Failed to load cache due to unknown format: %s', ex) return False except FileNotFoundError: logging.info("Cache file '%s' does not exist", path) return False
class TestVisit(unittest.TestCase): """Test carer""" EXAMPLE_SERVICE_USER = '******' EXAMPLE_DATE = datetime.datetime.utcnow().date() EXAMPLE_TIME = datetime.datetime.utcnow().time() EXAMPLE_DURATION = datetime.timedelta(minutes=15) EXAMPLE_ADDRESS = Address(road='Montrose Street', house_number='75', city='Glasgow', post_code='G1 1XJ') def setUp(self): self.example_visit = Visit(service_user=TestVisit.EXAMPLE_SERVICE_USER, date=TestVisit.EXAMPLE_DATE, time=TestVisit.EXAMPLE_TIME, duration=TestVisit.EXAMPLE_DURATION, address=TestVisit.EXAMPLE_ADDRESS) def test_csv_visit(self): """Can access properties and serialize to dictionary""" self.assertIsNone(self.example_visit.key) self.assertEqual(self.example_visit.address, TestVisit.EXAMPLE_ADDRESS) self.assertEqual(self.example_visit.service_user, TestVisit.EXAMPLE_SERVICE_USER) self.assertEqual(self.example_visit.date, TestVisit.EXAMPLE_DATE) self.assertEqual(self.example_visit.time, TestVisit.EXAMPLE_TIME) self.assertEqual(self.example_visit.duration, TestVisit.EXAMPLE_DURATION) self.assertEqual(self.example_visit.as_dict(), collections.OrderedDict( [(Visit.KEY, None), (Visit.SERVICE_USER, TestVisit.EXAMPLE_SERVICE_USER), (Visit.DATE, TestVisit.EXAMPLE_DATE), (Visit.TIME, TestVisit.EXAMPLE_TIME), (Visit.DURATION, TestVisit.EXAMPLE_DURATION), (Visit.CARER_COUNT, 1), (Visit.ADDRESS, TestVisit.EXAMPLE_ADDRESS)])) def test_dictionary_serialization(self): """Can deserialize from a dictionary""" actual = Visit(**self.example_visit.as_dict()) self.assertEqual(actual, self.example_visit) if __name__ == '__main__': unittest.main()
def from_json(json): """Converts object from dictionary""" address_json = json.get(ServiceUser.ADDRESS, None) address = Address(**address_json) if address_json else None location_json = json.get(ServiceUser.LOCATION, None) location = Location(**location_json) return ServiceUser( **{ ServiceUser.KEY: json.get(ServiceUser.KEY), ServiceUser.LOCATION: location, ServiceUser.ADDRESS: address, ServiceUser.CARER_PREFERENCE: json.get(ServiceUser.CARER_PREFERENCE, None) })
def setUp(self): self.example_address = Address(post_code=TestCarer.EXAMPLE_POST_CODE) self.example_carer = Carer(position=TestCarer.EXAMPLE_POSITION, address=self.example_address, sap_number=TestCarer.EXAMPLE_SAP_NUMBER)