Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CPSC301:ComputingintheLifeSciences LectureNotes7: PythonModules&Testing pre-classnotes JessicaDawson [email protected] http://www.cs.ubc.ca/~jqdawson UniversityofBritishColumbia DepartmentofComputerScience 2016W2 OriginalslidesbyIanM.MitchellandGeorgeTsiknis.Revisions/updatesbyJessicaDawson Objectives Attheendofthissection,youwillbeableto: • Useimport andrelatedcommandstoaccessvariables, functionsandobjects(andlatermethodsandclasses)from otherfiles • Writeyourownmodules(actually,youhavebeendoingthis allalong) • Usethedoctest moduletoautomaticallyrunthetest examplesindocstrings • Designyourownmoduleswhichwillautomaticallytest themselveswhentheyarerunbutnotwhentheyare imported Notes7:Modules 2 PythonModules • • Amoduleisacollectionof(usuallyrelated)functionsanddata(variables) groupedinasinglefilewith.py extension.Thefilename,(withoutthe".py"), isthenameofthemodule Pythoncomeswithhundredsofmodules – math modulehasmanyfunctionslike • sqrt • etc. • • • • (squareroot),trunc (trancate afloattoint),sin Tousethefunctionsofamodulewehavetoimportitwiththestatement import module-name,or import module-nameas local-name Afterimportingamodule,Pythoncreatesavariablewiththemodulename (originalorlocal,ifdefined)whichreferencesthatmodule. Tocallafunctioninthatmoduleyouhavetousemodule-name.functionnameasthefunctionname Example: import math var = 2.95 math.tranc(var) Notes7:Modules 3 PythonModules(cont) • Amodulemayalsohaveasetofdata – i.e.themathmodulehas e=2.7182818284590451 pi=3.1415926535897931 theseareconstantvaluesthatyoucanuse,butmustnotchange: radius=4.0 circle_area =math.pi *radius**2 • Youcanimportonlywhatyouwantfromamoduleusing: frommathimportfloor,pi circle_area =floor(pi*radius**2) noneedtouse math.pi or math.floor • Butifyoulaterimportanotherfunctioncalledfloor()fromanother moduleonlythelastonewillbeavailable. • Allbuilt-infunctionsareinthemodule__builtins__ .Thismodule isautomaticallyimported • Tocheckthecontentofamoduleyoucanuse: help(module) - longcomments dir(module) - onlynamesofitems Notes7:Modules 4 DefiningModules • EveryPythonfile(withextension.py)isamodule – everytimeyoucreateaprogramandsaveit,youcreatea module – youcanimportandusethismoduleinanotherprogram • Example: – populationgrowthfunctionisinfilepgrowth.py – touseit,theprogrambirthratehastoimportit • HowdoesPythonfindsthefilesthatneedstoimport? – Pythonfirstlooksinthedirectoriesthatcontainitslibraries, calleddefaultdirectories – thenitlooksinthecurrentdirectory – inSpyder thecurrentdirectoryisthedirectorythatcontainsthe lastprogramthatwasexecuted – fornow,wecanimportanyfilesfromthedefaultorcurrent directories,butnotfromanyotherdirectory(seelaterformore) Notes7:Modules 5 ImportingModules • Whenamoduleisimported,Pythonexecutesit.Wesaythatthe moduleisloaded(inmemory). • Whenamoduleisimportedagaininthesamesession,Pythondoes notloaditagain.Itknowsthatitisalreadyin. • Inmanycases,wewanttoexecutedifferentpartsofthemodule whenitisimportedthanwhenwerunitasthemainprogram • Pythondefinesavariable__name__ (twounderscoresbeforeand after)withineachmodulethatissetautomatically • Byconvention,implicitPythonentities(entitiessuchasvariablesand functionswhichPythoncreatesautomatically)aregivennamesthat beginandendwithdoubleunderscore • Whenamoduleisrunasthemainprogram(i.e.directlyinthe consoleorbyclickingtherunbutton),its__name__ variableisset to‘__main__’.Whenamoduleisimported,its__name__ variable issettoitsname. • Therefore,ifwewanttorunsomecodeonlywhenamoduleruns asthemainprogramweincludethatcodeintheconditional: if __name__ == '__main__': • Typicaluse:Testsforthemodule.Wedon'twanttoexecutethem whenthemoduleisimported. Notes7:Modules 6 Amodulefoo • Inthesubsequentclickerquestions,assumethatfoo.py containsthefollowinglines: def bar(x): print('name in bar:', __name__) return x * 2 def baz(x): return x / 2 print('name is: ', __name__) if __name__ == '__main__': print('in main') else: print('not in main') print('final line') Notes7:Modules 7 Testing • Astheydevelopaunitofcode(likeafunction,amodule), programmerstesttheunitbyperformingunittesting ontheunit • Aunittestingconsistsofasetoftestcases forthatunit • Atestcase consistsoftheinputvalues andtheexpectedoutput • Apopularstyleofprogrammingisthetest-drivendevelopment (TDD): – writethetestcasesbeforeyouwritethecodefortheunit • Whenallunitshavebeendevelopedandtested,wetestthewhole programtoverifythatsatisfiestheuserrequirements • Thetestingofthewholeprogramisusuallycalledsystemtesting andtherearemanytypesofthat: – – – – alphatesting :donebydevelopers betatesting :donebysomeselectedusers installationtesting :doneatthefinalsite etc Notes7:Modules 8 Black-boxTesting • Thetypeofunittestingthatweusuallyperforminatest drivendevelopmentiscalledblack-boxtesting. • Inablack-boxtesting,thetestcasesforaunitareusually derivedfromtheunit'sspecificationandinclude: – typicalcases whichusetypicalvaluesfortheinputs – boundarycases thatuseboundaryvalues:valuesthatarethe smallestorlargestallowablevaluesfortheunit'sinputs – simplestinterestingcases whoseinputvaluesarecloseto boundaryvalues • Examplesofboundaryandinterestingcases: – Fornumbers:zero,positiveandnegativetypicalvalues,largest andsmallestallowedvalues,onevalueawayfromthesmallest andlargestvalue – Forcollections(likestrings,ranges,lists,etc):emptycollection, collectionwithoneelement,collectionswithduplicatevalues – Forsearching:nomatchfound,onematch,manymatches. Notes7:Modules 9 ExampleofTestCases • Example:Thetestcasesforaunittestingofthepopulation functioninthepgrowth module: – typicalcase: population(1000,20,10,10)shouldreturn2594 – boundarycase: population(1000,0,0,anyperiods)shouldreturn1000 – boundarycase: population(1000,0,10,1)shouldreturn900 – boundarycase: population(1000,10,0,1)shouldreturn1100 – boundarycase: population(1000,any,any,0)shouldreturn1000 – interestingcase: population(1000,20,10,1)shouldreturn1100 • pgrowth_test.py containsthesetestcases Notes7:Modules 10 doctest :AsimplePythonLibraryforTesting • Programmersuseavailablelibrariestohelpthemwriteand maintaintheirtests • doctest isaverysimplemodulefortestthatwecanwritewithin thedocstring,exactlyliketheexamplesweuseinourrecipe • doctest – searchesthedocstringforlinesthatstartwith>>> – executesthemand – comparestheoutputwiththenextlinewhichsupposedtohavethe expectedresult • Comparisonisexactstringmatch(includinganyspaceornewline characters) • Toactivatethedoctest whenthemoduleisexecutedasmain program,weneedtouse: if __name__ == "__main__": import doctest doctest.testmod() • Check pgrowth_doctest.py foranexample. Notes7:Modules 11 OtherPythonTestingFrameworks • Therearemajorlimitationstothedoctest module – Itisdifficulttocreatetestcaseswhichrequiresettingupany significantamountofdata – Testforsuccessisbasedonmatchingstrings • Pythonalsohasunittest andnose modules – Youcandefinemorecomplextestcases – SuccesscanbedefinedintermsofanyBooleanexpression • Theunittest moduleispartofthePythonstandardlibrary – AnyinstallationofPythonwillincludethismodule • Thenose modulebuildsontopofunittest – Claimstobeeasiertobuild,runandmaintaintestsuites – Alsosupportsextensivecollectionof“plug-ins” Notes7:Modules 12 Summary • Afilewiththe.py extensioniscalleda“module” • Amodulecancontainmanyrelatedvariables/functions/objects • Pythonprovidesseveralwaysofexecutingthecommandsina module:import andfrom ... import • Thecommandsinamoduleareexecutedonlyonce,nomatterhow manytimesitisimported • Thenamesofthevariables/functions/objectsdefinedinthe otherfiledependonhowitisimported • Afilecandeterminewhetherithasbeenimportedorrundirectly byexaminingthe__name__ variable • Thedoctest modulecanbeusedtoautomaticallyrunthe exampletestsinamodule’sdocstrings • Pythonprovidesseveralotherframeworksforautomatingmore complicatedtestprocesses Notes7:Modules 13