def api_github_message(): """api for sending comments""" if request.headers['Content-Type'] == 'application/json': print('inside server ') my_info = json.dumps(request.json) payload = json.loads(my_info) if not payload['action'] == 'closed': model = StoreModel().loadData() tdf = TestData() tdf1 = TestData1() parameter_dict = tdf.fetcher(my_info) extension_file = tdf1.file_fetcher(my_info) feature_dict = parameter_dict['feature_dict'] comment_url = parameter_dict['comment_url'] comment_body = tdf.test_feeder(feature_dict, model) file_comment_body = tdf1.file_test_feeder(extension_file[0], extension_file[1]) Comment.post_comment(comment_url, comment_body) Comment.post_comment(comment_url, str(file_comment_body)) app.logger.info(comment_body) prediction_response = json.dumps({"state": comment_body}) app.logger.info(comment_body) res = Response(prediction_response, status=200, mimetype='application.json') return res prediction_response = json.dumps({"state": "closed pull request"}) app.logger.info("closed pull request") res = Response(prediction_response, status=200, mimetype='application.json') return res
def classify_data_item(self, data_item, decision_tree): """ Function that classifies a data item from test data set by traversing the trained decision tree. :param data_item: :param decision_tree: :return: """ test_data = TestData() current_node = decision_tree split_feature_value = data_item[current_node.split_feature_index] # Traverse tree until it finds the leaf node or the split on the feature value is not found. while len(current_node.children ) > 0 and split_feature_value in current_node.children: current_node = current_node.children[split_feature_value] split_feature_value = data_item[current_node.split_feature_index] classified = current_node.class_label test_data.predicted_class = classified test_data.is_error = True if data_item[0] != classified else False test_data.is_false_negative = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_true_negative = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_false_positive = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False test_data.is_true_positive = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False return test_data
def predict(*, path_csv, path_model, model_name, batch_size, device, transform): model = ConvnetModel(model_name).to(device) model_checkpoint = torch.load(path_model + ".pth.tar", map_location=lambda storage, loc: storage.cuda(0)) model.load_state_dict(model_checkpoint['state_dict']) data_loader_test = DataLoader( TestData(path_csv, transform=transform), batch_size=batch_size, shuffle=False, num_workers=0) model.eval() study_y = {} for (x, study) in data_loader_test: bs, n_crops, c, h, w = x.size() x = x.to(device) with torch.no_grad(): y = torch.nn.Sigmoid()(model(x.view(-1, c, h, w))) y = y.to(CPU) y = y.view(bs, n_crops) for i in range(bs): if study[i] in study_y: study_y[study[i]][0] += 1 study_y[study[i]][1] += y[i,:] else: study_y[study[i]] = [1, y[i,:]] lst = [] # arithmetic average for key, value in study_y.items(): lst.append([key] + (value[1] / value[0]).tolist()) return sorted(lst)
def submit_1to1_demo_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom1") demo_page = DemoPage(driver=chrome_browser) # Click 'Schedule Now' button on demo page demo_page.schedule_now_button.click() # Insert test data in required fields on registration form demo_page.first_name_input1.input_text(test_data.firstName) demo_page.last_name_input1.input_text(test_data.lastName) demo_page.company_name_input1.input_text(test_data.companyName) demo_page.business_email_input1.input_text(test_data.email) demo_page.phone_number_input.input_text(test_data.phone) demo_page.job_title_input.input_text(test_data.jobTitle) demo_page.company_type_select.select_by_value(test_data.companyType) demo_page.privacy_policy_checkbox.click() # Submit registration form demo_page.get_1to1_demo_button.click() # TEST -> That confirmation message is displayed, after submitting 1 to 1 demo request form assert EC.visibility_of_element_located(demo_page.confirmation_message1)
def request_feed_webview(self, num_items='all'): url = self.url_prefix + '/feed' data = {'StatusCode':200, 'num_items':num_items} total_time = Timer() response = requests.get(url=url, data=json.dumps(data), headers=self.auth_header) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def FromProto(proto): template_function = FindImplementation(proto) test_data = {} for data_proto in proto.data: data = TestData.FromProto(data_proto) test_data[data.name] = data.value test_case = _FunctionWrappingTestCase(template_function, test_data, proto.name, proto.description) return test_case
def test_incorrect_email(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.valid_password) rp.confirm_password(td.valid_password) rp.fill_email(td.invalid_email) rp.confirm_email(" ") ut.verify_visible_errors(1, ["Podaj prawidłowy adres email!"])
def test_get_icecreams_of_date(self, mock_get): # given requests.get.return_value = TestData.delzepich_html_get() # when date = datetime.datetime.strptime('2021-05-21', '%Y-%m-%d') variations = get_icecreams_of_date(date) # then assert variations == ['Franzbrötchen', 'Herrenschoki', 'Mascarpone - Waldfrucht', 'Sesam - Krokant', 'Schoko', 'Vanille', 'Cheesecake', 'Tagessorbet']
def request_getter(self, command, filename=''): url = self.url_prefix + '/getter' data = {'StatusCode': 200, 'command': command} if filename is not '': data['filename'] = filename total_time = Timer() response = requests.get(url=url, data=json.dumps(data), headers=self.auth_header) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def test_wrong_password_during_confirmation(self, email, password): # Stworzenie instancji klasy RegistrationPage (rp) rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password("3") rp.fill_email(email) # UWAGA TEST! ut.verify_visible_errors(1, ["Hasło i potwierdzenie hasła muszą być takie same."])
def test_incorrect_birth_year(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password(td.password) rp.fill_email(td.valid_email) rp.confirm_email(td.valid_email) rp.fill_birth_year("18") rp.choose_gender_female() ut.verify_visible_errors(1, ["* Niepoprawny rok urodzenia"])
def test_play_game_4_rounds_2_player(self, mock_print, mock_player, mock_round): mock_input.side_effect = ["2", "test1", "test2"] player1 = TestData.Player("player1") player2 = TestData.Player("player2") self.game.players = [player1, player2] self.game.rounds = 4 self.game.play_game() mock_input.assert_any_call( "Welcome to Yathzee!! \n With how many people will you play this game?" ) mock_input.assert_any_call("What is the name of player 1?") self.assertEqual(player1.name, self.game.players[0].name) mock_player.assert_any_call("test1") mock_player.assert_any_call("test2") mock_print.assert_any_call( f"{player1.name} has a score of {player1.scoreblock.total_score()}" ) mock_print.assert_any_call( f"{player2.name} has a score of {player2.scoreblock.total_score()}" ) self.assertEqual(4, mock_round.call_count)
def classify_data_item(self, data_item, learn_tree_list): """ Function that classifies a data item from test data set by traversing the trained decision tree. :param data_item: :param decision_tree: :return: """ result_dict = dict() test_data = TestData() # Iterating to all the learnt bag trees to find majority vote. for ltree in learn_tree_list: current_node = ltree.decision_tree split_feature_value = data_item[current_node.split_feature_index] # Traverse tree until it finds the leaf node or the split on the feature value is not found. while len(current_node.children ) > 0 and split_feature_value in current_node.children: current_node = current_node.children[split_feature_value] split_feature_value = data_item[ current_node.split_feature_index] if current_node.class_label not in result_dict: result_dict[current_node.class_label] = 1 else: result_dict[current_node.class_label] += 1 # Getting the majority vote here. classified = self.get_majority_vote(result_dict) test_data.predicted_class = classified test_data.is_error = True if data_item[0] != classified else False test_data.is_false_negative = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_true_negative = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_false_positive = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False test_data.is_true_positive = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False return test_data
def predict(path_csv, config): cudnn.benchmark = True model = convnet_models.load( config["model_name"], input_size=config["crop_size"], pretrained=False ).to(GPU) model_checkpoint = torch.load(config["path_model"], map_location=lambda storage, loc: storage.cuda(0)) model.load_state_dict(model_checkpoint['state_dict']) data_loader_test = DataLoader( TestData(path_csv, transform=config["transform"].get( img_size=config["img_size"], crop_size=config["crop_size"], target_mean=config["target_mean"], target_std=config["target_std"] )), batch_size=config["batch_size"], shuffle=False, num_workers=2, pin_memory=True ) model.eval() study_y = {} with torch.no_grad(): for (x, study) in data_loader_test: bs, n_crops, c, h, w = x.size() x = x.to(GPU) y = model(x.view(-1, c, h, w)) y = y.view(bs, n_crops).mean(1) for i in range(bs): if study[i] in study_y: study_y[study[i]][0] += 1 study_y[study[i]][1] += y[i] else: study_y[study[i]] = [1, y[i]] lst = [] for key, value in study_y.items(): lst.append([key, value[1] / value[0]]) lst = sorted(lst) keys = [] result = np.zeros(len(lst)) for i in range(len(lst)): keys.append(lst[i][0]) result[i] = lst[i][1] return keys, result
def test_play_game_wrong_input(self, mock_print, mock_player, mock_round): mock_input.side_effect = ["test", "1", "test1"] player1 = TestData.Player("player1") self.game.players = [player1] self.game.rounds = 0 self.game.play_game() mock_input.assert_any_call( "Welcome to Yathzee!! \n With how many people will you play this game?" ) mock_input.assert_any_call("What is the name of player 1?") self.assertEqual(player1.name, self.game.players[0].name) mock_player.assert_any_call("test1") mock_print.assert_called_with( f"{player1.name} has a score of {player1.scoreblock.total_score()}" ) self.assertEqual(0, mock_round.call_count) mock_print.assert_any_call("please enter a digit")
def submit_watch_now_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom2") demo_page = DemoPage(driver=chrome_browser) # Click 'Watch Now' button on demo page demo_page.watch_now_button.click() # Insert test data in required fields on registration form demo_page.first_name_input2.input_text(test_data.firstName) demo_page.last_name_input2.input_text(test_data.lastName) demo_page.company_name_input2.input_text(test_data.companyName) demo_page.business_email_input2.input_text(test_data.email) demo_page.privacy_policy_checkbox2.click() # Submit registration form demo_page.watch_now_demo_button.click() # TEST -> That confirmation message is displayed, after submitting watch now request form assert EC.visibility_of_element_located(demo_page.confirmation_message2)
def request_putter(self, image_path, filename): with open(image_path, mode='rb') as file: img = file.read() image_64_encode = base64.encodebytes(img).decode("utf-8") json_object = { "HTTPMethod":"POST", "StatusCode":200, "body": { "title":filename, "img":image_64_encode } } url = self.url_prefix + "/putter" data = json.dumps(json_object) headers = self.auth_header total_time = Timer() response = requests.post(url, data=data,headers=headers) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def main(): print(__file__ + " start!!") # simulation parameters nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, np.deg2rad(-10.0)] # movement [x[m],y[m],yaw[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points td = TestData() p = td.nominal_input.sweep px = p[:,0] py = p[:,1] # px = (np.random.rand(nPoint) - 0.5) * fieldLength # py = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py)) input_data = td.top_wall_input1 c = input_data.sweep cx = c[:,0] cy = c[:,1] # current points # cx = [math.cos(motion[2]) * x - math.sin(motion[2]) * y + motion[0] # for (x, y) in zip(px, py)] # cy = [math.sin(motion[2]) * x + math.cos(motion[2]) * y + motion[1] # for (x, y) in zip(px, py)] current_points = np.vstack((cx, cy)) R, T = icp_matching(previous_points, current_points) print("Calculated R:", R) print("Calculated T:", T) print("Real R: ", [[math.sin(input_data.theta), math.cos(input_data.theta)], [-math.cos(input_data.theta), math.sin(input_data.theta)]]) print("Real T: ", [input_data.y, -input_data.x])
def submit_sign_up_here_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom3") demo_page = DemoPage(driver=chrome_browser) # Click 'Sign Up Here' button on demo page demo_page.sign_up_here.click() # Insert test data in required fields on registration form demo_page.first_name_input3.input_text(test_data.firstName) demo_page.last_name_input3.input_text(test_data.lastName) demo_page.company_name_input3.input_text(test_data.companyName) demo_page.business_email_input3.input_text(test_data.email) demo_page.job_title_input3.input_text(test_data.jobTitle) demo_page.company_type_select3.select_by_value(test_data.companyType) demo_page.privacy_policy_checkbox3.click() # Submit registration form demo_page.save_my_spot_button3.click() # TEST -> That confirmation message is displayed, after submitting sign up form assert EC.visibility_of_element_located(demo_page.confirmation_message3)
import heapq class Recommender: def __init__(self, train): self.train = train def vector_model(self,to_predict): cos = cosine_similarity(self.train,to_predict) return self.train[(heapq.nlargest(2,xrange(len(cos)),cos.take))[1:][0]] def fit(self): self.nbrs = NearestNeighbors(n_neighbors=10).fit(self.train) # choose the 5 nearest neighbors def predict(self, to_predict): indices,distances = self.getKNN(to_predict) return [self.train[i] for i in indices] def getKNN(self,to_predict): distances, indices = self.nbrs.kneighbors(test.reshape(1,-1) , n_neighbors=10) # but take only the closest return indices,distances # his is the proof that the best match is in the cluster if __name__ == '__main__': t = TestData() X, test = t.generateTrainData(3700,1000) knn = Recommender(X) knn.fit() print knn.predict(test) print knn.vector_model(test)
class UnitTests(unittest.TestCase): """End-to-end Smoke Test""" config_schema_path = '/auction/util/config_schema.json' input_schema_path = '/auction/util/input_schema.json' test_config_path = '/auction/test_config.json' test_input_path = '/auction/test_input.json' def setUp(self): self.operator = TestData() @attr('unittest') def test_config_schema(self): """Check that config data matches valid schema""" config_data = get_json_file_content(self.test_config_path) config_schema = get_json_file_content(self.config_schema_path) result = True try: validate(config_data, config_schema) except jsonschema.exceptions.ValidationError as e: result = False self.assertEqual(result, True, 'Invalid File Data') @attr('unittest') def test_input_schema(self): """Check that input data format matches valid schema""" input_data = get_json_file_content(self.test_input_path) input_schema = get_json_file_content(self.input_schema_path) result = True try: validate(input_data, input_schema) except jsonschema.exceptions.ValidationError as e: result = False self.assertEqual(result, True, 'Invalid File Data') @attr('unittest') def test_config_parser_parse(self): """Test config parser -> parse method""" result = ConfigParser.parse(self.test_config_path) expected = ConfigData(*self.operator.mock_config_parser_parse()) self.assertEqual(result, expected, 'Invalid Config Data') @attr('unittest') def test_input_parser_parse(self): """Test input parser -> parse method""" result = InputParser.parse(self.test_input_path) expected = InputData(self.operator.mock_input_parser_parse()) self.assertEqual(result, expected, 'Invalid Input Data') @attr('unittest') def test_auction_results(self): """Test auction bids result calculation""" bids = [ Bid(Bidder('BRANDON', -0.001), 'banner', 50), Bid(Bidder('ASEMA', -0.0432), 'banner', 51) ] site = Site('test.com', [bids[0].bidder, bids[1].bidder], 40) auction = Auction(site, [AdUnit.banner], bids) actual = auction.get_max_bids() self.assertEqual(actual['banner'].bid, 50, 'Invalid Auction') @attr('unittest') def test_auction_results_performance(self): """Evaluate response time for auction results""" bids = [ Bid(Bidder('BRANDON', -0.001), 'banner', 50), Bid(Bidder('ASEMA', -0.0432), 'banner', 51) ] site = Site('test.com', [bids[0].bidder, bids[1].bidder], 40) auction = Auction(site, [AdUnit.banner], bids) time_start = time.time() auction.get_max_bids() time_end = time.time() time_span = time_end - time_start self.assertLess(time_span, 1, 'Results Method Performance Inadequate')
def setUp(self): self.test_data = TestData()
class DirCacheTest(unittest.TestCase): def setUp(self): self.test_data = TestData() def tearDown(self): self.test_data.close() def test_listdir_on_invalid_dir(self): c = DirCache() # shoudl not raise exception c.listdir(self.test_data.path_to('xxx')) def test_listdir_when_gone(self): c = DirCache() something = self.test_data.path_to('something'); c.listdir(something) self.test_data.rm_rf(something) self.assertEquals([], c.listdir(self.test_data.path_to('something'))) def test_up_to_date_after_change(self): c = DirCache() something = self.test_data.path_to('something'); c.listdir(something) self.test_data.rm_rf(something) self.assertEquals([], c.listdir(self.test_data.path_to('something'))) def test_toplevel_deletion_causes_changed(self): c = DirCache() base = self.test_data.path_to(''); something = self.test_data.path_to('something'); c.listdir(base) c.listdir(something) self.assertFalse(c.listdir_with_changed_status(base)[1]) self.assertFalse(c.listdir_with_changed_status(something)[1]) time.sleep(1.2) self.test_data.rm_rf(something) self.assertTrue(c.listdir_with_changed_status(base)[1]) self.assertTrue(c.listdir_with_changed_status(something)[1]) def test_toplevel_addition_causes_change(self): c = DirCache() base = self.test_data.path_to(''); c.listdir(base) self.assertFalse(c.listdir_with_changed_status(base)[1]) time.sleep(1.2) self.test_data.write1('READMEx') self.assertTrue(c.listdir_with_changed_status(base)[1]) def test_toplevel_modification_doesnt_cause_change(self): c = DirCache() base = self.test_data.path_to(''); c.listdir(base) self.assertFalse(c.listdir_with_changed_status(base)[1]) time.sleep(1.2) self.test_data.write1('READMEx') self.assertTrue(c.listdir_with_changed_status(base)[1]) time.sleep(1.2) self.test_data.write2('READMEx') self.assertFalse(c.listdir_with_changed_status(base)[1])
def setUp(self): self.operator = TestData()
class RegistrationPageTest(BaseTest, TestData): """ Test strony Rejestracji """ def setUp(self): print("setUp z RegistrationPageTest") # Wywołanie metody setUp z klasy nadrzędnej (BaseTest) super().setUp() # Kliknięcie zaloguj # Stworzenie instancji klasy HomePage (hp) hp = HomePage(self.driver) hp.accept_privacy_btn() # Użycie metody click_zaloguj_btn zawartej w obiekcie hp klasy HomePage hp.click_zaloguj_btn() # Kliknięcie Rejestracja na stronie Logowania # Stworzenie instancji klasy LoginPage (lp) lp = LoginPage(self.driver) # Użycie metody click_register_btn zawartej w obiekcie lp klasy LoginPage sleep(1) lp.click_register_btn() # @unittest.skip("Pomijam") @data(*TestData.get_data("excel_data.csv")) @unpack def test_wrong_password_during_confirmation(self, email, password): # Stworzenie instancji klasy RegistrationPage (rp) rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password("3") rp.fill_email(email) # UWAGA TEST! ut.verify_visible_errors(1, ["Hasło i potwierdzenie hasła muszą być takie same."]) # @unittest.skip("Pomijam") def test_incorrect_email(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.valid_password) rp.confirm_password(td.valid_password) rp.fill_email(td.invalid_email) rp.confirm_email(" ") ut.verify_visible_errors(1, ["Podaj prawidłowy adres email!"]) # @unittest.skip("Pomijam") def test_incorrect_birth_year(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password(td.password) rp.fill_email(td.valid_email) rp.confirm_email(td.valid_email) rp.fill_birth_year("18") rp.choose_gender_female() ut.verify_visible_errors(1, ["* Niepoprawny rok urodzenia"]) if __name__ == "__main__": unittest.main(verbosity=2)