Best Python code snippet using webdriver_manager
testClient.py
Source:testClient.py
1'''2Created on Oct 27, 20163@author: henrylevy4'''5from tornado import httpclient6import urllib, base647import unittest8import json9# ip = '35.160.111.133'10# ip = '35.163.38.167'11ip = 'localhost'12#ip = 'parkhere.cghr1zvgeuqd.us-west-1.rds.amazonaws.com'13#ip = 'ec2-35-163-38-167.us-west-2.compute.amazonaws.com'14def buildImgStr(path):15 with open(path, 'rb') as image_file:16 return base64.b64encode(image_file.read())17def createUser(http_client, email, password, first, last, phone, seeker, owner, img=None):18 url = 'http://{0}:8888/signup'.format(ip)19 body = urllib.urlencode({'email' : email,20 'password' : password,21 'first' : first,22 'last' : last,23 'phone' : phone,24 'seeker' : seeker,25 'owner' : owner,26 'profilePic' : img})27 req = httpclient.HTTPRequest(url, 'POST', body=body)28 res = http_client.fetch(req)29 try:30 cookie = res.headers["set-cookie"]31 except:32 cookie = None33 return cookie, res.body34 35def signIn(http_client, email, password):36 url = 'http://{0}:8888/signin'.format(ip)37 body = urllib.urlencode({'email' : email,38 'password' : password})39 req = httpclient.HTTPRequest(url, 'POST', body=body)40 res = http_client.fetch(req)41 try:42 cookie = res.headers["set-cookie"]43 except:44 cookie = None45 return cookie, res.body46def searchSpot(cookie, http_client, address):47 url = 'http://{0}:8888/search/spot/location'.format(ip)48 headers = {'Cookie' : cookie}49 args = urllib.urlencode({'address' : address})50 url = url + '?' + args51 req = httpclient.HTTPRequest(url, 'GET', headers=headers)52 53 res = http_client.fetch(req)54 return res.body55def searchSpotTime(cookie, http_client, start, end):56 url = 'http://{0}:8888/search/spot/date'.format(ip)57 headers = {'Cookie' : cookie}58 args = urllib.urlencode({'start' : start, 59 'end' : end})60 url = url + '?' + args61 req = httpclient.HTTPRequest(url, 'GET', headers=headers)62 63 res = http_client.fetch(req)64 return res.body65def postSpot(cookie, http_client, address, spotType, isCovered,66 cancelationPolicy, price, start, end, recurring):67 headers = {"Cookie": cookie}68 url = 'http://{0}:8888/post/spot'.format(ip)69 body = urllib.urlencode({'address' : address,70 'spotType' : spotType,71 'isCovered' : isCovered,72 'cancelationPolicy' : cancelationPolicy,73 'price' : price,74 'start' : start,75 'end' : end,76 'isRecurring' : recurring})77 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)78 79 res = http_client.fetch(req)80 return res.body81def checkUser(cookie, http_client, email):82 url = 'http://{0}:8888/check/user'.format(ip)83 headers = {'Cookie' : cookie}84 args = urllib.urlencode({'email' : email})85 url = url + '?' + args86 req = httpclient.HTTPRequest(url, 'GET', headers=headers)87 88 res = http_client.fetch(req)89 return res.body90def viewUser(cookie, http_client, email):91 url = 'http://{0}:8888/view/user'.format(ip)92 headers = {'Cookie' : cookie}93 args = urllib.urlencode({'email' : email})94 url = url + '?' + args95 req = httpclient.HTTPRequest(url, 'GET', headers=headers)96 res = http_client.fetch(req)97 return res.body98def rateUser(cookie, http_client, email, rating):99 headers = {"Cookie": cookie}100 url = 'http://{0}:8888/rate/user'.format(ip)101 body = urllib.urlencode({'email' : email,102 'rating' : rating})103 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)104 105 res = http_client.fetch(req)106 print "body:"107 print res.body108def rateSpot(cookie, http_client, spotId, rating):109 headers = {"Cookie": cookie}110 url = 'http://{0}:8888/rate/spot'.format(ip)111 body = urllib.urlencode({'spotId' : spotId,112 'rating' : rating})113 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)114 res = http_client.fetch(req)115 print "body:"116 print res.body117def modifyUser1(cookie, http_client, phone, isSeeker):118 headers = {"Cookie": cookie}119 url = 'http://{0}:8888/modify/user'.format(ip)120 body = urllib.urlencode({'phone' : phone,121 'isSeeker' : isSeeker})122 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)123 124 res = http_client.fetch(req)125 print "body:"126 print res.body127def viewSpot(cookie, http_client, spotID):128 url = 'http://{0}:8888/view/spot'.format(ip)129 headers = {'Cookie' : cookie}130 args = urllib.urlencode({'spotID' : spotID})131 url = url + '?' + args132 req = httpclient.HTTPRequest(url, 'GET', headers=headers)133 res = http_client.fetch(req)134 return res.body135def deleteSpot(cookie, http_client, spotID):136 headers = {"Cookie": cookie}137 url = 'http://{0}:8888/delete/spot'.format(ip)138 body = urllib.urlencode({'spotID': spotID})139 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)140 141 res = http_client.fetch(req)142 return res.body143def viewPostings(cookie, http_client, email):144 url = 'http://{0}:8888/view/postings'.format(ip)145 headers = {'Cookie' : cookie}146 args = urllib.urlencode({'email' : email})147 url = url + '?' + args148 req = httpclient.HTTPRequest(url, 'GET', headers=headers)149 res = http_client.fetch(req)150 print res.body151 return res.body152def cancelReservation(cookie, http_client, spotID):153 headers = {"Cookie": cookie}154 url = 'http://{0}:8888/cancel/reservation'.format(ip)155 body = urllib.urlencode({'spotID': spotID})156 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)157 158 res = http_client.fetch(req)159 return res.body160def spotHistory(cookie, http_client, email):161 headers = {"Cookie": cookie}162 url = 'http://{0}:8888/view/history'.format(ip)163 args = urllib.urlencode({'email' : email})164 url = url + '?' + args165 req = httpclient.HTTPRequest(url, 'GET', headers=headers)166 res = http_client.fetch(req)167 return res.body168def contactCustomerService(cookie, http_client, email, message):169 headers = {"Cookie": cookie}170 url = 'http://{0}:8888/contact/service'.format(ip)171 body = urllib.urlencode({'email': email,172 'message': message})173 req = httpclient.HTTPRequest(url, 'POST', body=body, headers=headers)174 175 res = http_client.fetch(req)176 return res.body177def getCount(cookie, http_client, addressID):178 headers = {"Cookie": cookie}179 url = 'http://{0}:8888/get/count'.format(ip)180 args = urllib.urlencode({'addressID' : addressID})181 url = url + '?' + args182 req = httpclient.HTTPRequest(url, 'GET', headers=headers)183 res = http_client.fetch(req)184 return res.body185# if __name__ == '__main__':186# http_client = httpclient.HTTPClient()187# #img = buildImgStr('/Users/henrylevy/Downloads/default.jpg')188# cookie = createUser(http_client, 'rob1@rob.com', 'Password1$', 'first', 'last', '123-456-7890', 1, 1)189# cookie = signIn(http_client, 'rob@rob.com', 'Password1$')190# checkUser(cookie, http_client, "rob1@rob.com")191# checkUser(cookie, http_client, "rob@rob.com")192 # postSpot(cookie, http_client, '707 West 28th street, Los Angeles CA, 90007', '0', '0', "0", '10.00', "2016-10-12 12:00:00", "2016-10-12 14:00:00", '0')193# searchSpot(cookie, http_client, '700 West 28th street, Los Angeles CA, 90007')194# http_client.close()195class TestParkHereMethods(unittest.TestCase):196 # def test_signup(self):197 # http_client = httpclient.HTTPClient()198 # cookie, code = createUser(http_client, '', 'Password1$', 'first', 'last', '123-456-7890', 1, 1)199 # # cookie, code = createUser(http_client, 'rob6@rob.com', 'Password1$', 'first', 'last', '123-456-7890', 1, 1)200 # # self.assertNotEqual(code, '401')201 # # info = viewUser(cookie, http_client, 'rob6@rob.com')202 # # jsondata = json.loads(info)203 # # self.assertEqual(jsondata["isSeeker"], 1)204 # # cookie, code = createUser(http_client, 'rob@rob.com', 'Password1$', 'first', 'last', '123-456-7890', 1, 1)205 # # self.assertEqual(code, '401')206 # http_client.close()207 # def test_signin(self):208 # http_client = httpclient.HTTPClient()209 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1')210 # self.assertEqual(code, '401')211 # cookie, code = signIn(http_client, 'ob@rob.com', 'Password1')212 # self.assertEqual(code, '401')213 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')214 # self.assertEqual(code, '200')215 # http_client.close()216 # def test_check_user(self):217 # http_client = httpclient.HTTPClient()218 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')219 # res = checkUser(cookie, http_client, "rob@rob.com")220 # self.assertEqual(int(res), 1)221 # res = checkUser(cookie, http_client, "rob1@rob.com")222 # self.assertEqual(int(res), 0)223 # res = checkUser(cookie, http_client, "rob45@rob.com")224 # self.assertEqual(int(res), 0)225 # http_client.close()226 # # self.assertEqual(s.split(), ['hello', 'world'])227 # # # check that s.split fails when the separator is not a string228 # # with self.assertRaises(TypeError):229 # # s.split(2)230 # def test_view_user(self):231 # http_client = httpclient.HTTPClient()232 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')233 # info = viewUser(cookie, http_client, "rob@rob.com")234 # jsondata = json.loads(info)235 # self.assertEqual(jsondata["rating"], 0.0)236 # self.assertEqual(jsondata["last"], 'last')237 # self.assertEqual(jsondata["first"], 'first')238 # self.assertEqual(jsondata["isSeeker"], 1)239 # self.assertEqual(jsondata["isOwner"], 1)240 # self.assertEqual(jsondata["phoneNumber"], '123-456-7890')241 # self.assertEqual(jsondata["email"], 'rob@rob.com')242 # http_client.close()243 # def test_rate_user(self):244 # http_client = httpclient.HTTPClient()245 # # cookie, code = createUser(http_client, 'rate@user.com', 'Password1$', 'first', 'last', '123-456-7890', 1, 1)246 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')247 # info = viewUser(cookie, http_client, 'rate@user.com')248 # jsondata = json.loads(info)249 # print jsondata["rating"]250 # self.assertEqual(jsondata["rating"], 0.0)251 # rateUser(cookie, http_client,'rate@user.com', 5)252 # info = viewUser(cookie, http_client, 'rate@user.com')253 # jsondata = json.loads(info)254 # print jsondata["rating"]255 # self.assertEqual(jsondata["rating"], 5.0)256 # http_client.close()257 # def test_rate_spot(self):258 # http_client = httpclient.HTTPClient()259 # spot = 10260 # cookie, code = signIn(http_client, 'a@b.com', 'password1!')261 # info = viewSpot(cookie, http_client, spot)262 # jsondata = json.loads(info)263 # print jsondata["rating"]264 # self.assertEqual(jsondata["rating"], 0.0)265 # rateSpot(cookie, http_client, spot, 5)266 # info = viewSpot(cookie, http_client, spot)267 # jsondata = json.loads(info)268 # print jsondata["rating"]269 # self.assertEqual(jsondata["rating"], 5.0)270 # http_client.close()271 # def test_modify_user(self):272 # http_client = httpclient.HTTPClient()273 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')274 # info = viewUser(cookie, http_client, 'rob@rob.com')275 # jsondata = json.loads(info)276 # self.assertEqual(jsondata["phoneNumber"], '123-456-1111')277 # self.assertEqual(jsondata["isSeeker"], 1)278 # modifyUser1(cookie, http_client, '123-456-1121', 0)279 # info = viewUser(cookie, http_client, 'rob@rob.com')280 # jsondata = json.loads(info)281 # self.assertEqual(jsondata["phoneNumber"], '123-456-1121')282 # self.assertEqual(jsondata["isSeeker"], 0)283 # http_client.close()284 # def test_post_spot(self):285 # http_client = httpclient.HTTPClient()286 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')287 # res = postSpot(cookie, http_client, '2801 Menlo Ave, Los Angeles CA, 90007', '0', '0', "0", '10.00', "2016-11-12 12:00:00", "2016-11-12 14:00:00", '0')288 # self.assertEqual(res, '200')289 # http_client.close()290 # def test_search_spot(self):291 # http_client = httpclient.HTTPClient()292 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')293 # res = searchSpot(cookie, http_client,"2801 Menlo Ave, Los Angeles, CA")294 # jsondata = json.loads(res)295 # self.assertEqual(jsondata[0]["address"], '2801 Menlo Ave, Los Angeles CA, 90007')296 # self.assertEqual(jsondata[0]["start"], "2016-11-12 12:00:00")297 # self.assertEqual(jsondata[0]["end"], "2016-11-12 14:00:00")298 # http_client.close()299 # def test_search_time_spot(self):300 # http_client = httpclient.HTTPClient()301 # cookie, code = signIn(http_client, 'rob2@rob.com', 'Password1$')302 # res = searchSpotTime(cookie, http_client,"2016-10-19 11:58:00","2016-10-26 22:40:00")303 # print res304 # jsondata = json.loads(res)305 # self.assertEqual(jsondata[0]["address"], '1200 West 35th street, Los Angeles CA, 90007')306 # http_client.close()307 # def test_view_spot(self):308 # http_client = httpclient.HTTPClient()309 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')310 # # res = postSpot(cookie, http_client, '706 West 28th street, Los Angeles CA, 90007', '0', '0', '0', '10.00', "2016-10-12 12:00:00", "2016-10-12 14:00:00", '0')311 # res = searchSpot(cookie, http_client, '706 West 28th street, Los Angeles CA, 90007')312 # jsondata = json.loads(res)313 # spotID = jsondata[0]['id']314 # res = viewSpot(cookie, http_client,spotID)315 # jsondata = json.loads(res)316 # self.assertEqual(jsondata["address"], '706 West 28th street, Los Angeles CA, 90007')317 # self.assertEqual(jsondata["spotType"], 0)318 # self.assertEqual(jsondata["isCovered"], 0)319 # self.assertEqual(jsondata["cancelationPolicy"], 0)320 # self.assertEqual(jsondata["price"], 10.00)321 # self.assertEqual(jsondata["start"], u'2016-10-12 12:00:00')322 # self.assertEqual(jsondata["end"], u'2016-10-12 14:00:00')323 # self.assertEqual(jsondata["isRecurring"],0)324 # http_client.close()325 # def test_delete_spot(self):326 # http_client = httpclient.HTTPClient()327 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')328 # res = postSpot(cookie, http_client, '2800 Menlo Ave, Los Angeles CA, 90007', '0', '0', "0", '10.00', "2016-11-12 12:00:00", "2016-11-12 14:00:00", '0')329 # res = searchSpot(cookie, http_client, '2800 Menlo Ave, Los Angeles CA, 90007')330 # jsondata = json.loads(res)331 # spotID = jsondata[0]['id']332 # res = deleteSpot(cookie, http_client, spotID)333 # self.assertEqual(res, '200')334 # http_client.close()335 # def test_view_postings(self):336 # http_client = httpclient.HTTPClient()337 # cookie, code = signIn(http_client, 'rob@rob.com', 'Password1$')338 # res = viewPostings(cookie, http_client, 'rob@rob.com')339 # jsondata = json.loads(res)340 # self.assertEqual(jsondata[0][0],6)341 # self.assertEqual(jsondata[1][0],7)342 # http_client.close()343 #def test_cancel_spot(self):344 # http_client = httpclient.HTTPClient()345 # cookie, code = signIn(http_client, 'qwerty@a.com', 'Password!1')346 # spotID = 10347 # res = cancelReservation(cookie, http_client, spotID)348 # self.assertEqual(res, '200')349 # http_client.close()350 #ID only351 #def test_spot_history(self):352 # http_client = httpclient.HTTPClient()353 # cookie, code = signIn(http_client, 'qwerty@a.com', 'Password!1')354 # res = spotHistory(cookie, http_client,'qwerty@a.com')355 # jsondata = json.loads(res)356 # #self.assertEqual(jsondata[0][0], 10)357 # self.assertEqual(len(jsondata), 2)358 # http_client.close()359 #more data360 def test_spot_history(self):361 http_client = httpclient.HTTPClient()362 cookie, code = signIn(http_client, 'qwerty@a.com', 'Password!1')363 res = spotHistory(cookie, http_client,'qwerty@a.com')364 jsondata = json.loads(res)365 self.assertEqual(jsondata[0]["id"], 3)366 self.assertEqual(jsondata[0]["address"], "2000 new test street, los angeles CA 90008")367 http_client.close()368 #def test_contact_service(self):369 # http_client = httpclient.HTTPClient()370 # cookie, code = signIn(http_client, 'qwerty@a.com', 'Password!1')371 # res = contactCustomerService(cookie, http_client, "qwerty@.com", "testing")372 # self.assertEqual(res,'200')373 # http_client.close()374 def test_get_count(self):375 http_client = httpclient.HTTPClient()376 cookie, code = signIn(http_client, 'qwerty@a.com', 'Password!1')377 res = getCount(cookie, http_client, 1)378 self.assertEqual(res,'1')379 http_client.close()380if __name__ == '__main__':381 unittest.main()...
test_application_features.py
Source:test_application_features.py
1import pytest2from fastapi import status3from tests.helpers import prepare_headers, clean_feature4def setup_module(module):5 clean_feature(["test1", "test2", "test3", "test4", "test5", "test6"])6def test_get_should_return_features(http_client, jwt_token):7 # ARRANGE & ACT8 response = http_client.get("/v1/applications/netflix/features", headers=prepare_headers(jwt_token))9 # ASSERT10 assert response.status_code == status.HTTP_200_OK11 json = response.json()12 assert len(json) >= 113def test_get_should_not_return_features_because_missing_token(http_client, jwt_token):14 # ARRANGE & ACT15 response = http_client.get("/v1/applications/netflix/features", headers=prepare_headers())16 # ASSERT17 assert response.status_code == status.HTTP_200_OK18 json = response.json()19 assert "Not authenticated" in json["errors"]20@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])21def test_patch_should_create_new_feature(http_client, jwt_token, feature_name):22 # ARRANGE23 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))24 assert response.status_code == status.HTTP_200_OK25 initial_features = response.json()26 assert len(initial_features) > 027 new_feature = {28 "environment_id": 4,29 "name": feature_name,30 "enable": True,31 }32 # ACT33 response = http_client.patch(34 "/v1/applications/netflix/features/",35 headers=prepare_headers(jwt_token),36 json=new_feature)37 # ASSERT38 assert response.status_code == status.HTTP_200_OK39 json = response.json()40 assert len(initial_features) != len(json)41def test_patch_should_not_create_new_feature_because_missing_token(http_client, jwt_token):42 # ARRANGE43 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))44 assert response.status_code == status.HTTP_200_OK45 initial_features = response.json()46 assert len(initial_features) > 047 new_feature = {48 "environment_id": 4,49 "name": "test",50 "enable": True,51 }52 # ACT53 response = http_client.patch(54 "/v1/applications/netflix/features/",55 headers=prepare_headers(),56 json=new_feature)57 # ASSERT58 assert response.status_code == status.HTTP_200_OK59 json = response.json()60 assert "Not authenticated" in json["errors"]61def test_patch_should_not_create_new_feature_because_feature_already_exists(http_client, jwt_token):62 # ARRANGE63 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))64 assert response.status_code == status.HTTP_200_OK65 initial_features = response.json()66 assert len(initial_features) > 067 new_feature = {68 "environment_id": 4,69 "name": "test1",70 "enable": True,71 }72 # ACT73 response = http_client.patch(74 "/v1/applications/netflix/features/",75 headers=prepare_headers(jwt_token),76 json=new_feature)77 # ASSERT78 assert response.status_code == status.HTTP_200_OK79 json = response.json()80 assert "The feature(test1) already exists this environment" in json["errors"]81@pytest.mark.parametrize("feature_name", ["test4", "test5", "test6"])82def test_patch_should_create_new_feature_in_all_environment(http_client, jwt_token, feature_name):83 # ARRANGE84 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))85 assert response.status_code == status.HTTP_200_OK86 initial_features = response.json()87 assert len(initial_features) > 088 new_feature = {89 "environment_id": 0,90 "name": feature_name,91 "enable": True,92 "all": True93 }94 # ACT95 response = http_client.patch(96 "/v1/applications/netflix/features/",97 headers=prepare_headers(jwt_token),98 json=new_feature)99 # ASSERT100 assert response.status_code == status.HTTP_200_OK101 json = response.json()102 assert len(initial_features) != len(json)103@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])104def test_patch_should_activate_feature_in_environment(http_client, jwt_token, feature_name):105 # ARRANGE106 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))107 assert response.status_code == status.HTTP_200_OK108 initial_features = response.json()109 assert len(initial_features) > 0110 # ACT111 response = http_client.patch(112 "/v1/applications/netflix/features/{feature_name}/1/activate",113 headers=prepare_headers(jwt_token))114 # ASSERT115 assert response.status_code == status.HTTP_200_OK116 json = response.json()117 for feature in json:118 if feature["name"] == feature_name and feature["environment_id"] == 1:119 assert feature["enable"]120@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])121def test_patch_should_not_activate_feature_in_environment_because_missing_token(http_client, jwt_token, feature_name):122 # ARRANGE123 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))124 assert response.status_code == status.HTTP_200_OK125 initial_features = response.json()126 assert len(initial_features) > 0127 # ACT128 response = http_client.patch(129 "/v1/applications/netflix/features/{feature_name}/1/activate",130 headers=prepare_headers())131 # ASSERT132 assert response.status_code == status.HTTP_200_OK133 json = response.json()134 assert "Not authenticated" in json["errors"]135@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])136def test_patch_should_activate_all_feature_in_all_environment(http_client, jwt_token, feature_name):137 # ARRANGE138 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))139 assert response.status_code == status.HTTP_200_OK140 initial_features = response.json()141 assert len(initial_features) > 0142 # ACT143 response = http_client.patch(144 "/v1/applications/netflix/features/activate-all",145 headers=prepare_headers(jwt_token))146 # ASSERT147 assert response.status_code == status.HTTP_200_OK148 json = response.json()149 for feature in json:150 assert feature["enable"]151@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])152def test_patch_should_not_activate_all_feature_in_all_environment_because_missing_token(http_client, jwt_token, feature_name):153 # ARRANGE154 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))155 assert response.status_code == status.HTTP_200_OK156 initial_features = response.json()157 assert len(initial_features) > 0158 # ACT159 response = http_client.patch(160 "/v1/applications/netflix/features/activate-all",161 headers=prepare_headers())162 # ASSERT163 assert response.status_code == status.HTTP_200_OK164 json = response.json()165 assert "Not authenticated" in json["errors"]166@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])167def test_patch_should_inactivate_feature_in_environment(http_client, jwt_token, feature_name):168 # ARRANGE169 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))170 assert response.status_code == status.HTTP_200_OK171 initial_features = response.json()172 assert len(initial_features) > 0173 # ACT174 response = http_client.patch(175 "/v1/applications/netflix/features/{feature_name}/1/inactivate",176 headers=prepare_headers(jwt_token))177 # ASSERT178 assert response.status_code == status.HTTP_200_OK179 json = response.json()180 for feature in json:181 if feature["name"] == feature_name and feature["environment_id"] == 1:182 assert not feature["enable"]183@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])184def test_patch_should_not_inactivate_feature_in_environment_because_missing_token(http_client, jwt_token, feature_name):185 # ARRANGE186 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))187 assert response.status_code == status.HTTP_200_OK188 initial_features = response.json()189 assert len(initial_features) > 0190 # ACT191 response = http_client.patch(192 "/v1/applications/netflix/features/{feature_name}/1/inactivate",193 headers=prepare_headers())194 # ASSERT195 assert response.status_code == status.HTTP_200_OK196 json = response.json()197 assert "Not authenticated" in json["errors"]198@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])199def test_patch_should_inactivate_all_feature_in_all_environment(http_client, jwt_token, feature_name):200 # ARRANGE201 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))202 assert response.status_code == status.HTTP_200_OK203 initial_features = response.json()204 assert len(initial_features) > 0205 # ACT206 response = http_client.patch(207 "/v1/applications/netflix/features/inactivate-all",208 headers=prepare_headers(jwt_token))209 # ASSERT210 assert response.status_code == status.HTTP_200_OK211 json = response.json()212 for feature in json:213 assert not feature["enable"]214@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])215def test_patch_should_not_inactivate_all_feature_in_all_environment_because_missing_token(http_client, jwt_token, feature_name):216 # ARRANGE217 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))218 assert response.status_code == status.HTTP_200_OK219 initial_features = response.json()220 assert len(initial_features) > 0221 # ACT222 response = http_client.patch(223 "/v1/applications/netflix/features/inactivate-all",224 headers=prepare_headers())225 # ASSERT226 assert response.status_code == status.HTTP_200_OK227 json = response.json()228 assert "Not authenticated" in json["errors"]229@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])230def test_delete_should_feature_application(http_client, jwt_token, feature_name):231 # ARRANGE & ACT232 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))233 assert response.status_code == status.HTTP_200_OK234 initial_features = response.json()235 assert len(initial_features) > 0236 # ACT237 response = http_client.delete(f"/v1/applications/netflix/features/{feature_name}", headers=prepare_headers(jwt_token))238 # ASSERT239 assert response.status_code == status.HTTP_200_OK240 json = response.json()241 assert len(initial_features) != len(json)242@pytest.mark.parametrize("feature_name", ["test1", "test2", "test3"])243def test_delete_should_not_feature_application_because_missing_token(http_client, jwt_token, feature_name):244 # ARRANGE & ACT245 response = http_client.get("/v1/applications/netflix/features/", headers=prepare_headers(jwt_token))246 assert response.status_code == status.HTTP_200_OK247 initial_features = response.json()248 assert len(initial_features) > 0249 # ACT250 response = http_client.delete(f"/v1/applications/netflix/features/{feature_name}", headers=prepare_headers())251 # ASSERT252 assert response.status_code == status.HTTP_200_OK253 json = response.json()254 assert "Not authenticated" in json["errors"]255def teardown_module(module):...
test_http_client.py
Source:test_http_client.py
...23 path = format(example_cert.parent.parent)24 path_file = format(example_cert.name)25 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")26 http_client.certify(path=path, path_file=path_file, lvl="debug")27 r = http_client()28 assert http_client.certify.store.subject == {"common_name": "example.com"}29 assert http_client.url in format(http_client)30 assert http_client.url in repr(http_client)31 assert path_file in format(http_client.certify)32 assert path_file in repr(http_client.certify)33 assert isinstance(r, requests.Response)34 entries = [35 "Default certificate for .*? is not valid, will find/get one",36 "Certificate at .*? is valid for URL",37 ]38 log_check(caplog, entries)39 def test_hostname_cert(self, caplog, tmp_path, httpsbin_cert, log_check):40 """Test supplying no path_file finds hostname based cert in path."""41 caplog.set_level(logging.DEBUG)42 server, example_cert = httpsbin_cert43 url = server()44 url_parsed = requests.compat.urlparse(url)45 path = tmp_path46 certs_path = path / "certs"47 certs_path.mkdir(parents=True, exist_ok=True)48 host_cert_file = "{}.pem".format(url_parsed.hostname)49 host_cert_path = certs_path / host_cert_file50 shutil.copy(format(example_cert), format(host_cert_path))51 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")52 http_client.certify(path=path, lvl="debug")53 http_client()54 assert http_client.certify.store.subject == {"common_name": "example.com"}55 entries = [56 "Default certificate for .*? is not valid, will find/get one",57 "Certificate at .*? is valid for URL",58 ]59 log_check(caplog, entries)60 def test_already_valid_cert(self, caplog, httpsbin_cert, log_check):61 """Test OS env based cert file works with out specifying path/path_file."""62 caplog.set_level(logging.DEBUG)63 server, example_cert = httpsbin_cert64 url = server()65 os.environ["REQUESTS_CA_BUNDLE"] = format(example_cert)66 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")67 http_client.certify(lvl="debug")68 http_client()69 del (os.environ["REQUESTS_CA_BUNDLE"])70 assert http_client.certify.store.subject == {"common_name": "example.com"}71 entries = ["Default certificate for .*? is valid, not setting custom cert."]72 log_check(caplog, entries)73 def test_missing_cert_user_yes(74 self, caplog, capsys, tmp_path, httpsbin_cert, log_check, monkeypatch75 ):76 """Test use saying yes to is cert valid works."""77 caplog.set_level(logging.DEBUG)78 server, example_cert = httpsbin_cert79 url = server()80 monkeypatch.setattr("pytan3.http_client.SHOW_CERT", "yes")81 monkeypatch.setattr("pytan3.http_client.SHOW_CHAIN", "yes")82 monkeypatch.setattr("pytan3.http_client.CERT_VALID", "yes")83 with pytest.warns(pytan3.http_client.exceptions.CertificateNotFoundWarning):84 with capsys.disabled():85 inputs = ["y", "y", "y"]86 with input_mocker.InputMocker(inputs=inputs):87 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")88 http_client.certify(path=tmp_path, lvl="debug")89 assert http_client.certify.store.subject == {"common_name": "example.com"}90 entries = ["Wrote certificate for"]91 log_check(caplog, entries)92 def test_missing_cert_osenv_yes(93 self, caplog, capsys, tmp_path, httpsbin_cert, log_check94 ):95 """Test setting PYTAN_CERT_VALID env var makes valid prompt default=yes."""96 caplog.set_level(logging.DEBUG)97 server, example_cert = httpsbin_cert98 url = server()99 os.environ["PYTAN_CERT_VALID"] = "y"100 with pytest.warns(pytan3.http_client.exceptions.CertificateNotFoundWarning):101 with capsys.disabled():102 inputs = ["", "", ""]103 with input_mocker.InputMocker(inputs=inputs):104 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")105 http_client.certify(path=tmp_path, lvl="debug")106 del (os.environ["PYTAN_CERT_VALID"])107 assert http_client.certify.store.subject == {"common_name": "example.com"}108 entries = ["Wrote certificate for"]109 log_check(caplog, entries)110 def test_missing_cert_verify_hook_false(111 self, caplog, tmp_path, httpsbin_cert, log_check112 ):113 """Test verify_hook=False does not do validity prompting."""114 caplog.set_level(logging.DEBUG)115 server, example_cert = httpsbin_cert116 url = server()117 with pytest.warns(pytan3.http_client.exceptions.CertificateNotFoundWarning):118 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")119 http_client.certify(path=tmp_path, verify_hook=False, lvl="debug")120 assert http_client.certify.store.subject == {"common_name": "example.com"}121 entries = ["Wrote certificate for"]122 log_check(caplog, entries)123 def test_missing_cert_user_no(self, tmp_path, httpsbin_cert):124 """Test exc thrown when user says no to validity prompt."""125 server, example_cert = httpsbin_cert126 url = server()127 with pytest.warns(pytan3.http_client.exceptions.CertificateNotFoundWarning):128 with pytest.raises(pytan3.http_client.exceptions.CertificateInvalidError):129 inputs = ["n", "n", "n"]130 with input_mocker.InputMocker(inputs=inputs):131 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")132 http_client.certify(path=tmp_path, lvl="debug")133 def test_invalid_cert(self, httpsbin_cert, other_cert):134 """Test exc thrown if wrong cert provided."""135 server, example_cert = httpsbin_cert136 url = server()137 path_file = format(other_cert.name)138 path = format(other_cert.parent.parent)139 with pytest.raises(pytan3.http_client.exceptions.CertificateInvalidError):140 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")141 http_client.certify(path=path, path_file=path_file, lvl="debug")142 def test_record_history(self, httpsbin_cert):143 """Test record_history adds responses to history attr."""144 server, example_cert = httpsbin_cert145 url = server()146 path = format(example_cert.parent.parent)147 path_file = format(example_cert.name)148 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")149 http_client.certify(path=path, path_file=path_file, lvl="debug")150 http_client.control_hook_record_history(enable=True)151 r = http_client()152 assert r in http_client.history153 http_client.control_hook_record_history(enable=False)154 r = http_client()155 assert r not in http_client.history156 def test_record_disk(self, httpsbin_cert, tmp_path):157 """Test record_disk writes responses to disk as json."""158 server, example_cert = httpsbin_cert159 url = server()160 path = format(example_cert.parent.parent)161 path_file = format(example_cert.name)162 http_client = pytan3.http_client.HttpClient(url=url, lvl="debug")163 http_client.certify(path=path, path_file=path_file, lvl="debug")164 http_client.control_hook_record_disk(enable=True, path=tmp_path)165 r = http_client()166 assert hasattr(r, "record_path")167 assert r.record_path.is_file()168 assert json.loads(r.record_path.read_text())169 http_client.control_hook_record_disk(enable=False)170 r = http_client()171 assert not hasattr(r, "record_path")172 def test_clean_auth(self):173 """Test headers get cleaned in request to auth api."""174 httpretty.enable()175 httpretty.register_uri(176 method=httpretty.POST,177 uri="http://pytantest:443/auth",178 body="session",179 status=200,180 )181 http_client = pytan3.http_client.HttpClient(url="http://pytantest:443")182 headers = {"username": "dunder"}183 r = http_client(method="post", path="auth", headers=headers)184 assert r.request.clean_headers["username"] == "###HIDDEN###"185 httpretty.disable()186 httpretty.reset()187 def test_clean_auth_rest(self):188 """Test headers get cleaned in request to rest session api."""189 httpretty.enable()190 response_body = json.dumps({"text": {"session": "moo"}})191 httpretty.register_uri(192 method=httpretty.POST,193 uri="http://pytantest:443/api/v2/session/login",194 body=response_body,195 status=200,196 )197 http_client = pytan3.http_client.HttpClient(url="http://pytantest:443")198 # bytes so no pyopenssl warning on py2 # TODO(!) in client??199 body = json.dumps({"username": "dunder"})200 r = http_client(method="post", path="/api/v2/session/login", data=body)201 clean_body = json.loads(r.request.clean_body)202 assert clean_body["username"] == "###HIDDEN###"203 httpretty.disable()...
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!!