Best Python code snippet using lemoncheesecake
tests.py
Source:tests.py
1from django.test import TestCase2from django.test.client import RequestFactory3from api import Api4from example import resources1, resources2, resources35from example import testdata16from validation import FieldsValidation7from test.client import Client8from models import Test as TestModel9from django.core.urlresolvers import reverse10from tastytools.test.resources import ResourceTestData11class ApiTestCase(TestCase):12 urls = 'tastytools.test_urls'13 14 def setUp(self):15 self.api = Api()16 17 def _assert_in_registry(self, resource_names):18 for resource_name in resource_names:19 try:20 assert resource_name in self.api._registry 21 except:22 print resource_name23 raise24 def test_resource_importing(self):25 """The Api class is able to import a single resource"""26 self.api.register(resources1.Test_1_1_Resource())27 self._assert_in_registry(["test_1_1"])28 def test_resource_list_importing(self):29 """The Api class is able to import a list of resources"""30 resources = [31 resources1.Test_1_2_Resource, 32 resources1.Test_1_3_Resource() 33 ]34 self.api.register(resources=resources)35 self._assert_in_registry(["test_1_2", "test_1_3"])36 37 def test_module_list_importing(self):38 """The Api class is able to import all resources from listed modules"""39 modules = [resources2, resources3]40 self.api.register(modules=modules)41 self._assert_in_registry(["test_2_1", "test_2_2", "test_2_3"])42 self._assert_in_registry(["test_3_1", "test_3_2", "test_3_3"])43 44 def test_testdata(self):45 """The API is able to register a testdata class"""46 self.api.register(resources1.Test_1_1_Resource())47 self.api.register_testdata(testdata1.Test_1_1_TestData)48 td = self.api.resource("test_1_1")._meta.testdata49 msg = "%s is not subclass of ResourceTestData" % td.__class__50 self.assertTrue(issubclass(td.__class__, ResourceTestData), msg)51 res = self.api.resource("test_1_1").create_test_resource()52 def test_testdata_list(self):53 """The API is able to register a list of testdata classes"""54 resources=[resources1.Test_1_1_Resource(), resources1.Test_1_2_Resource()]55 self.api.register(resources=resources)56 testdata_list=[testdata1.Test_1_1_TestData,testdata1.Test_1_2_TestData]57 self.api.register_testdata(list=testdata_list)58 59 for r in ["test_1_1", "test_1_2"]:60 td = self.api.resource(r)._meta.testdata61 msg = "%s is not subclass of ResourceTestData" % td.__class__62 self.assertTrue(issubclass(td.__class__, ResourceTestData), msg)63 res = self.api.resource(r).create_test_resource()64 def test_testdata_modules(self):65 """The API is able to register a testdata classes from a module"""66 self.api.register(modules=[resources1])67 self.api.register_testdata(modules=[testdata1])68 for r in ["test_1_1", "test_1_2"]:69 td = self.api.resource(r)._meta.testdata70 msg = "%s is not subclass of ResourceTestData" % td.__class__71 self.assertTrue(issubclass(td.__class__, ResourceTestData), msg)72 res = self.api.resource(r).create_test_resource()73class ClientTest(TestCase):74 urls = 'tastytools.test_urls'75 76 def test_urls_are_working(self):77 self.assertEqual("/test", reverse("test_url"))78 79 def test_path_or_resource(self):80 c = Client()81 obj = TestModel()82 obj.test = 'TESTING'83 obj.save()84 85 resource = resources1.Test_1_1_Resource()86 87 list_path = resource.get_resource_list_uri()88 object_path = resource.get_resource_uri(obj)89 90 result = c._path_or_resource(list_path)91 expected = list_path92 self.assertEqual(result, expected, 93 "Bare path.\nResult:%s\nExpected:%s" % (result, expected))94 95 result = c._path_or_resource(list_path, obj)96 expected = list_path97 self.assertEqual(result, expected, 98 "Bare path w/obj.\nResult:%s\nExpected:%s" % (result, expected))99 100 result = c._path_or_resource(resource)101 expected = list_path102 self.assertEqual(result, expected, 103 "Empty resource.\nResult:%s\nExpected:%s" % (result, expected))104 105 result = c._path_or_resource(resource, obj)106 expected = object_path107 self.assertEqual(result, expected, 108 "Populated resource.\nResult:%s\nExpected:%s" % (result, expected)) 109 110 111class FieldsValidationTest(TestCase):112 def test_parse_methods_key(self):113 validation = FieldsValidation()114 key = "required_post"115 #value = ['field1', 'field2']116 methods = validation.parse_methods_key(key, 'required')117 self.assertEqual(['POST'], methods)118 def test_map_method_validation(self):119 validation = FieldsValidation()120 fields = ['field1', 'field2']121 methods = ["POST", "PUT", "GET", "DELETE"]122 target = {}123 validation.map_method_validations(target, fields, methods)124 expected = {125 'POST': ['field1', 'field2'],126 'GET': ['field1', 'field2'],127 'PUT': ['field1', 'field2'],128 'DELETE': ['field1', 'field2'],129 }130 self.assertEqual(expected, target)131 validation.map_method_validations(target, ['field3'], ['PUT', 'POST'])132 expected = {133 'POST': ['field1', 'field2', 'field3'],134 'GET': ['field1', 'field2'],135 'PUT': ['field1', 'field2', 'field3'],136 'DELETE': ['field1', 'field2'],137 }138 self.assertEqual(expected, target)139 def test_fieldsvalid_constructor(self):140 validation = FieldsValidation(required=['f1', 'f2'],141 validated=['f1', 'f3'],142 required_post_get=['f4'],143 validated_put=['f5'])144 expected_required = {145 'POST': ['f1', 'f2', 'f4'],146 'GET': ['f1', 'f2', 'f4'],147 'PUT': ['f1', 'f2'],148 'DELETE': ['f1', 'f2'],149 'PATCH': ['f1', 'f2'],150 }151 expected_validated = {152 'POST': ['f1', 'f3'],153 'GET': ['f1', 'f3'],154 'PUT': ['f1', 'f3', 'f5'],155 'DELETE': ['f1', 'f3'],156 'PATCH': ['f1', 'f3'],157 }158 self.assertEqual(expected_validated, validation.validated_fields)...
predict_7.py
Source:predict_7.py
1# -*-coding:utf-8 -*-2import pandas as pd3import numpy as np4from sklearn.ensemble import RandomForestClassifier5from sklearn.ensemble import GradientBoostingClassifier # GBM algorithm6from sklearn import cross_validation, metrics # Additional scklearn functions7from sklearn.grid_search import GridSearchCV # Perforing grid search8import matplotlib.pylab as plt9from sklearn.metrics import f1_score10#æ¢å¤0.026æåç代ç 线ä¸è¯åååä½ãã11def predict_7(train, test, silent=1):12 len_of_test = len(test)13 train = train.fillna(-1)14 test = test.fillna(-1)15 target = 'subsidy'16 IDcol = 'studentid'17 predictors = [x for x in train.columns if x not in [target]]18 train_1 = train.copy()19 train_1['money'] = train_1['money'].map({0: 0, 1000: 1, 1500: 1, 2000: 1})20 train_1 = train_1[train_1['studentid'] < 22073]21 test_1_1 = test[test['studentid'] < 22073]22 # model23 clf = GradientBoostingClassifier(learning_rate=0.1,n_estimators=60, max_depth=3,min_samples_leaf=6,min_samples_split=150,subsample=1,random_state=30)24 clf.fit(train_1[predictors], train_1[target])25 result1 = clf.predict_proba(test_1_1[predictors])26 result1 = pd.DataFrame({'studentid':test_1_1['studentid'].values,'proba_of_1':result1[:,1]}).sort_values(by=['proba_of_1'],ascending=False)27 select_id = [id in result1.head(int(len_of_test*0.28))['studentid'].values for id in test['studentid'].values]28 clf2 = GradientBoostingClassifier(learning_rate=0.1,n_estimators=60, max_depth=3,min_samples_leaf=6,min_samples_split=150,subsample=1,random_state=30)29 clf2.fit(train[train['money'] != 0][predictors], train[train['money'] != 0][target])30 result2 = clf2.predict(test[select_id][predictors])31 result2 = pd.DataFrame({'studentid': test[select_id]['studentid'].values, 'subsidy': result2})32 remain_id = [id not in result1.head(int(len_of_test*0.28))['studentid'].values for id in test['studentid'].values]33 result3 = pd.DataFrame({'studentid':test[remain_id]['studentid'],'subsidy':0})34 result = result2.append(result3).sort_values('studentid')35 if silent==0: print result.groupby(result['subsidy']).size()...
test_1.py
Source:test_1.py
1import pytest2def test_1_1():3 assert False4@pytest.mark.dependency(depends=['test_1_1'])5def test_1_2():...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!