Foreword
Mylastarticletalkedaboutthebasicintroductionofhttprunner.Thisarticlemainlyintroducestheenvironmentvariablesinhttprunner.
Generallyspeaking,duringthedevelopmentprocessofactualapplications,theapplicationswillhavedifferentrunningenvironments,usuallythefollowingenvironments:
- localdevelopmentenvironment
- testenvironment
- ProductionEnvironment
Indifferentenvironments,wemayusedifferentconfigurationssuchasdatabasesoremailsendingdrivers.Inthiscase,weneedtouse.envfilestomakedifferentsettingsfordifferentoperatingenvironments.
Environmentvariables
Inautomatedtesting,itissometimesnecessarytouseenvironmentvariablestoachievecertainspecificpurposes.Commonscenariosinclude:
- Switchtestenvironment
- Switchtestconfiguration
- Storingsensitivedata(fromaninformationsecurityperspective)
InWindowssystems,usethesetcommandtosetenvironmentvariablesandvalues.Next,setthefollowingvariables
- host=http://127.0.0.1:8000Setthehostvaluetoswitchtherunningenvironmentwithoneclick
- user=testSetloginaccountandpassword,switchaccounttotest
- psw=123456Setloginaccountandpassword,switchaccountstotest
Opencmdandusethesetkey=valueformattosetenvironmentvariables(linuxusestheexportcommand)
C:\Users\dell>sethost=http://127.0.0.1:8000 C:\Users\dell>setname=test C:\Users\dell>setpassword=123456
Toviewthevalueofanenvironmentvariable,usesetkeynametoviewthecorrespondingvalue.
C:\Users\dell>sethost host=http://127.0.0.1:8000 C:\Users\dell>setname name=test C:\Users\dell>setpassword password=123456
InWindowssystems,%var%isusedtoreferencevariablesonthecommandline.
C:\Users\dell>echoaccount:%name% Account:test
Toreferencetheenvironmentvariablejustsetinpython,firstimporttheosmoduleandobtainitusingtheos.environmethod(environisadictdefinedinos.pyenviron={})
C:\Users\dell>python Python3.6.0(v3.6.0:41df79263a11,Dec232016,08:06:12)[MSCv.190064bit(AMD64)]onwin32 Type"help","copyright","credits"or"license"formoreinformation. >>>importos >>>os.environ.get('host') 'http://127.0.0.1:8000' >>>os.environ.get('name') 'test' >>>os.environ.get('password') '123456' >>>
Allmodificationstoenvironmentvariablesunderthecmdcommandlineareonlyeffectiveforthecurrentwindowandarenotpermanentmodifications.Thatistosay,whenthiscmdcommandlinewindowisclosed,itwillnolongerwork.
Topermanentlymodifyenvironmentvariables,youcansetthesystem’senvironmentvariablesthroughMyComputer→Properties→Advanced.
.envfilesetsenvironmentvariables
Theenvironmentvariablessetincmdcannotbestored,soyouneedtocreatea.envfiletostoretheenvironmentvariables.Thestorageusesthename=valueformat:
Winodwscannotdirectlycreate.envfilesandwillpromptthatthefilenamecannotbeempty.Here,usepycharmtocreateanew.envfile.
(Oryoucreateanewfilethathasbeenusedin1.envandrenameitinthecmdwindowrename1.env.env)
#.env host=http://127.0.0.1:8000 name=test password=123456
Next,writeanENVfunctionindebugtalk.pytoreadenvironmentvariablesanddirectlyreferenceenvironmentvariablesinYAML/JSONscripts.
(Thefunctionenviron(ENVforshort)isbuilt-ininHttpRunner2.xversion)
#debugtalk.py importos defENV(keyname): ''' Getthevaluecorrespondingtotheenvironmentkeyname :return: ''' value=os.environ.get(keyname,'') returnvalue
WhenHttpRunnerisrunning,itwillautomaticallyloadthecontentsofthe.envfileintotheenvironmentvariablesoftheruntime(RunTime),andthentheenvironmentvariablescanbereadduringtheruntime.
Scriptcase
ToreferenceenvironmentvariablesusetheENVfunction${ENV(keyname)
-config: name:logincase variables:{} request: base_url:${ENV(host)}#Referencetheenvironmentvariablehostvalue -test: name:logincase1 request: url:/api/v1/login/ method:POST headers: Content-Type:application/json User-Agent:python-requests/2.18.4 json: username:${ENV(name)}#Referencetheenvironmentvariablenamevalue password:${ENV(password)}#Referencetheenvironmentvariablepasswordvalue extract: -token:content.token#Extracttoken validate: -eq:[status_code,200] -eq:[headers.Content-Type,application/json] -eq:[content.msg,loginsuccess!] -eq:[content.code,0]
Runtheusecase
D:\soft\untitled\projectdemo>hruntest_env_demo.yml INFOLoadingenvironmentvariablesfromD:\soft\untitled\projectdemo\.env logincase1 INFOPOST/api/v1/login/ INFOstatus_code:200,response_time(ms):517.84ms,response_length:109bytes INFOstarttoextractfromresponseobject. INFOstarttovalidate. . --------------------------------------------------------------------- Ran1testin0.525s OK INFOStarttorenderHtmlreport... INFOGeneratedHtmlreport:D:\soft\untitled\projectdemo\reports\1569661053.html D:\soft\untitled\projectdemo>
Ifthe.envfileanddebugtalkarenotinthesamefolder,youcanusethe–dot-env-pathparametertospecifythepathtothe.env
hruntest_env_demo.yml–dot-env-path/path/to/.env
Youcansetthe–log-levelparametertodebugmodetoviewmoredetailedrunninglogs
>hruntest_env_demo.yml--log-leveldebug INFOLoadingenvironmentvariablesfromD:\soft\untitled\projectdemo\.env DEBUGLoadedvariable:host DEBUGLoadedvariable:name DEBUGLoadedvariable:password logincase1 DEBUGcallhook:${setup_hook_prepare_kwargs($request)} INFOPOST/api/v1/login/ DEBUGrequestkwargs(raw):{'headers':{'content-type':'application/json','user-agent':'python-requests/2.18.4'},'json':{'username':'test','password':'123456'}} DEBUGprocessedrequest: >POSThttp://127.0.0.1:8000/api/v1/login/
Thefunctionenviron(ENVforshort)isbuilt-ininHttpRunner2.xversion
Finally,Iwouldliketothankeveryonewhoreadmyarticlecarefully.Reciprocityisalwaysnecessary.Althoughitisnotaveryvaluablething,ifyoucanuseit,youcantakeitdirectly:
Thisinformationshouldbethemostcomprehensiveandcompletepreparationwarehousefor[softwaretesting]friends.Thiswarehousehasalsoaccompaniedtensofthousandsoftestengineersthroughthemostdifficultjourney.Ihopeitcanalsohelpyou!