Best Python code snippet using playwright-python
tests.py
Source:tests.py
1import time2from django.test import TestCase3from django.conf.urls.defaults import *4from django.http import HttpResponse5from django.conf import settings6import paranoidsessions7def test_view(request):8 """Simple little view for testing purposes.9 This adds a unique timestamp into the session if it doesn't already10 have one; used to make sure no info leaks between sessions.11 """12 if "timestamp" not in request.session:13 request.session["timestamp"] = time.time()14 return HttpResponse("OK")15def request_filter(request):16 """Test filtering of requests; anything with "safe" in it is filtered."""17 if "safe" in request.path:18 return False19 return True20urlpatterns = patterns('',21 (r'^$', test_view), 22 (r'^safeview$', test_view),23)24def with_settings(**new_settings):25 """Decorator to temporarily change django settings during a test."""26 def with_settings_dec(func):27 def newfunc(*args,**kwds):28 old_settings = {}29 for (key,value) in new_settings.iteritems():30 old_settings[key] = getattr(settings,key)31 setattr(settings,key,value)32 try:33 return func(*args,**kwds)34 finally:35 for (key,value) in old_settings.iteritems():36 setattr(settings,key,value)37 return newfunc38 return with_settings_dec39class TestParanoidSessions(TestCase):40 """Testcases for paranoidsessions module."""41 urls = "paranoidsessions.tests"42 def setUp(self):43 self.orig_clear_session = settings.PSESSION_CLEAR_SESSION_FUNCTION44 settings.PSESSION_CLEAR_SESSION_FUNCTION = lambda r: r.session.flush()45 def tearDown(self):46 settings.PSESSION_CLEAR_SESSION_FUNCTION = self.orig_clear_session47 @with_settings(PSESSION_SECURE_COOKIE_NAME="secureid")48 def test_secure_key_handling(self):49 # No secure key gets sent as it's not a secure request50 r = self.client.get("/")51 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value52 self.assertFalse("secureid" in self.client.cookies)53 # Secure key generated and sent in secure cookie54 r = self.client.get("/",**{"wsgi.url_scheme":"https"})55 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value56 key1 = self.client.cookies["secureid"].value57 self.assertEquals(session1,session2)58 self.assertTrue(self.client.cookies["secureid"]["secure"])59 # Additional request accepted, key not sent again60 r = self.client.get("/",**{"wsgi.url_scheme":"https"})61 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value62 self.assertEquals(session1,session3)63 self.assertFalse("secureid" in r.cookies)64 # Insecure requests are accepted with an invalid secure key65 # (Django test client dosen't respect 'secure' cookie setting)66 self.client.cookies["secureid"] = "invalid"67 r = self.client.get("/")68 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value69 self.assertEquals(session1,session4)70 self.assertFalse("secureid" in r.cookies)71 # And with no secure key at all72 del self.client.cookies["secureid"]73 r = self.client.get("/")74 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value75 self.assertEquals(session1,session4)76 self.assertFalse("secureid" in r.cookies)77 # But secure requests are rejected with an invalid key78 self.client.cookies["secureid"] = "invalid"79 r = self.client.get("/",**{"wsgi.url_scheme":"https"})80 session5 = self.client.cookies[settings.SESSION_COOKIE_NAME].value81 key2 = self.client.cookies["secureid"].value82 self.assertNotEquals(session1,session5)83 self.assertNotEquals(key1,key2)84 # Rejected session is new, and works OK85 r = self.client.get("/",**{"wsgi.url_scheme":"https"})86 session6 = self.client.cookies[settings.SESSION_COOKIE_NAME].value87 self.assertEquals(session5,session6)88 # But is rejected again when secureid is not provided89 del self.client.cookies["secureid"]90 r = self.client.get("/",**{"wsgi.url_scheme":"https"})91 session7 = self.client.cookies[settings.SESSION_COOKIE_NAME].value92 self.assertNotEquals(session5,session7)93 # It's possible to directly start a session over secure connection94 del self.client.cookies[settings.SESSION_COOKIE_NAME]95 r = self.client.get("/",**{"wsgi.url_scheme":"https"})96 session8 = self.client.cookies[settings.SESSION_COOKIE_NAME].value97 self.assertNotEquals(session8,session7)98 r = self.client.get("/",**{"wsgi.url_scheme":"https"})99 session9 = self.client.cookies[settings.SESSION_COOKIE_NAME].value100 self.assertEquals(session8,session9)101 @with_settings(PSESSION_NONCE_TIMEOUT=0)102 def test_nonce_generation(self):103 # We are initially assigned a nonce104 r = self.client.get("/")105 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value106 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value107 # And the next request gets a new one108 r = self.client.get("/")109 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value110 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value111 self.assertEqual(session1,session2)112 self.assertNotEqual(nonce1,nonce2)113 @with_settings(PSESSION_NONCE_TIMEOUT=0.2)114 def test_nonce_timeout(self):115 # We keep the same nonce for a few requests116 r = self.client.get("/")117 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value118 r = self.client.get("/")119 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value120 self.assertEqual(nonce1,nonce2)121 # But get a new one after the timeout122 time.sleep(0.2)123 r = self.client.get("/")124 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value125 self.assertNotEqual(nonce1,nonce2)126 @with_settings(PSESSION_NONCE_TIMEOUT=0)127 def test_invalid_nonce(self):128 # Proving proper nonces gives access to our session data129 r = self.client.get("/")130 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value131 timestamp1 = self.client.session["timestamp"]132 r = self.client.get("/")133 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value134 timestamp2 = self.client.session["timestamp"]135 self.assertEqual(session1,session2)136 self.assertEqual(timestamp1,timestamp2)137 # But an invalid nonce gets us booted into a fresh session138 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = "invalid"139 r = self.client.get("/")140 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value141 timestamp3 = self.client.session["timestamp"]142 self.assertNotEqual(session1,session3)143 self.assertNotEqual(timestamp1,timestamp3)144 @with_settings(PSESSION_NONCE_WINDOW=2,PSESSION_NONCE_TIMEOUT=0)145 def test_nonce_window(self):146 # Generate two nonces, we'll use the old one for requests147 r = self.client.get("/")148 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value149 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value150 r = self.client.get("/")151 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value152 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value153 self.assertEqual(session1,session2)154 # Use the old nonce, it should still work155 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1156 r = self.client.get("/")157 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value158 self.assertEqual(session1,session3)159 # Use the old nonce again, it should still work160 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1161 r = self.client.get("/")162 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value163 self.assertEqual(session1,session3)164 # But using it a third time should fail165 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1166 r = self.client.get("/")167 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value168 self.assertNotEqual(session1,session4)169 @with_settings(PSESSION_NONCE_WINDOW=3,PSESSION_NONCE_TIMEOUT=0,PSESSION_NONCE_WINDOW_TIMEOUT=0.2)170 def test_nonce_window_timeout(self):171 # Generate two nonces, we'll use the old one for requests172 r = self.client.get("/")173 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value174 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value175 r = self.client.get("/")176 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value177 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value178 self.assertEqual(session1,session2)179 # Use the old nonce, it should still work180 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1181 r = self.client.get("/")182 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value183 self.assertEqual(session1,session3)184 # After the window timeout has elapsed, we get our session booted.185 time.sleep(0.2)186 self.client.cookies[settings.PSESSION_COOKIE_NAME].value = nonce1187 r = self.client.get("/")188 session4 = self.client.cookies[settings.SESSION_COOKIE_NAME].value189 self.assertNotEqual(session1,session4)190 @with_settings(PSESSION_KEY_TIMEOUT=0.2)191 def test_key_timeout(self):192 # No nonces here, just check the session key.193 r = self.client.get("/")194 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value195 timestamp1 = self.client.session["timestamp"]196 # Session key stays the same for a while197 r = self.client.get("/")198 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value199 timestamp2 = self.client.session["timestamp"]200 self.assertEqual(session1,session2)201 self.assertEqual(timestamp1,timestamp2)202 # But is cycled after the timeout has elapsed203 time.sleep(0.2)204 r = self.client.get("/")205 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value206 timestamp3 = self.client.session["timestamp"]207 self.assertNotEqual(session1,session3)208 self.assertEqual(timestamp1,timestamp3)209 @with_settings(PSESSION_CHECK_HEADERS=["REMOTE_ADDR","HTTP_USER_AGENT"])210 def test_check_headers(self):211 # Test a missing header suddenly appearing212 r = self.client.get("/")213 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value214 r = self.client.get("/",HTTP_USER_AGENT="attacker")215 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value216 self.assertNotEqual(session1,session2)217 # Test a header changing its value218 r = self.client.get("/",HTTP_USER_AGENT="goodguy")219 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value220 r = self.client.get("/",HTTP_USER_AGENT="badguy")221 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value222 self.assertNotEqual(session1,session2)223 # Test a header disappearing224 r = self.client.get("/",HTTP_USER_AGENT="goodguy")225 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value226 r = self.client.get("/")227 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value228 self.assertNotEqual(session1,session2)229 # Test a change and a disappear230 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")231 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value232 r = self.client.get("/",REMOTE_ADDR="yyy")233 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value234 self.assertNotEqual(session1,session2)235 # Test everything staying the same236 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")237 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value238 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")239 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value240 self.assertEqual(session1,session2)241 r = self.client.get("/",HTTP_USER_AGENT="goodguy",REMOTE_ADDR="xxx")242 session3 = self.client.cookies[settings.SESSION_COOKIE_NAME].value243 self.assertEqual(session1,session3)244 @with_settings(PSESSION_REQUEST_FILTER_FUNCTION=request_filter,PSESSION_CHECK_HEADERS=["HTTP_USER_AGENT"])245 def test_request_filter(self):246 r = self.client.get("/")247 session1 = self.client.cookies[settings.SESSION_COOKIE_NAME].value248 nonce1 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value249 # Requests to the safe view aren't validated250 r = self.client.get("/safeview",HTTP_USER_AGENT="attacker")251 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value252 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value253 self.assertEqual(session1,session2)254 self.assertEqual(nonce1,nonce2)255 # But requests to the other view get booted256 r = self.client.get("/",HTTP_USER_AGENT="attacker")257 session2 = self.client.cookies[settings.SESSION_COOKIE_NAME].value258 nonce2 = self.client.cookies[settings.PSESSION_COOKIE_NAME].value259 self.assertNotEqual(session1,session2)...
api.py
Source:api.py
1__author__ = 'powergx'2import json3import requests4from crysadm_helper import r_session5from requests.adapters import HTTPAdapter6import time7from urllib.parse import urlparse, parse_qs8requests.packages.urllib3.disable_warnings()9# è¿
é·APIæ¥å£10appversion = '3.1.1'11server_address = 'http://2-api-red.xunlei.com'12agent_header = {'user-agent': "RedCrystal/3.0.0 (iPhone; iOS 9.9; Scale/2.00)"}13# è´è½½åè¡¡14def api_proxies():15 return {}16# æ交è¿
é·é¾æ¥ï¼è¿åä¿¡æ¯17def api_post(cookies, url, data, verify=False, headers=agent_header, timeout=60):18 address = server_address + url19 try:20 proxies = api_proxies()21 r = requests.post(url=address, data=data, proxies=proxies, verify=verify, headers=headers, cookies=cookies, timeout=timeout) 22 except requests.exceptions.RequestException as e:23 return __handle_exception(e=e)24 if r.status_code != 200: 25 return __handle_exception(rd=r.reason)26 return json.loads(r.text)27# ç³è¯·æç°è¯·æ±28def exec_draw_cash(cookies, limits=None):29 r = get_can_drawcash(cookies)30 if r.get('r') != 0:31 return r32 if r.get('is_tm') == 0:33 return dict(r=0, rd=r.get('tm_tip'))34 r = get_balance_info(cookies)35 if r.get('r') != 0:36 return r37 wc_pkg = r.get('wc_pkg')38 if limits is not None and wc_pkg < limits: 39 return dict(r=1, rd='å¸æ·éé¢å°äºä¸éå¼%så
' % limits)40 if wc_pkg > 200:41 wc_pkg = 20042 r = draw_cash(cookies, wc_pkg)43 if r.get('r') != 0:44 return r45 return r46# è·åæç°ä¿¡æ¯47def get_can_drawcash(cookies):48 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'49 body = dict(v='1', appversion=appversion)50 return api_post(url='/?r=usr/drawcashInfo', data=body, cookies=cookies)51# æ£æµæç°ä½é¢52def get_balance_info(cookies):53 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'54 body = dict(v='2', appversion=appversion)55 return api_post(url='/?r=usr/asset', data=body, cookies=cookies)56# æ交æç°è¯·æ±57def draw_cash(cookies, money):58 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'59 body = dict(v='3', m=str(money))60 return api_post(url='?r=usr/drawpkg', data=body, cookies=cookies)61# è·åMINEä¿¡æ¯62def get_mine_info(cookies):63 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'64 body = dict(v='4', appversion=appversion)65 return api_post(url='/?r=mine/info', data=body, cookies=cookies)66# è·åæ¶çä¿¡æ¯67def get_produce_stat(cookies):68 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'69 body = dict(appversion=appversion)70 return api_post(url="/?r=mine/produce_stat", data=body, cookies=cookies)71# è·åé度ç¶æ72def get_speed_stat(cookies):73 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'74 try:75 proxies = api_proxies()76 r = requests.post(server_address + '/?r=mine/speed_stat', data=None, proxies=proxies, verify=False, cookies=cookies, headers=agent_header, timeout=60)77 except requests.exceptions.RequestException as e:78 __handle_exception(e=e)79 return [0] * 2480 if r.status_code != 200:81 __handle_exception(rd=r.reason)82 return [0] * 2483 return json.loads(r.text).get('sds')84# è·å个人信æ¯85def get_privilege(cookies):86 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'87 body = dict(v='1', appversion=appversion, ver=appversion)88 return api_post(url='/?r=usr/privilege', data=body, cookies=cookies)89# è·å设å¤ç¶æ90def get_device_stat(s_type, cookies):91 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'92 body = dict(type=s_type, hand='0', v='2', ver='1')93 return api_post(url='/?r=mine/devices_stat', data=body, cookies=cookies)94# æ交æ¶éæ°´æ¶è¯·æ±95def collect(cookies):96 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'97 return api_post(url='/index.php?r=mine/collect', data=None, cookies=cookies)98# è·åå®ç®±ä¿¡æ¯99def api_giftbox(cookies):100 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'101 body = dict(tp='0', p='0', ps='60', t='', v='2', cmid='-1')102 return api_post(url='/?r=usr/giftbox', data=body, cookies=cookies)103# æ交æå¼å®ç®±è¯·æ±104def api_openStone(cookies, giftbox_id, direction):105 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'106 body = dict(v='1', id=str(giftbox_id), side=direction)107 return api_post(url='/?r=usr/openStone', data=body, cookies=cookies)108# æ交æ¾å¼å®ç®±è¯·æ±109def api_giveUpGift(cookies, giftbox_id):110 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'111 body = dict(v='2', id=str(giftbox_id), tag='0')112 return api_post(url='/?r=usr/giveUpGift', data=body, cookies=cookies)113# è·å幸è¿è½¬çä¿¡æ¯114def api_getconfig(cookies):115 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'116 return api_post(url='/?r=turntable/getconfig', data=None, cookies=cookies)117# æ交幸è¿è½¬ç请æ±118def api_getaward(cookies):119 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'120 return api_post(url='/?r=turntable/getaward', data=None, cookies=cookies)121# è·åç§é¶è¿æ»ä¿¡æ¯122def api_sys_getEntry(cookies):123 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'124 body = dict(v='6')125 return api_post(url='/?r=sys/getEntry', data=body, cookies=cookies)126# è·åç§é¶å¤ä»ä¿¡æ¯127def api_steal_stolenSilverHistory(cookies):128 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'129 body = dict(v='2', p='0', ps='20')130 return api_post(url='/?r=steal/stolenSilverHistory', data=body, cookies=cookies)131# æ交ç§é¶è¿æ»è¯·æ±132def api_steal_search(cookies, searcht_id=0):133 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'134 body = dict(v='2', sid=str(searcht_id))135 return api_post(url='/?r=steal/search', data=body, cookies=cookies)136# æ交æ¶éç§é¶è¯·æ±137def api_steal_collect(cookies, searcht_id):138 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'139 body = dict(sid=str(searcht_id), cmid='-2', v='2')140 return api_post(url='/?r=steal/collect', data=body, cookies=cookies)141# æ交è¿æ»ç»æ请æ±142def api_steal_summary(cookies, searcht_id):143 cookies['origin'] = '4' if len(cookies.get('sessionid')) == 128 else '1'144 body = dict(sid=str(searcht_id), v='2')145 return api_post(url='/?r=steal/summary', data=body, cookies=cookies)146# è·åæååå¨ç¸å
³ä¿¡æ¯147def ubus_cd(session_id, account_id, action, out_params, url_param=None):148 url = "http://kjapi.peiluyou.com:5171/ubus_cd?account_id=%s&session_id=%s&action=%s" % (account_id, session_id, action)149 if url_param is not None:150 url += url_param151 params = ["%s" % session_id] + out_params152 data = {"jsonrpc": "2.0", "id": 1, "method": "call", "params": params}153 try:154 body = dict(data=json.dumps(data), action='onResponse%d' % int(time.time() * 1000))155 s = requests.Session()156 s.mount('http://', HTTPAdapter(max_retries=5))157 proxies = api_proxies()158 r = s.post(url, data=body, proxies=proxies)159 result = r.text[r.text.index('{'):r.text.rindex('}')+1]160 return json.loads(result)161 except requests.exceptions.RequestException as e:162 return __handle_exception(e=e)163# åé设置é¾æ¥164def parse_setting_url(url):165 query_s = parse_qs(urlparse(url).query, keep_blank_values=True)166 device_id = query_s['device_id'][0]167 session_id = query_s['session_id'][0]168 account_id = query_s['user_id'][0]169 return device_id, session_id, account_id170# æ£æµæ¯å¦APIé误171def is_api_error(r):172 if r.get('r') == -12345:173 return True174 return False175# æ¥å£æ
é176def __handle_exception(e=None, rd='æ¥å£æ
é', r=-12345):177 if e is None:178 print(rd)179 else:180 print(e)181 b_err_count = r_session.get('api_error_count')182 if b_err_count is None:183 r_session.setex('api_error_count', '1', 60)184 return dict(r=r, rd=rd)185 err_count = int(b_err_count.decode('utf-8')) + 1186 if err_count > 200:187 r_session.setex('api_error_info', 'è¿
é·ç¿åºAPIæ
éä¸,æ»åç®æ£å¨èµ¶å¾äºæ
ç°åº,请èå¿çå¾
.', 60)188 err_count_ttl = r_session.ttl('api_error_count')189 if err_count_ttl is None:190 err_count_ttl = 30191 r_session.setex('api_error_count', str(err_count), err_count_ttl + 1)192 return dict(r=r, rd=rd)...
main.py
Source:main.py
1#coding:utf-82import BeautifulSoup3import requests4from requests.cookies import RequestsCookieJar5import time6import re7import os8import sys9import json10from generic_variables import *11'''12get a raw_inpupt13return the striped string from the raw_input14'''15def GetRawInput(str = ''):16 message = str(raw_input(str))17 return message.strip()18'''19Read the recorded Cookies values20if get the cookies then return it 21else return None22'''23def ReadCookies():24 jar = RequestsCookieJar()25 try:26 with open('cookies.txt','r') as f:27 cookies = json.load(f)28 # print type(cookies)29 for cookie in cookies:30 # print cookie31 # jar.set(cookie["name"],cookie["value"])32 jar.set(cookie,cookies[cookie])33 # print jar34 except :35 # print 'get cookie error'36 return None37 return jar38'''39Save the Cookies value 40get a cookies and save it to 'cookies.txt' file41if saved successfully return True42else return False43'''44def SaveCookies(cookies):45 print 'save cookies',cookies46 cookies = requests.utils.dict_from_cookiejar(cookies)47 # print cookies48 try:49 with open('cookies.txt','w') as f:50 json.dump(cookies,f)51 except :52 # print 'save cookie error'53 return False54 return True55'''56Update the cookies value through access the LoginUrl and call SaveCookies57'''58def RenewCookies():59 # print 'renew the cookies'60 SaveCookies(requests.get(LoginUrl).cookies)61'''62check whether the cookies is valuable 63get the session(have the cookies)64if the session can get the home page return True65else return False66'''67def CheckCookies(session):68 print 'CheckCookies',session.cookies69 rsq =session.get(LoginUrl+'/Home/StudentIndex')70 rr = re.compile(r'1\d{7}')71 # print rsq.content72 s = rr.findall(rsq.content)73 # print s74 if s != []:75 return True76 else :77 return False78'''79get the session that has the valuable cookies to login 80'''81def GetSession():82 session = requests.session()83 cookie = ReadCookies()84 if cookie != None :85 # print 'cookie is not none'86 session.cookies = cookie87 if (CheckCookies(session)):88 # print 'check login seccess'89 return session90 else:91 RenewCookies()92 cookie = ReadCookies()93 session.cookies = cookie94 LoginCMS(session)95 if (CheckCookies(session)):96 return session97 RenewCookies()98 GetSession()99'''100to get login the CurriculumManagementSystem101get a session that hasn't been logged in yet102get the Username and Password through input 103return a response from login104'''105def LoginCMS(session):106 UserName = GetRawInput('input the Username:')107 UserPassword = GetRawInput('input the Password:')108 ValidateCode = GetVc(session)109 print 'logincmscookie:',session.cookies110 parms = {'txtUserName':UserName,'txtPassword':UserPassword,'txtvaliCode':ValidateCode}111 return session.post(LoginUrl,parms)112'''113get the ValidateCode114get the validatecode through input and return it115'''116def GetVc(session):117 print 'getvccookie:',session.cookies118 res = session.get(LoginUrl+ValidateCodeUrl)119 with open('validatecode.png','wb') as f:120 f.write(res.content)121 return str(raw_input('input the validatecode:'))122'''123get the student course table message124get the logged session and access the trul url125save the response to a html file126'''127def GetCrouseTable(session):128 QueryCTUrl = LoginUrl+QueryCourseTableUrl129 # QueryCTUrl = 'http://xk.autoisp.shu.edu.cn:8080/StudentQuery/CtrlViewQueryCourseTable'130 rsp = session.get(QueryCTUrl)131 # print rsp.content132 with open('coursetable.html', 'wb')as f:133 f.write(rsp.content)134'''135get the student course rank table message136get the logged session and access the trul url137save the response to a html file138'''139def GetEnrollRankTable(session):140 QueryERUrl = LoginUrl+QueryEnrollRankUrl141 rsp = session.get(QueryERUrl)142 # print rsp.content143 with open('enrollranktable.html', 'wb')as f:144 f.write(rsp.content)145'''146get the student deleted course table message147get the logged session and access the trul url148save the response to a html file149'''150def GetDeleteCourseTable(session):151 QueryERUrl = LoginUrl+QueryDeleteCourseUrl152 rsp = session.get(QueryERUrl)153 # print rsp.content154 with open('deletecoursetable.html', 'wb')as f:155 f.write(rsp.content)156'''157get the student deleted course table message158get the logged session and access the trul url159save the response to a html file160'''161def GetQueryParmsData():162 ParmsName = ['CourseNo', 'CourseName', 'TeachNo', 'TeachName',163 'CourseTime', 'NotFull', 'Credit', 'Campus', 'Enrolls',164 'DataCount', 'MinCapacicy', 'MaxCapacity', 'PageIndex',165 'PageSize', 'FunctionString']166 # ParmsValue = ['12', '', '', '',167 # '', 'false', '', '0', '',168 # '0', '', '', '1',169 # '1000', 'InitPage']170 parms = {}171 for i in ParmsName:172 if i == 'NotFull':173 print i ,":0 is false and 1 is true,default false"174 print "input your choose [0/1]:"175 ForT = GetRawInput()176 parms[i] = 'false'177 if ForT == 1:178 parms[i] = 'true'179 elif i == 'Campus':180 print i,":get 7 choose"181 print "0ï¼å
¨é¨ 1ï¼æ¬é¨ 2ï¼å»¶é¿ 3ï¼åå® 4ï¼å¾
ç¨ 5ï¼å¾ç» 6ï¼å®å±±ä¸æ ¡åº"182 print "input you choose [0-6]:"183 ChooseCampus = GetRawInput()184 if ChooseCampus!='':185 parms[i] = ChooseCampus186 else:187 parms[i] = 0188 elif i == 'DataCount':189 print i,":0 is not limit and other num is the response data num"190 LimitDataCount = GetRawInput()191 if LimitDataCount != '':192 parms[i] = LimitDataCount193 else:194 parms[i] = 0195 elif i == 'PageSize':196 print i,"default 20:"197 PageSize = GetRawInput()198 if PageSize != '':199 parms[i] = PageSize200 else:201 parms[i] = 20202 elif i == 'FunctionString':203 parms[i] = 'InitPage'204 elif i == 'PageIndex':205 PageIndex = GetRawInput()206 if PageIndex != '':207 parms[i] = PageIndex208 else:209 parms[i] = 1210 else:211 print i,":"212 parms[i] = GetRawInput()213 return parms214'''215'''216def GetQueryCourseTable(session):217 QueryERUrl = LoginUrl+QueryCourseTUrl218 # QueryERUrl ='http://xk.autoisp.shu.edu.cn:8080/StudentQuery/CtrlViewQueryCourse'219 headers = {220 "Host": "xk.autoisp.shu.edu.cn:8080",221 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0",222 "Accept": "*/*",223 "Accept-Language": "en-US,en;q=0.5",224 "Accept-Encoding": "gzip, deflate",225 "Content-Type": "application/x-www-form-urlencoded",226 "X-Requested-With": "XMLHttpRequest",227 "Referer": "http://xk.autoisp.shu.edu.cn:8080/StudentQuery/QueryCourse",228 "Content-Length": "181",229 }230 parms = GetQueryParmsData()231 rsp = session.post(QueryERUrl,parms,headers=headers)232 print rsp.content233 with open('querycoursetable.html', 'wb')as f:234 f.write(rsp.content)235'''236'''237def ValiWhereValue(session):238 QueryERUrl = 'http://xk.autoisp.shu.edu.cn:8080/Login/ValiWhereValue'239 headers = {240 "Host": "xk.autoisp.shu.edu.cn:8080",241 "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0",242 "Accept": "*/*",243 "Accept-Language": "en-US,en;q=0.5",244 "Accept-Encoding": "gzip, deflate",245 "Content-Type": "application/x-www-form-urlencoded",246 "X-Requested-With": "XMLHttpRequest",247 "Referer": "http://xk.autoisp.shu.edu.cn:8080/StudentQuery/QueryCourse",248 "Content-Length": "121",249 }250 ParmsName = ['CourseNo','CourseName','TeachNo','TeachName',251 'CourseTime','NotFull','Credit','Campus','Enrolls',252 'MinCapacicy','MaxCapacity']253 # ParmsValue = []254 ParmsValue = ['12', '', '', '',255 '', 'false', '', '0', '','','',]256 parms = {}257 for i in range(len(ParmsName)):258 print "input the ",ParmsName[i],":"259 # parms[ParmsName[i]] = GetRawInput()260 print ParmsValue[i]261 parms[ParmsName[i]] = ParmsValue[i]262 print parms263 rsp = session.post(QueryERUrl,data=parms,headers = headers)264 print rsp.content265 with open('vali.html', 'wb')as f:266 f.write(rsp.content)267'''268'''269if __name__ == '__main__':270 session = GetSession()271 GetCrouseTable(session)272 GetEnrollRankTable(session)273 GetDeleteCourseTable(session)274 # ValiWhereValue(session)...
test_auth_tkt.py
Source:test_auth_tkt.py
...14 '''15 The returned cookies are in the format we expect, with HttpOnly flag.16 '''17 plugin = make_plugin(secret='sosecret')18 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},19 value='HELLO')20 expected_cookies = [21 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),22 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),23 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')24 ]25 assert cookies == expected_cookies26 @helpers.change_config('who.httponly', False)27 def test_httponly_expected_cookies_with_config_httponly_false(self):28 '''29 The returned cookies are in the format we expect, without HttpOnly30 flag.31 '''32 plugin = make_plugin(secret='sosecret')33 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},34 value='HELLO')35 expected_cookies = [36 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/'),37 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0'),38 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0')39 ]40 assert cookies == expected_cookies41 def test_httponly_expected_cookies_without_config_httponly(self):42 '''43 The returned cookies are in the format we expect, with HttpOnly flag.44 '''45 plugin = make_plugin(secret='sosecret')46 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},47 value='HELLO')48 expected_cookies = [49 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),50 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),51 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')52 ]53 assert cookies == expected_cookies54 @helpers.change_config('who.secure', True)55 def test_secure_expected_cookies_with_config_secure_true(self):56 '''57 The returned cookies are in the format we expect, with secure flag.58 '''59 plugin = make_plugin(secret='sosecret')60 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},61 value='HELLO')62 expected_cookies = [63 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; secure; HttpOnly'),64 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; secure; HttpOnly'),65 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; secure; HttpOnly')66 ]67 assert cookies == expected_cookies68 @helpers.change_config('who.secure', False)69 def test_secure_expected_cookies_with_config_secure_false(self):70 '''71 The returned cookies are in the format we expect, without secure72 flag.73 '''74 plugin = make_plugin(secret='sosecret')75 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},76 value='HELLO')77 expected_cookies = [78 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),79 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),80 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')81 ]82 assert cookies == expected_cookies83 def test_secure_expected_cookies_without_config_secure(self):84 '''85 The returned cookies are in the format we expect, without secure flag.86 '''87 plugin = make_plugin(secret='sosecret')88 cookies = plugin._get_cookies(environ={'SERVER_NAME': '0.0.0.0'},89 value='HELLO')90 expected_cookies = [91 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; HttpOnly'),92 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=0.0.0.0; HttpOnly'),93 ('Set-Cookie', 'auth_tkt="HELLO"; Path=/; Domain=.0.0.0.0; HttpOnly')94 ]95 assert cookies == expected_cookies96 def test_timeout_not_set_in_config(self):97 '''98 Creating a CkanAuthTktCookiePlugin instance without setting timeout in99 config sets correct values in CkanAuthTktCookiePlugin instance.100 '''101 plugin = make_plugin(secret='sosecret')102 nose_tools.assert_equal(plugin.timeout, None)...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!