def marriage_after_14(self) -> bool: from datetime import date if not self._husband or not self._wife or not self._marriedDate: raise AttributeError( "Missing husband/wife/marriedDate") if not self._husband.get_birthDate() or not self._wife.get_birthDate(): raise AttributeError( "Missing birthdate for husband/wife") if not self._husband or not self._wife or not self._marriedDate: raise AttributeError( "Missing husband/wife/marriedDate") if not self._husband.get_birthDate() or not self._wife.get_birthDate(): raise AttributeError( "Missing birthdate for husband/wife") husbandMarryAge = (date(*self._marriedDate) - date(*self._husband.get_birthDate())).days // 365 wifeMarryAge = (date(*self._marriedDate) - date(*self._wife.get_birthDate())).days // 365 if (husbandMarryAge > 14 and wifeMarryAge > 14): return True else: raise Error('ERROR', 'FAMILY', 'US10', self.get_lineNum()["MARR"], f"Family marriage date {self.get_marriedDate()} is not 14 years after" f"Husband birthday {self._husband.get_birthDate()} or Wife birthday {self._wife.get_birthDate()}")
def dfs(family, last_name): flag = True for child in family.get_children(): if child.get_gender() == None: raise AttributeError("child's gender is not set yet") if child.get_gender() == "F": continue if not child.get_name(): raise AttributeError("Child's name is missing") if child.get_name().split('/')[1] != last_name: #return False raise Error( 'ERROR', 'FAMILY', 'US16', child.get_lineNum()['NAME'] if "NAME" in child.get_lineNum() else "N/A", f"Male Child's last name {child.get_name().split('/')[1]} doesn't match family last name {last_name}" ) for fam in child.get_family(): flag = dfs(fam, check_last_name) and flag return flag
def birth_before_marriage(self): from datetime import date if not self._birthDate or not self._family: raise AttributeError( "Missing self birthday or family marriage date") # if not self._parentFamily.get_marriedDate(): raise AttributeError("Missing attribute") for family in self.get_family(): if not family.get_marriedDate(): raise AttributeError("Missing marriage data") timedelta = date(*family.get_marriedDate()) - date( *self._birthDate) if (timedelta.days <= 0): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US02', self.get_lineNum()['BIRT'] if "BIRT" in self.get_lineNum() else "N/A", f" Individual's Birthday {self.get_birthDate()} is after marriage date of Family {family.get_marriedDate()}" ) return True
def parents_not_too_old(self): if not self._husband or not self._wife: raise AttributeError("missing husband or wife") if not self._husband.get_age() or not self._wife.get_age(): raise AttributeError( "missing age for husband or wife") if not self._husband.get_age() or not self._wife.get_age(): raise AttributeError( "missing age for husband or wife") wife_age = self._wife.get_age() husband_age = self._husband.get_age() for child in self._children: if not child.get_age(): raise AttributeError("missing child age") wife_diff = wife_age - child.get_age() husband_diff = husband_age - child.get_age() if wife_diff >= 60 or husband_diff >= 80: raise Error('ANOMALY', 'FAMILY', 'US12', self.get_lineNum()["FAM ID"], f"Family Mother's age {wife_age} exceeds child's age {child.get_age()} by 60 or Father's age {husband_age} exceeds child's age by 80") # return False return True
def divorce_before_death(self) -> bool: from datetime import date if not self._husband or not self._wife: raise AttributeError("Missing husband/wife") if not self._husband.get_deathDate() and not self._wife.get_deathDate(): return True if not self._divorced: return True deathdays = None if self._husband.get_deathDate() and self._wife.get_deathDate(): deathdays = (date(*self._divorced) - date(*self._husband.get_deathDate())).days if deathdays > (date(*self._divorced) - date(*self._wife.get_deathDate())).days: deathdays = (date(*self._divorced) - date(*self._wife.get_deathDate())).days elif not self._husband.get_deathDate(): deathdays = (date(*self._divorced) - date(*self._wife.get_deathDate())).days elif not self._wife.get_deathDate(): deathdays = (date(*self._divorced) - date(*self._husband.get_deathDate())).days if deathdays < 0: return True else: raise Error('ERROR', 'FAMILY', 'US05', self.get_lineNum()["DIV"], f"Family divorce date {self.get_divorcedDate()} is after death date of husband {self._husband.get_deathDate()} or wife {self._wife.get_deathDate()}")
def test_error(self): raise Error("123", 1, 2, 3, 4)
def aunts_and_uncles(self): if (not self._parentFamily): raise AttributeError("missing value") if (not self._parentFamily.get_husband() or not self._parentFamily.get_wife()): raise AttributeError("missing value") if (not self._parentFamily.get_husband().get_parent_family() or not self._parentFamily.get_wife().get_parent_family()): raise AttributeError("missing value") dad_grand_family = self._parentFamily.get_husband().get_parent_family() mom_grand_family = self._parentFamily.get_wife().get_parent_family() for dad_side_aunt_uncle in dad_grand_family.get_children(): if (dad_side_aunt_uncle == self.get_parent_family().get_husband()): continue check_id = dad_side_aunt_uncle.get_id() for dad_side_family in dad_side_aunt_uncle.get_family(): if (not dad_side_family.get_husband() or not dad_side_family.get_wife()): raise AttributeError("missing value") uncle_id = dad_side_family.get_husband().get_id() aunt_id = dad_side_family.get_wife().get_id() if (uncle_id == aunt_id): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US20', dad_side_family.get_husband().get_lineNum()['INDI ID'], f" Individual's Aunt{aunt_id} and Uncle{uncle_id} has the same ID" ) for each_child in dad_side_family.get_children(): if (uncle_id == each_child.get_id() or aunt_id == each_child.get_id()): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US20', dad_side_family.get_husband().get_lineNum() ['INDI ID'], f" Individual's Aunt{aunt_id} or Uncle{uncle_id} is married to their child {each_child.get_id()}" ) for mom_side_aunt_uncle in mom_grand_family.get_children(): if (mom_side_aunt_uncle == self.get_parent_family().get_wife()): continue for mom_side_family in mom_side_aunt_uncle.get_family(): if (not mom_side_family.get_husband() or not mom_side_family.get_wife()): raise AttributeError("missing value") uncle_id = mom_side_family.get_husband().get_id() aunt_id = mom_side_family.get_wife().get_id() if (uncle_id == aunt_id): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US20', mom_side_family.get_husband().get_lineNum()['INDI ID'], f" Individual's Aunt{aunt_id} and Uncle{uncle_id} has the same ID" ) for each_child in mom_side_family.get_children(): if (uncle_id == each_child.get_id() or aunt_id == each_child.get_id()): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US20', mom_side_family.get_husband().get_lineNum() ['INDI ID'], f" Individual's Aunt{aunt_id} or Uncle{uncle_id} is married to their child {each_child.get_id()}" ) return True
def no_bigamy(self): if (len(self._family) <= 1): return True marrageAgeList = [] birthDate = self._birthDate if not self._family: raise AttributeError("Missing self family") for each_marrage in self._family: if not each_marrage.get_marriedDate(): raise AttributeError("Missing marrage date") marrageAge = each_marrage.get_marriedDate()[0] - birthDate[0] + ( each_marrage.get_marriedDate()[1] - birthDate[1]) / 12 + ( each_marrage.get_marriedDate()[2] - birthDate[2]) / 365 devorceAge = None if (each_marrage.get_divorcedDate() is not None): devorceAge = each_marrage.get_divorcedDate()[0] - \ birthDate[ 0] + (each_marrage.get_divorcedDate()[ 1] - birthDate[1]) / 12 + ( each_marrage.get_divorcedDate()[ 2] - birthDate[2]) / 365 for Age_range in marrageAgeList: if (Age_range[1] == devorceAge and devorceAge == None): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US11', self.get_lineNum()['INDI ID'], f" Individual{self.get_id()} has committed bigamy") elif ((not Age_range[1] == devorceAge) and devorceAge == None): if (not (Age_range[0] < marrageAge and Age_range[1] < marrageAge)): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US11', self.get_lineNum()['INDI ID'], f" Individual{self.get_id()} has committed bigamy") elif ((not Age_range[1] == devorceAge) and Age_range[1] == None): if (not (marrageAge < Age_range[0] and devorceAge < Age_range[0])): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US11', self.get_lineNum()['INDI ID'], f" Individual{self.get_id()} has committed bigamy") else: if (marrageAge > Age_range[0] and marrageAge < Age_range[1]): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US11', self.get_lineNum()['INDI ID'], f" Individual{self.get_id()} has committed bigamy") elif (devorceAge > Age_range[0] and devorceAge < Age_range[1]): #return False raise Error( 'ERROR', 'INDIVIDUAL', 'US11', self.get_lineNum()['INDI ID'], f" Individual{self.get_id()} has committed bigamy") marrageAgeList.append((marrageAge, devorceAge)) return True
def test_schedule_resource(): print( "#################### TESTING SCHEDULE RESOURCE ####################" ) # GETTING ALL EVENT_CALLS print("TEST_1 --- GETTING ALL SCHEDULES") uri = "schedules" expected_result = {"schedules": []} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE EVENT_CALL print("TEST_2 --- POSTING ONE SCHEDULE") body = { "time": "18:00:00", "schedule_days": [1, 2, 3], "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 2, "value": 1 }] } schedule_1 = ScheduleModel(datetime.strptime("18:00:00", "%H:%M:%S")) schedule_1_json = schedule_1.to_json() schedule_1_json['id'] = 1 schedule_1_json['url'] = "127.0.0.1:5000/api/v1/schedules/1" schedule_days_1 = ScheduleDayModel(schedule_1_json['id'], 1) schedule_days_1_json = schedule_days_1.to_json() schedule_days_1_json['id'] = 1 schedule_days_2 = ScheduleDayModel(schedule_1_json['id'], 2) schedule_days_2_json = schedule_days_2.to_json() schedule_days_2_json['id'] = 2 schedule_days_3 = ScheduleDayModel(schedule_1_json['id'], 3) schedule_days_3_json = schedule_days_3.to_json() schedule_days_3_json['id'] = 3 schedule_1_json['schedule_days'] = [ schedule_days_1_json, schedule_days_2_json, schedule_days_3_json ] scheduled_usage_1 = ScheduledUsageModel(1, 1, 1) scheduled_usage_1_json = scheduled_usage_1.to_json() scheduled_usage_1_json['id'] = 1 scheduled_usage_2 = ScheduledUsageModel(1, 2, 1) scheduled_usage_2_json = scheduled_usage_2.to_json() scheduled_usage_2_json['id'] = 2 schedule_1_json['scheduled_usages'] = [ scheduled_usage_1_json, scheduled_usage_2_json ] expected_result = schedule_1_json expected_status = 201 uri = "schedules" test_post(uri, body, expected_result, expected_status) # GETTING ALL SCHEDULES print("TEST_3 --- GETTING ALL SCHEDULES") uri = "schedules" expected_result = {"schedules": [schedule_1_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE ITEM print("TEST_4 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "100:00:00", "schedule_days": [1, 2, 3], "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 2, "value": 1 }] } expected_result = { "errors": [ Error("Invalid time format given, expected format is: '12:00:00'", "Invalid time format, expected format is: '%H:%M:%S'", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_5 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "10:00:00", "schedule_days": [], "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 2, "value": 1 }] } expected_result = { "errors": [ Error("No schedule days given.", "Expecting array of days", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_6 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "10:00:00", "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 2, "value": 1 }] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_7 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "10:00:00", "schedule_days": [1, 2, 3], "scheduled_usages": [] } expected_result = { "errors": [ Error("No schedule usages given.", "Expecting array of usages", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_8 --- POSTING ONE SCHEDULE - BAD REQUEST") body = {"time": "10:00:00", "schedule_days": [1, 2, 3]} expected_result = { "errors": [ Error("No schedule usages given.", "Expecting array of usages", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_9 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "10:00:00", "schedule_days": [1, 1, 2, 2], "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 2, "value": 1 }] } expected_result = { "errors": [ Error("Duplicate day entry. {}".format(1), "Duplicate day entry. {}".format(1), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json(), Error("Duplicate day entry. {}".format(2), "Duplicate day entry. {}".format(2), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_10 --- POSTING ONE SCHEDULE - BAD REQUEST") body = { "time": "10:00:00", "schedule_days": [1, 2, 3], "scheduled_usages": [{ "usage_id": 1, "value": 1 }, { "usage_id": 1, "value": 1 }] } expected_result = { "errors": [ Error("Duplicate usage entry. {}".format(1), "Duplicate usage entry. {}".format(1), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "schedules" test_post(uri, body, expected_result, expected_status)
def corresponding_entries(self): """ user story 26 the information in the individual and family records should be consistent.""" for key_id, indi in self._individuals: if indi.get_parentFamily(): flag = False for child in indi.get_parentFamily().get_children(): if child.get_id() == key_id: flag = True if not flag: # return False raise Error( 'ERROR', 'GEDCOM', 'US026', indi.get_parentFamily().get_lineNum()['FAM ID'], f"Individual{indi.get_id()} 's family{indi.get_parentFamily().get_id()} have non-corresponding IDs'" ) for fam in indi.get_family(): if not fam.get_husband() and not fam.get_wife(): # return False raise Error( 'ANOMALY', 'GEDCOM', 'US026', fam.get_lineNum()['FAM ID'], f"Family{fam.get_id()} has no husband or no wife") if not (fam.get_husband().get_id() == key_id or fam.get_wife().get_id() == key_id): # return False raise Error( 'ERROR', 'GEDCOM', 'US026', fam.get_lineNum()['FAM ID'], f"Family{fam.get_id()} has non-corresponding entries") for key_id, fam in self._families: if fam.get_husband(): flag = False for check_fam in fam.get_husband().get_family(): if check_fam.get_id() == key_id: flag = True if not flag: # return False raise Error( 'ERROR', 'GEDCOM', 'US026', fam.get_lineNum()['FAM ID'], f"Family{fam.get_id()} has non-corresponding entries") if fam.get_wife(): flag = False for check_fam in fam.get_wife().get_family(): if check_fam.get_id == key_id: flag = True if not flag: # return False raise Error( 'ERROR', 'GEDCOM', 'US026', fam.get_lineNum()['FAM ID'], f"Family{fam.get_id()} has non-corresponding entries") for child in fam.get_children(): if not child.get_parentFamily(): # return False raise Error( 'ERROR', 'GEDCOM', 'US026', child.get_lineNum()['INDI ID'], f"Individual{child.get_id()}'s family{fam.get_id()} has non-corresponding entries" ) if not child.get_parentFamily().get_id() == key_id: # return False raise Error( 'ERROR', 'GEDCOM', 'US026', child.get_lineNum()['INDI ID'], f"Individual{child.get_id()}'s family{fam.get_id()} has non-corresponding entries" ) return True
def test_group_resource(): print( "#################### TESTING GROUP RESOURCE ####################") # GETTING ALL GROUPS print("TEST_1 --- GETTING ALL GROUPS") uri = "groups" expected_result = {"groups": []} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE GROUP print("TEST_2 --- POSTING ONE GROUP") group_1_name = 'Huiskamer' group_1_is_module = True group_1 = GroupModel(group_1_name, group_1_is_module) body = { "name": group_1_name, "is_module": group_1_is_module, } group_1_json = group_1.to_json() group_1_json['id'] = 1 group_1_json['url'] = "127.0.0.1:5000/api/v1/groups/1" expected_result = group_1_json expected_status = 201 uri = "groups" test_post(uri, body, expected_result, expected_status) # GETTING ALL GROUPS print("TEST_3 --- GETTING ALL GROUPS") uri = "groups" expected_result = {"groups": [group_1_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ONE GROUP print("TEST_4 --- GETTING ONE GROUP") uri = "groups/1" expected_result = group_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # ADDING ONE ITEM TO GROUP print("TEST_5 --- ADDING ONE ITEM TO GROUP") uri = "groups/1/items" item_1_json = send_get('items/1') body = {"item_id": item_1_json['id']} expected_result = group_1_json expected_result['items'] = [{ "id": item_1_json['id'], "name": item_1_json['name'], "comment": item_1_json['comment'], "url": item_1_json['url'] }] expected_status = 200 test_post(uri, body, expected_result, expected_status) group_1_json['items'] = [{ "id": item_1_json['id'], "name": item_1_json['name'], "comment": item_1_json['comment'], "url": item_1_json['url'] }] # GETTING ONE GROUP print("TEST_6 --- GETTING ONE GROUP") uri = "groups/1" expected_result = group_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE GROUP print("TEST_7 --- POSTING ONE GROUP") group_2_name = 'Verlichting' group_2_is_module = False group_2 = GroupModel(group_2_name, group_2_is_module) body = { "name": group_2_name, "is_module": group_2_is_module, } group_2_json = group_2.to_json() group_2_json['id'] = 2 group_2_json['url'] = "127.0.0.1:5000/api/v1/groups/2" expected_result = group_2_json expected_status = 201 uri = "groups" test_post(uri, body, expected_result, expected_status) # POSTING ONE GROUP print("TEST_8 --- POSTING ONE GROUP") group_3_name = 'Badkamer' group_3_is_module = True group_3 = GroupModel(group_3_name, group_3_is_module) body = { "name": group_3_name, "is_module": group_3_is_module, } group_3_json = group_3.to_json() group_3_json['id'] = 3 group_3_json['url'] = "127.0.0.1:5000/api/v1/groups/3" expected_result = group_3_json expected_status = 201 uri = "groups" test_post(uri, body, expected_result, expected_status) # ADDING ONE ITEM TO GROUP print("TEST_9 --- ADDING ONE ITEM TO GROUP") uri = "groups/2/items" item_1_json = send_get('items/1') body = {"item_id": item_1_json['id']} expected_result = group_2_json expected_result['items'] = [{ "id": item_1_json['id'], "name": item_1_json['name'], "comment": item_1_json['comment'], "url": item_1_json['url'] }] expected_status = 200 test_post(uri, body, expected_result, expected_status) group_2_json['items'] = [{ "id": item_1_json['id'], "name": item_1_json['name'], "comment": item_1_json['comment'], "url": item_1_json['url'] }] # ADDING ONE ITEM TO GROUP print("TEST_10 --- ADDING ONE ITEM TO SECOND MODULE") uri = "groups/3/items" item_1_json = send_get('items/1') body = {"item_id": item_1_json['id']} error = Error("Item cannot be in two different modules", "item.is_in_module() returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422") expected_result = {"errors": [error.to_json()]} expected_status = 422 test_post(uri, body, expected_result, expected_status) # GETTING ONE ITEM print("TEST_11 --- GETTING ONE ITEM") uri = "items/1" expected_result = { "id": 1, "name": 'Z04 Gang lamp (SW)', "comment": 'new_comment', "last_use": None, "usages": [], "url": "127.0.0.1:5000/api/v1/items/1", "groups": [{ "id": 1, "name": 'Huiskamer' }, { "id": 2, "name": 'Verlichting' }] } expected_status = 200 test_get(uri, expected_result, expected_status) # ADDING ONE ITEM TO GROUP print("TEST_12 --- REMOVING ONE ITEM FROM GROUP") uri = "groups/1/items/1" item_1_json = send_get('items/1') body = {"item_id": item_1_json['id']} expected_result = group_1_json expected_result['items'] = [] expected_status = 200 test_delete(uri, body, expected_result, expected_status) group_1_json['items'] = [] # GETTING ONE GROUP print("TEST_13 --- GETTING ONE GROUP") uri = "groups/1" expected_result = group_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # ADDING ONE ITEM TO NON EXISTING GROUP print("TEST_14 --- ADDING ITEM TO NON EXISTING GROUP") uri = "groups/5/items" item_1_json = send_get('items/1') body = {"item_id": item_1_json['id']} error = Error("Could not find group with id: {}".format(5), "GroupModel.find_by_id({}) returned None".format(5), 404, "https://en.wikipedia.org/wiki/HTTP_404") expected_result = {"errors": [error.to_json()]} expected_status = 422 test_post(uri, body, expected_result, expected_status) group_1_json['items'] = [] # POSTING ONE GROUP print("TEST_15 --- POSTING ONE GROUP - BAD REQUEST") group_3_name = 'Badkamer _____________________________________________________________________' \ '______________________________________________________________________________' \ '______________________________________________________________________________' \ '______________________________________________________________________________' group_3_is_module = True body = { "name": group_3_name, "is_module": group_3_is_module, } error = Error("Name cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400") expected_result = {"errors": [error.to_json()]} expected_status = 400 uri = "groups" test_post(uri, body, expected_result, expected_status) # DELETING ONE GROUP print("TEST_16 --- DELETING ONE GROUP") uri = "groups/3" body = {} expected_result = "Group with id: {} was successfully deleted.".format(3) expected_status = 200 test_delete(uri, body, expected_result, expected_status) # CHECKING IF GROUP WAS DELETED print("TEST_17 --- GETTING ALL GROUPS") uri = "groups" expected_result = {"groups": [group_1_json, group_2_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # ADDING ONE ITEM TO GROUP print("TEST_18 --- ADDING ONE ITEM TO GROUP") uri = "groups/1/items" item_2_json = send_get('items/2') body = {"item_id": 2} expected_result = group_1_json expected_result['items'] = [{ "id": item_2_json['id'], "name": item_2_json['name'], "comment": item_2_json['comment'], "url": item_2_json['url'] }] expected_status = 200 test_post(uri, body, expected_result, expected_status) group_1_json['items'] = [{ "id": item_2_json['id'], "name": item_2_json['name'], "comment": item_2_json['comment'], "url": item_2_json['url'] }]
def test_event_resource(): print("#################### TESTING EVENT RESOURCE ####################") # GETTING ALL USAGES print("TEST_1 --- GETTING ALL EVENTS") uri = "events" expected_result = { "events": [] } expected_status = 200 test_get(uri, expected_result, expected_status) # POST ONE EVENT print("TEST_2 --- POSTING ONE EVENT") uri = "events" usage_1 = send_get('usages/1') event_1 = EventModel(usage_1['id'], 'True', round(datetime.now().timestamp())) event_1_json = event_1.to_json() event_1_json['id'] = 1 body = { "usage_id": usage_1['id'], "data_type": UnitEnum.TOGGLE.value, "data": 'True' } expected_result = event_1_json expected_status = 201 test_post(uri, body, expected_result, expected_status) # GETTING ONE EVENT print("TEST_3 --- GETTING ONE EVENT") uri = "events/1" expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ALL EVENTS print("TEST_4 --- GETTING ALL EVENTS") uri = "events" expected_result = { "events": [event_1_json] } expected_status = 200 test_get(uri, expected_result, expected_status) # POST ONE EVENT print("TEST_5 --- POSTING ONE EVENT - BAD REQUEST") uri = "events" body = { "usage_id": 17, "data_type": UnitEnum.TOGGLE.value, "data": 'True' } error = Error( "Cannot find usage with id: {}".format(17), "UsageModel.find_by_id({}) returns None".format(17), 404, "https://en.wikipedia.org/wiki/HTTP_404") expected_result = {"errors": [error.to_json()]} expected_status = 422 test_post(uri, body, expected_result, expected_status) # POST ONE EVENT print("TEST_6 --- POSTING ONE EVENT - BAD REQUEST") uri = "events" body = { "usage_id": 1, "data_type": "KILO WHAT?", "data": 'True' } error = Error( '"{}" is not a valid unit type.'.format("KILO WHAT?"), "UnitEnum.has_value({}) returned False".format("KILO WHAT?"), 400, "https://en.wikipedia.org/wiki/HTTP_400" ) expected_result = {"errors": [error.to_json()]} expected_status = 422 test_post(uri, body, expected_result, expected_status)
def validate(**kwargs): errors = [] item = None usage = None group = None preset = None schedule = None scheduled_usage = None method = None if "method" in kwargs: method = kwargs.pop('method') # ITEM if "item_id" in kwargs: item_id = kwargs.pop("item_id") item = ItemModel.find_by_id(item_id) if item is None: errors.append( Error("Could not find item with id: {}".format(item_id), "ItemMode.find_by_id({}) returned None".format(item_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) if "item_name" in kwargs: item_name = kwargs.pop("item_name") if len(item_name) < 3: errors.append( Error("Name must be at least 3 characters long.", "Name parameter must be at least 3 characters long.", 400, "https://en.wikipedia.org/wiki/HTTP_400")) elif len(item_name) > 255: errors.append( Error("Name cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400")) if "item_comment" in kwargs: item_comment = kwargs.pop('item_comment') if len(item_comment) > 255: errors.append( Error("Comment cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400")) # USAGE if "usage_id" in kwargs: usage_id = kwargs.pop('usage_id') usage = UsageModel.find_by_id(usage_id) if usage is None: errors.append( Error( "Could not find usage with id: {}".format(usage_id), "UsageModel.find_by_id({}) returned None".format(usage_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) elif item is not None: if not item.has_usage(usage_id): errors.append( Error( "Item with id {} does not have usage with id: {}". format(item.id, usage_id), "UsageModel.find_by_id({}) returned None".format( usage_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) if "usage_value" in kwargs: usage_value = kwargs.pop("usage_value") if usage is None: pass elif usage_value < usage.min_value or usage_value > usage.max_value: errors.append( Error( "Given value is not in range of Usage values. ({} - {}) ({} given)" .format(usage.min_value, usage.max_value, usage_value), "value is not within range. ({} - {}) ({} given)".format( usage.min_value, usage.max_value, usage_value), 422, "https://en.wikipedia.org/wiki/HTTP_404")) if "usage_consumption_type" in kwargs: usage_consumption_type = kwargs.pop('usage_consumption_type') if not UsageTypeEnum.has_value(usage_consumption_type): errors.append( Error( "{} is not a valid consumption type.".format( usage_consumption_type), "UsageTypeEnum.has_value({}) returned False".format( usage_consumption_type), 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "usage_unit" in kwargs: usage_unit = kwargs.pop('usage_unit') if not UnitEnum.has_value(usage_unit): errors.append( Error( "{} is not a valid unit option.".format(usage_unit), "UnitEnum.has_value({}) returned False".format(usage_unit), 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "usage_address" in kwargs: usage_address = kwargs.pop('usage_address') if len(usage_address) < 3: errors.append( Error( "Address must be at least 4 characters long.", "address was {} characters long".format( len(usage_address)), 422, "https://en.wikipedia.org/wiki/HTTP_422")) if len(usage_address) > 255: errors.append( Error( "Address cannot be longer than 255 characters.", "address was {} characters long".format( len(usage_address)), 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "usage_consumption_amount" in kwargs: usage_consumption_amount = kwargs.pop("usage_consumption_amount") if usage_consumption_amount < 0: errors.append( Error("Consumption amount cannot be below 0.", "{} is below 0".format(usage_consumption_amount), 422, "https://en.wikipedia.org/wiki/HTTP_422")) usage_min_value = None if "usage_min_value" in kwargs: usage_min_value = kwargs.pop("usage_min_value") usage_max_value = None if "usage_max_value" in kwargs: usage_max_value = kwargs.pop("usage_max_value") if (usage_min_value is None and usage_max_value is not None) or \ (usage_min_value is not None and usage_max_value is None): errors.append( Error("If either min or max value is given, both should be given.", "Either min or max was None while the other was not.", 422, "https://en.wikipedia.org/wiki/HTTP_422")) elif usage_min_value is not None and usage_max_value is not None: if usage_min_value > usage_max_value: errors.append( Error("Min value should be lower than max value", "min_value is higher than max_value", 422, "https://en.wikipedia.org/wiki/HTTP_422")) # GROUP if "group_id" in kwargs: group_id = kwargs.pop("group_id") group = GroupModel.find_by_id(group_id) if group is None: errors.append( Error( "Could not find group with id: {}".format(group_id), "GroupModel.find_by_id({}) returned None".format(group_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) if "group_name" in kwargs: group_name = kwargs.pop("group_name") if len(group_name) < 3: errors.append( Error("Name must be at least 3 characters long.", "Name parameter must be at least 3 characters long.", 400, "https://en.wikipedia.org/wiki/HTTP_400")) elif len(group_name) > 255: errors.append( Error("Name cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400")) # PRESET if "preset_id" in kwargs: preset_id = kwargs.pop("preset_id") preset = PresetModel.find_by_id(preset_id) if preset is None: errors.append( Error( "Could not find preset with id: {}".format(preset_id), "PresetModel.find_by_id({}) returned None".format( preset_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) elif preset.group_id != group.id: errors.append( Error("The given group id did not match the presets group id", "preset.group_id != group.id", 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "preset_name" in kwargs: preset_name = kwargs.pop("preset_name") if len(preset_name) < 3: errors.append( Error("Name must be at least 3 characters long.", "len(preset_name) < 3 returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422")) if len(preset_name) > 30: errors.append( Error("Name cannot be longer than 30 characters.", "len(preset_name) > 30 returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422")) # PRESET_ACTION if "preset_action_id" in kwargs: preset_action_id = kwargs.pop("preset_action_id") preset_action = PresetActionModel.find_by_id(preset_action_id) if preset_action is None: errors.append( Error( "Could not find preset action with id: {}".format( preset_action_id), "PresetActionModel.find_by_id({}) returned None".format( preset_action_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) elif preset is not None: if preset_action.preset_id != preset.id: errors.append( Error( "The given preset id did not match the presets actions preset id", "preset_action.preset_id != preset.id", 422, "https://en.wikipedia.org/wiki/HTTP_422")) # SCHEDULE if "schedule_id" in kwargs: schedule_id = kwargs.pop("schedule_id") schedule = ScheduleModel.find_by_id(schedule_id) if schedule is None: errors.append( Error( "Could not find schedule with id: ".format(schedule_id), "ScheduleModel.find_by_id({}) returned None".format( schedule_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) if "schedule_time" in kwargs: schedule_time = kwargs.pop("schedule_time") if len(schedule_time) != 8 or not datetime.strptime( schedule_time, "%H:%M:%S"): errors.append( Error( "Invalid time format given, expected format is: '12:00:00'", "Invalid time format, expected format is: '%H:%M:%S'", 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "schedule_days" in kwargs: schedule_days = kwargs.pop("schedule_days") if len(schedule_days) < 1: errors.append( Error("No schedule days given.", "Expecting array of days", 422, "https://en.wikipedia.org/wiki/HTTP_422")) else: seen_values = [] for schedule_day in schedule_days: if int(schedule_day) < 0 or int(schedule_day) > 6: errors.append( Error( "day should be in range 0 - 6, {} given".format( int(schedule_day)), "day should be in range 0 - 6, {} given".format( int(schedule_day)), 422, "https://en.wikipedia.org/wiki/HTTP_422")) if schedule_day in seen_values: errors.append( Error("Duplicate day entry. {}".format(schedule_day), "Duplicate day entry. {}".format(schedule_day), 422, "https://en.wikipedia.org/wiki/HTTP_422")) seen_values.append(schedule_day) if "schedule_usages" in kwargs: schedule_usages = kwargs.pop("schedule_usages") if len(schedule_usages) < 1: errors.append( Error("No schedule usages given.", "Expecting array of usages", 422, "https://en.wikipedia.org/wiki/HTTP_422")) seen_values = [] for scheduled_usage in schedule_usages: if scheduled_usage['usage_id'] is None: errors.append( Error("Missing usage_id for a scheduled usage.", "Missing usage_id for a scheduled usage.", 422, "https://en.wikipedia.org/wiki/HTTP_422")) else: _usage = UsageModel.find_by_id(scheduled_usage['usage_id']) if _usage is None: errors.append( Error( "Could not find item with id: ".format(usage_id), "UsageModel.find_by_id({}) returned None".format( usage_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) else: scheduled_usage_value = scheduled_usage['value'] if scheduled_usage_value < _usage.min_value or scheduled_usage_value > _usage.max_value: errors.append( Error( "Given value is not in range of Usage values. ({} - {}) ({} given}" .format(_usage.min_value, _usage.max_value, scheduled_usage_value), "value is not within range. ({} - {}) ({} given}" .format(_usage.min_value, _usage.max_value, scheduled_usage_value), 422, "https://en.wikipedia.org/wiki/HTTP_404")) if scheduled_usage['usage_id'] in seen_values: errors.append( Error( "Duplicate usage entry. {}".format( scheduled_usage['usage_id']), "Duplicate usage entry. {}".format( scheduled_usage['usage_id']), 422, "https://en.wikipedia.org/wiki/HTTP_422")) seen_values.append(scheduled_usage['usage_id']) if "schedule_day_number" in kwargs: schedule_day_number = kwargs.pop("schedule_day_number") if schedule is None: pass else: for schedule_day in schedule.schedule_days: if schedule_day.day == schedule_day_number: errors.append( Error( "Given day ({}) is already being used by this schedule." .format(schedule_day_number), "Given day ({}) is already being used by this schedule." .format(schedule_day_number), 422, "https://en.wikipedia.org/wiki/HTTP_404")) if "schedule_day_id" in kwargs: schedule_day_id = kwargs.pop("schedule_day_id") schedule_day = ScheduleDayModel.find_by_id(schedule_day_id) if schedule_day is None: errors.append( Error( "Could not find schedule day with id: ".format( schedule_day_id), "ScheduleDayModel.find_by_id({}) returned None".format( schedule_day_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) if schedule is None: pass elif schedule.id != schedule_day.schedule_id: errors.append( Error( "The given schedule id did not match the days schedule id", "schedule.id != schedule_day.schedule_id", 422, "https://en.wikipedia.org/wiki/HTTP_422")) # SCHEDULED USAGE if "scheduled_usage_id" in kwargs: scheduled_usage_id = kwargs.pop("scheduled_usage_id") scheduled_usage = ScheduledUsageModel.find_by_id(scheduled_usage_id) if scheduled_usage is None: errors.append( Error( "Could not find scheduled usage with id: ".format( scheduled_usage_id), "ScheduledUsageModel.find_by_id({}) returned None".format( scheduled_usage_id), 404, "https://en.wikipedia.org/wiki/HTTP_404")) elif scheduled_usage.schedule_id != schedule.id: errors.append( Error( "The given schedule id did not match the scheduled usage schedule id", "scheduled_usage.schedule_id != schedule.id", 422, "https://en.wikipedia.org/wiki/HTTP_422")) if "scheduled_usage_value" in kwargs: scheduled_usage_value = kwargs.pop("scheduled_usage_value") if scheduled_usage is not None: _usage = UsageModel.find_by_id(scheduled_usage.usage_id) if _usage.min_value > scheduled_usage_value or _usage.max_value < scheduled_usage_value: errors.append( Error( "Given value is not in range of Usage values. ({} - {}) ({} given}" .format(_usage.min_value, _usage.max_value, scheduled_usage_value), "value is not within range. ({} - {}) ({} given}". format(_usage.min_value, _usage.max_value, scheduled_usage_value), 422, "https://en.wikipedia.org/wiki/HTTP_404")) # METHOD SPECIFIC if method == "GroupItemResource.get": if item is None or group is None: pass elif not item.is_in_this_group(group.id): errors.append( Error( "Item with id {} is not in group with id {}".format( item.id, group.id), "item.is_in_this_group({}) returned False".format( group.id), 422, "https://en.wikipedia.org/wiki/HTTP_422")) elif method == "GroupItemsResource.post": if item is None or group is None: pass elif item.is_in_this_group(group.id): errors.append( Error( "Item with id {} is already in group with id {}".format( item.id, group.id), "item is already in this group", 422, "https://en.wikipedia.org/wiki/HTTP_422")) elif group.is_module is True: if item.is_in_module(): errors.append( Error("Item cannot be in two different modules", "item.is_in_module() returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422")) elif method == "GroupItemResource.delete": if item is None or group is None: pass elif not item.is_in_this_group(group.id): errors.append( Error( "Item with id {} is not in group with id {}".format( item.id, group.id), "item.is_in_this_group({}) returned False".format( group.id), 400, "https://en.wikipedia.org/wiki/HTTP_400")) elif method == "PresetActionsResource.post": if (group is not None) and (usage is not None): usage_is_in_group = False for item in group.items: if item.id == usage.item_id: usage_is_in_group = True if not usage_is_in_group: errors.append( Error( "The item that usage with id {} is attached to does not belong to group with id {}." .format(usage.id, group.id), "Usage is not in this group", 422, "https://en.wikipedia.org/wiki/HTTP_422")) elif method == "ScheduledUsagesResource.post": if schedule is None or usage is None: pass else: for scheduled_usage in schedule.scheduled_usages: if scheduled_usage.usage_id == usage.id: errors.append( Error( "Given usage id is already being used by this schedule", "usage id already in schedule", 422, "https://en.wikipedia.org/wiki/HTTP_422")) assert len(kwargs) == 0, kwargs return errors
def test_presets_resource(): print( "#################### TESTING PRESETS RESOURCE ####################" ) # GETTING ALL PRESETS print("TEST_1 --- GETTING ALL PRESETS") uri = "groups/1/presets" expected_result = {"presets": []} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE PRESET print("TEST_2 --- POSTING ONE PRESET") preset_1_group_id = 1 preset_1_name = "name" body = { "name": preset_1_name, } preset_1 = PresetModel(preset_1_group_id, preset_1_name) preset_1_json = preset_1.to_json() preset_1_json['id'] = 1 preset_1_json['url'] = "127.0.0.1:5000/api/v1/groups/1/presets/1" expected_result = preset_1_json expected_status = 201 uri = "groups/{}/presets".format(preset_1_group_id) test_post(uri, body, expected_result, expected_status) # POSTING ONE PRESET print("TEST_3 --- POSTING ONE PRESET - BAD REQUEST") body = { "name": "na", } expected_result = { "errors": [ Error("Name must be at least 3 characters long.", "len(preset_name) < 3 returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "groups/{}/presets".format(preset_1_group_id) test_post(uri, body, expected_result, expected_status) # POSTING ONE PRESET print("TEST_4 --- POSTING ONE PRESET - BAD REQUEST") body = { "name": "namenamenamenamenamenamenamenamenamename", } expected_result = { "errors": [ Error("Name cannot be longer than 30 characters.", "len(preset_name) > 30 returned True", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json() ] } expected_status = 422 uri = "groups/{}/presets".format(preset_1_group_id) test_post(uri, body, expected_result, expected_status) # GETTING ALL PRESETS print("TEST_5 --- GETTING ALL PRESETS") uri = "groups/{}/presets".format(preset_1_group_id) expected_result = {"presets": [preset_1_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE PRESET print("TEST_6 --- POSTING ONE PRESET") preset_2_group_id = 1 preset_2_name = "preset_22" body = { "name": preset_2_name, } preset_2 = PresetModel(preset_2_group_id, preset_2_name) preset_2_json = preset_2.to_json() preset_2_json['id'] = 2 preset_2_json['url'] = "127.0.0.1:5000/api/v1/groups/1/presets/2" expected_result = preset_2_json expected_status = 201 uri = "groups/{}/presets".format(preset_2_group_id) test_post(uri, body, expected_result, expected_status) # GETTING ALL PRESETS print("TEST_7 --- GETTING ALL PRESETS") uri = "groups/{}/presets".format(preset_1_group_id) expected_result = {"presets": [preset_1_json, preset_2_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # DELETING ONE PRESET print("TEST_8 --- DELETING ONE PRESET") uri = "groups/{}/presets/{}".format(preset_1_group_id, preset_2_json['id']) expected_result = "Preset with id: {} was successfully deleted.".format( preset_2_json['id']) expected_status = 200 test_delete(uri, {}, expected_result, expected_status) # GETTING ALL PRESETS print("TEST_9 --- GETTING ALL PRESETS") uri = "groups/{}/presets".format(preset_1_group_id) expected_result = {"presets": [preset_1_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # UPDATING ONE PRESET print("TEST_10 --- UPDATING ONE PRESET") uri = "groups/{}/presets/{}".format(preset_1_group_id, preset_1_json['id']) body = {"name": "preset_1"} preset_1_json['name'] = "preset_1" expected_status = 200 test_put(uri, body, preset_1_json, expected_status) # GETTING ALL PRESETS print("TEST_11 --- GETTING ALL PRESETS") uri = "groups/{}/presets".format(preset_1_group_id) expected_result = {"presets": [preset_1_json]} expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE PRESET print("TEST_12 --- POSTING ONE PRESET") preset_3_group_id = 2 preset_3_name = "preset_3" body = { "name": preset_3_name, } preset_3 = PresetModel(preset_3_group_id, preset_3_name) preset_3_json = preset_3.to_json() preset_3_json['id'] = 3 preset_3_json['url'] = "127.0.0.1:5000/api/v1/groups/2/presets/3" expected_result = preset_3_json expected_status = 201 uri = "groups/{}/presets".format(preset_3_group_id) test_post(uri, body, expected_result, expected_status)
def test_preset_actions_resource(): print("#################### TESTING PRESET_ACTIONS RESOURCE ####################") uri = "groups/2/presets/3" preset_3 = send_get(uri) # GETTING ALL PRESET_ACTIONS print("TEST_1 --- GETTING ALL PRESETS_ACTIONS") uri = "groups/{}/presets/{}/preset_actions".format(preset_3['group_id'], preset_3['id']) expected_result = { "preset_actions": [] } expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE PRESET_ACTION print("TEST_2 --- POSTING ONE PRESET ACTION") preset_action_1_usage_id = 1 preset_action_1_value = 0 body = { "usage_id": preset_action_1_usage_id, "value": preset_action_1_value } preset_action_1 = PresetActionModel(preset_3['id'], preset_action_1_usage_id, preset_action_1_value) preset_action_1_json = preset_action_1.to_json() preset_action_1_json['id'] = 1 expected_result = preset_action_1_json expected_status = 201 uri = "groups/{}/presets/{}/preset_actions".format(preset_3['group_id'], preset_3['id']) test_post(uri, body, expected_result, expected_status) # POSTING ONE PRESET_ACTION print("TEST_3 --- POSTING ONE PRESET ACTION - BAD REQUEST") body = { "usage_id": 2, "value": preset_action_1_value } expected_result = {"errors": [Error( "The item that usage with id {} is attached to does not belong to group with id {}." .format(body['usage_id'], preset_3['group_id']), "Usage is not in this group", 422, "https://en.wikipedia.org/wiki/HTTP_422" ).to_json()]} expected_status = 422 uri = "groups/{}/presets/{}/preset_actions".format(preset_3['group_id'], preset_3['id']) test_post(uri, body, expected_result, expected_status) # POSTING ONE PRESET_ACTION print("TEST_4 --- POSTING ONE PRESET ACTION - BAD REQUEST") body = { "usage_id": 1, "value": 2 } expected_result = {"errors": [ Error( "Given value is not in range of Usage values. (0 - 1) (2 given)", "value is not within range. (0 - 1) (2 given)", 422, "https://en.wikipedia.org/wiki/HTTP_404" ).to_json() ]} expected_status = 422 uri = "groups/{}/presets/{}/preset_actions".format(preset_3['group_id'], preset_3['id']) test_post(uri, body, expected_result, expected_status) # GETTING ALL PRESET_ACTIONS print("TEST_5 --- GETTING ALL PRESETS_ACTIONS") uri = "groups/{}/presets/{}/preset_actions".format(preset_3['group_id'], preset_3['id']) expected_result = { "preset_actions": [preset_action_1_json] } expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ONE PRESET_ACTION print("TEST_6 --- GETTING ONE PRESETS_ACTION") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], preset_action_1_json['id']) expected_result = preset_action_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ONE PRESET_ACTION print("TEST_7 --- GETTING ONE PRESETS_ACTION - BAD REQUEST") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], 2) expected_result = {"errors": [Error( "Could not find preset action with id: {}".format(2), "PresetActionModel.find_by_id({}) returned None".format(2), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 test_get(uri, expected_result, expected_status) # PUTTING ONE PRESET_ACTION print("TEST_8 --- PUTTING ONE PRESET_ACTION - BAD REQUEST") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], 2) expected_result = {"errors": [Error( "Could not find preset action with id: {}".format(2), "PresetActionModel.find_by_id({}) returned None".format(2), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 body = { "usage_id": 1, "value": 0 } test_put(uri, body, expected_result, expected_status) # PUTTING ONE PRESET_ACTION print("TEST_9 --- PUTTING ONE PRESET_ACTION - BAD REQUEST") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], 2, 1) expected_result = {"errors": [Error( "Could not find preset with id: {}".format(2), "PresetModel.find_by_id({}) returned None".format(2), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 body = { "usage_id": 1, "value": 0 } test_put(uri, body, expected_result, expected_status) # PUTTING ONE PRESET_ACTION print("TEST_10 --- PUTTING ONE PRESET_ACTION - BAD REQUEST") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], 1) expected_result = {"errors": [Error( "Could not find usage with id: {}".format(15), "UsageModel.find_by_id({}) returned None".format(15), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 body = { "usage_id": 15, "value": 0 } test_put(uri, body, expected_result, expected_status) # PUTTING ONE PRESET_ACTION print("TEST_11 --- PUTTING ONE PRESET_ACTION - BAD REQUEST") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], 1) expected_result = {"errors": [Error( "Given value is not in range of Usage values. ({} - {}) ({} given)".format( 0, 1, 200), "value is not within range. ({} - {}) ({} given)".format( 0, 1, 200), 422, "https://en.wikipedia.org/wiki/HTTP_404" ).to_json()]} expected_status = 422 body = { "usage_id": 1, "value": 200 } test_put(uri, body, expected_result, expected_status) # PUTTING ONE PRESET_ACTION print("TEST_12 --- PUTTING ONE PRESET_ACTION") uri = "groups/{}/presets/{}/preset_actions/{}"\ .format(preset_3['group_id'], preset_3['id'], 1) preset_action_1_json['value'] = 0 expected_result = preset_action_1_json expected_status = 200 body = { "usage_id": 1, "value": 0 } test_put(uri, body, expected_result, expected_status) # GETTING ALL PRESET_ACTIONS print("TEST_13 --- GETTING ALL PRESET_ACTIONS") uri = "groups/{}/presets/{}/preset_actions"\ .format(preset_3['group_id'], preset_3['id']) expected_result = {"preset_actions": [ preset_action_1_json ]} expected_status = 200 test_get(uri, expected_result, expected_status) print("TEST_14 --- POSTING ONE PRESET ACTION") preset_action_2_usage_id = 2 preset_action_2_value = 1 body = { "usage_id": preset_action_2_usage_id, "value": preset_action_2_value } preset_action_2 = PresetActionModel(1, preset_action_2_usage_id, preset_action_2_value) preset_action_2_json = preset_action_2.to_json() preset_action_2_json['id'] = 2 expected_result = preset_action_2_json expected_status = 201 uri = "groups/1/presets/1/preset_actions" test_post(uri, body, expected_result, expected_status) # GETTING ALL PRESET_ACTIONS print("TEST_15 --- GETTING ALL PRESET_ACTIONS") uri = "groups/{}/presets/{}/preset_actions"\ .format(preset_3['group_id'], preset_3['id']) expected_result = { "preset_actions": [ preset_action_1_json ] } expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ALL PRESET_ACTIONS print("TEST_16 --- GETTING ALL PRESET_ACTIONS") uri = "groups/1/presets/1/preset_actions" expected_result = { "preset_actions": [ preset_action_2_json ] } expected_status = 200 test_get(uri, expected_result, expected_status) # DELETING ONE PRESET_ACTION print("TEST_17 --- GETTING ALL PRESET_ACTIONS - BAD REQUEST") uri = "groups/1/presets/1/preset_actions/12" expected_result = {"errors": [Error( "Could not find preset action with id: {}".format(12), "PresetActionModel.find_by_id({}) returned None".format(12), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 test_delete(uri, {}, expected_result, expected_status) # DELETING ONE PRESET_ACTION print("TEST_18 --- GETTING ALL PRESET_ACTIONS - BAD REQUEST") uri = "groups/1/presets/2/preset_actions/2" expected_result = {"errors": [Error( "Could not find preset with id: {}".format(2), "PresetModel.find_by_id({}) returned None".format(2), 404, "https://en.wikipedia.org/wiki/HTTP_404").to_json()]} expected_status = 422 test_delete(uri, {}, expected_result, expected_status) # DELETING ONE PRESET_ACTION print("TEST_19 --- GETTING ALL PRESET_ACTIONS - BAD REQUEST") uri = "groups/1/presets/1/preset_actions/2" expected_result = "Preset action with id: 2 was successfully deleted." expected_status = 200 test_delete(uri, {}, expected_result, expected_status)
def test_usage_resource(): print("#################### TESTING USAGE RESOURCE ####################") # GETTING ALL USAGES print("TEST_1 --- GETTING ALL USAGES") uri = "usages" expected_result = { "usages": [] } expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE USAGE print("TEST_2 --- POSTING ONE USAGE") item_1 = send_get('items/1') usage_1_item_id = item_1['id'] usage_1_external_item_id = 1 usage_1_consumption_type = UsageTypeEnum.KILOWATT usage_1_consumption_amount = 5 usage_1_address = "http://127.0.0.1:5000/usages/1" usage_1_unit = UnitEnum.TOGGLE usage_1_min_value = 0 usage_1_max_value = 1 usage_1 = UsageModel(usage_1_item_id, usage_1_external_item_id, usage_1_consumption_type, usage_1_consumption_amount, usage_1_address, usage_1_unit, usage_1_min_value, usage_1_max_value) body = { "item_id": usage_1_item_id, "external_item_id": usage_1_external_item_id, "consumption_type": usage_1_consumption_type.value, "consumption_amount": usage_1_consumption_amount, "address": usage_1_address, "unit": "TOGGLE", "min_value": usage_1_min_value, "max_value": usage_1_max_value } usage_1_json = usage_1.to_json() usage_1_json['id'] = 1 usage_1_json['url'] = "127.0.0.1:5000/api/v1/usages/1" expected_result = usage_1_json expected_status = 201 uri = "usages" test_post(uri, body, expected_result, expected_status) # GETTING ALL USAGES print("TEST_3 --- GETTING ALL USAGES") uri = "usages" expected_result = { "usages": [usage_1_json] } expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ONE USAGE print("TEST_4 --- GETTING ONE USAGE") uri = "usages/1" expected_result = usage_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # UPDATING ONE USAGE print("TEST_5 --- UPDATING ONE USAGE") uri = 'usages/1' expected_result = usage_1_json expected_result['address'] = '127.0.0.1:5000/api/usages/7' body = expected_result expected_status = 200 test_put(uri, body, expected_result, expected_status) usage_1_json['address'] = '127.0.0.1:5000/api/usages/7' # GETTING ONE USAGE print("TEST_6 --- GETTING ONE USAGE") uri = "usages/1" expected_result = usage_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_7 --- POSTING ONE USAGE - BAD REQUEST") item_1 = send_get('items/1') usage_1_item_id = item_1['id'] usage_1_external_item_id = item_1['id'] usage_1_consumption_type = UsageTypeEnum.KILOWATT usage_1_consumption_amount = 5 usage_1_address = "http://127.0.0.1:5000/usage/1" usage_1_min_value = 0 usage_1_max_value = 1 body = { "item_id": usage_1_item_id, "external_item_id": usage_1_external_item_id, "consumption_type": usage_1_consumption_type.value, "consumption_amount": usage_1_consumption_amount, "address": usage_1_address, "unit": "FOGGLE", "min_value": usage_1_min_value, "max_value": usage_1_max_value } expected_result = {"errors": [Error( "{} is not a valid unit option.".format("FOGGLE"), "UnitEnum.has_value({}) returned False".format("FOGGLE"), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_8 --- POSTING ONE USAGE - BAD REQUEST") body['unit'] = usage_1_unit.value body['consumption_type'] = 'KILO WHAT?' expected_result = {"errors": [Error( "{} is not a valid consumption type.".format("KILO WHAT?"), "UsageTypeEnum.has_value({}) returned False".format("KILO WHAT?"), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_9 --- POSTING ONE USAGE - BAD REQUEST") body['consumption_type'] = usage_1_consumption_type.value body['address'] = '12' expected_result = {"errors": [Error( "Address must be at least 4 characters long.", "address was {} characters long".format(len(body['address'])), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_10 --- POSTING ONE USAGE - BAD REQUEST") body['address'] = "________________________________________________________________________________________" \ "________________________________________________________________________________________" \ "________________________________________________________________________________________" \ "________________________________________________________________________________________" \ "________________________________________________________________________________________" \ "________________________________________________________________________________________" \ "________________________________________________________________________________________" expected_result = {"errors": [Error( "Address cannot be longer than 255 characters.", "address was {} characters long".format(len(body['address'])), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_11 --- POSTING ONE USAGE - BAD REQUEST") body['address'] = usage_1_address body['consumption_amount'] = -1 expected_result = {"errors": [Error( "Consumption amount cannot be below 0.", "{} is below 0".format(-1), 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_12 --- POSTING ONE USAGE - BAD REQUEST") body['consumption_amount'] = usage_1_consumption_amount body['min_value'] = None expected_result = {"errors": [Error( "If either min or max value is given, both should be given.", "Either min or max was None while the other was not.", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # POSTING ONE USAGE - BAD REQUEST print("TEST_13 --- POSTING ONE USAGE - BAD REQUEST") body['min_value'] = usage_1_min_value body['max_value'] = None expected_result = {"errors": [Error( "If either min or max value is given, both should be given.", "Either min or max was None while the other was not.", 422, "https://en.wikipedia.org/wiki/HTTP_422").to_json()]} expected_status = 422 uri = "usages" test_post(uri, body, expected_result, expected_status) # EXECUTING COMMAND - BAD REQUEST print("TEST 14 --- POSTING COMMAND - BAD REQUEST") body = {} uri = "usages/1/command/2" expected_result = {"errors": Error( "New value does not fall within the expected range. ({} - {})" .format(usage_1_json["min_value"], usage_1_json['max_value']), "{} is outside of ({} - {})".format(2, usage_1_json["min_value"], usage_1_json['max_value']), 422, "" ).to_json()} expected_status = 422 test_patch(uri, body, expected_result, expected_status) # POSTING ONE USAGE print("TEST_15 --- POSTING ONE USAGE") item_2 = send_get('items/2') usage_2_item_id = item_2['id'] usage_2_external_item_id = 1 usage_2_consumption_type = UsageTypeEnum.KILOWATT usage_2_consumption_amount = 5 usage_2_address = "http://127.0.0.1:5000/usages/2" usage_2_unit = UnitEnum.TOGGLE usage_2_min_value = 0 usage_2_max_value = 1 usage_2 = UsageModel(usage_2_item_id, usage_2_external_item_id, usage_2_consumption_type, usage_2_consumption_amount, usage_2_address, usage_2_unit, usage_2_min_value, usage_2_max_value) body = { "item_id": usage_2_item_id, "external_item_id": usage_2_external_item_id, "consumption_type": usage_2_consumption_type.value, "consumption_amount": usage_2_consumption_amount, "address": usage_2_address, "unit": "TOGGLE", "min_value": usage_2_min_value, "max_value": usage_2_max_value } usage_2_json = usage_2.to_json() usage_2_json['id'] = 2 usage_2_json['url'] = "127.0.0.1:5000/api/v1/usages/2" expected_result = usage_2_json expected_status = 201 uri = "usages" test_post(uri, body, expected_result, expected_status)
def test_item_resource(): print("#################### TESTING ITEM RESOURCE ####################") # GETTING ALL ITEMS print("TEST_1 --- GETTING ALL ITEMS") uri = "items" expected_result = { "items": [] } expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE ITEM print("TEST_2 --- POSTING ONE ITEM") item_1_name = 'Z04 Gang lamp (SW)' item_1_comment = 'ETS import' item_1 = ItemModel(item_1_name, item_1_comment) body = { "name": item_1_name, "comment": item_1_comment } item_1_json = item_1.to_json() item_1_json['id'] = 1 item_1_json['url'] = "127.0.0.1:5000/api/v1/items/1" expected_result = item_1_json expected_status = 201 uri = "items" test_post(uri, body, expected_result, expected_status) # GETTING ALL ITEMS print("TEST_3 --- GETTING ALL ITEMS") uri = "items" expected_result = { "items": [item_1_json] } expected_status = 200 test_get(uri, expected_result, expected_status) # GETTING ONE ITEM print("TEST_4 --- GETTING ONE ITEM") uri = "items/1" expected_result = item_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # UPDATING ONE ITEM print("TEST_5 --- UPDATING ONE ITEM") uri = 'items/1' expected_result = item_1_json expected_result['comment'] = 'new_comment' body = { 'name': item_1.name, 'comment': 'new_comment' } expected_status = 200 test_put(uri, body, expected_result, expected_status) item_1_json['comment'] = 'new_comment' # GETTING ONE ITEM print("TEST_6 --- GETTING UPDATED ITEM") uri = 'items/1' expected_result = item_1_json expected_status = 200 test_get(uri, expected_result, expected_status) # POSTING ONE ITEM print("TEST_7 --- POSTING ONE ITEM - BAD REQUEST") item_1_name = 'Z04 Gang lamp (SW)_______________________________________________________________' \ '_________________________________________________________________________________' \ '_________________________________________________________________________________' \ '_________________________________________________________________________________' item_1_comment = 'ETS import' item_1 = ItemModel(item_1_name, item_1_comment) body = { "name": item_1_name, "comment": item_1_comment } item_1_json = item_1.to_json() item_1_json['id'] = 2 expected_result = {"errors": [ Error( "Name cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400").to_json() ]} expected_status = 422 uri = "items" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_8 --- POSTING ONE ITEM - BAD REQUEST") item_1_name = 'Z04 Gang lamp (SW)' item_1_comment = 'ETS import_______________________________________________________________' \ '_________________________________________________________________________________' \ '_________________________________________________________________________________' \ '_________________________________________________________________________________' item_1 = ItemModel(item_1_name, item_1_comment) body = { "name": item_1_name, "comment": item_1_comment } item_1_json = item_1.to_json() item_1_json['id'] = 2 expected_result = {"errors": [ Error( "Comment cannot be longer than 255 characters.", "Name parameter cannot be longer than 255 characters.", 400, "https://en.wikipedia.org/wiki/HTTP_400").to_json() ]} expected_status = 422 uri = "items" test_post(uri, body, expected_result, expected_status) # POSTING ONE ITEM print("TEST_9 --- POSTING ONE ITEM") item_2_name = 'Z04 Eetkamer lamp (SW)' item_2_comment = 'ETS import' item_2 = ItemModel(item_2_name, item_2_comment) body = { "name": item_2_name, "comment": item_2_comment } item_2_json = item_2.to_json() item_2_json['id'] = 2 item_2_json['url'] = "127.0.0.1:5000/api/v1/items/2" expected_result = item_2_json expected_status = 201 uri = "items" test_post(uri, body, expected_result, expected_status)