• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaScript Static Analysis Tools and Techniques - STP Online Session 2013
 

JavaScript Static Analysis Tools and Techniques - STP Online Session 2013

on

  • 3,781 views

An overview of JavaScript static analysis tools and an anecdotal case for the utility of static analysis in automated testing of JavaScript projects. ...

An overview of JavaScript static analysis tools and an anecdotal case for the utility of static analysis in automated testing of JavaScript projects.

Many errors in JavaScript projects --- think misplaced semicolons and mis-scoped variables --- are trivially preventable with habitual use of community-maintained tools like JSHint, JSLint, JSONLint or the Google Closure Compiler Linter. Many other errors are preventable through the judicious use of find, grep and simple regular expressions. In test automation, the simplest approach often proves surprisingly robust. I will conclude the session by discussing in detail how I am using static analysis on my own projects today.

Statistics

Views

Total Views
3,781
Views on SlideShare
3,773
Embed Views
8

Actions

Likes
4
Downloads
0
Comments
0

2 Embeds 8

http://www.linkedin.com 6
https://www.linkedin.com 2

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    JavaScript Static Analysis Tools and Techniques - STP Online Session 2013 JavaScript Static Analysis Tools and Techniques - STP Online Session 2013 Presentation Transcript

    • NoahSussmanns@noahsussman.com@noahsussmanToolsandTechniquesJavaScriptStaticAnalysisSoftwareTestProfessionalsonlinesessionNewYorkMay2013
    • “Lint”
    • “StaticAnalysis”means“AutomatedReading”
    • spinroot.com/gerard/pdf/ScrubPaper_rev.pdf
    • Thegoalofstaticanalysisistoautomateyourselfreadingcode.—SebastianBergmann
    • TheCaseForStaticAnalysisStatic analysis can reveal interesting places to startreading in an unfamiliar code base.It can also be used to locate areas of the code basethat may benefit from refactoring.Additionally static analysis may highlight potentialsources of latent bugs.
    • “Errors”aren’tnecessarilybad.Edsger Dijkstra famously said that tests can show thepresence of bugs, but never their absence.Static analysis can tell you where to start reading, butit can’t tell you where and when to stop reading andtake action.The feedback from any of these tools is ultimately justanother data point. How to respond to that data is aproblem static analysis can’t solve ;-)
    • Goodhart’sLawAnymetricthatisusedtogaugeperformance,willbegamedsuchthatitisnolongeranaccuratemeasureofperformance.
    • —GerardHolzmann(NASA/JPL)"reliabilityisasystemproperty,notacomponentproperty""sincesmalldefectscanlineupandleadtoabiganomaly…beingmeticulousaboutevensmalldefectscanreallypayoff.Everysmalldefectthatyoueliminate,eliminatesonelinkinthechainthatcouldbuildtowardalargerproblem.Acodingstandardcouldhelp.Almosteveryorganizationhasacodingstandardandinmostcasesthedevelopersarecompletelyunawareofit--theydontreadit...Ifyoucomeupwithacodingstandardyoubetterhaverulesthatmatter,thatcorrelatewithriskandyoubettermakesurethatyoucancheckcompliancemechanically."
    • UniformityandComprehensibility
    • ChecksfordetectableerrorsFind places where semicolon insertion mightproduce unintended resultsDetect unintentional declaration of global variablesDetect undeclared variablesWarn about potential unintended behavior from ==Flag usages of eval()
    • Firstweneedanexistingcodebase.wget http://code.jquery.com/jquery-1.10.1.jsmv jquery-1.10.1.js jquery.js
    • JSLintnpm -g install jslintjslint jquery.jsJSLint is Douglas Crockfords personal linting tool.It ships with a great default ruleset -- Crockfords own,constantly updated as he continues to learn aboutJavaScript and its pitfalls.JSLint is highly opinionated. While this is generallyseen as a good thing, theres a limited amount offlexibility when it comes to disabling individual rules.It’s hard to apply JSLint to legacy code.
    • JSHintnpm -g install jshintjshint jquery.jsJSHint is very similar to JSLint (in fact it began life asJSLint fork) but all of JSHint’s warnings and errors canbe configured or disabled via command line options orwith a .jshintrc configuration file.
    • JSONLintnpm -g install jsonlintjsonlint myFile.jsonJSONLint is a validator for the JSON data-interchangeformat. JSON is used by almost all modern Web APIs.JSONLint automates the process of testing whetherthere are parsiing errors in a block of JSON.
    • GoogleClosureCompilercurl -sO http://closure-compiler.googlecode.com/files/compiler-latest.zipunzip -qo compiler-latest.zipjava -jar compiler.jar jquery.jsClosure compilation is the closest thing that JavaScripthas to an "interpreter" syntax check like php  -­‐l orruby  -­‐c  Closure also warns you about potential issues suchas missing parameters and undeclared or redefinedvariables.If code wont compile with the Closure Compiler, thenyou can be certain said code is deeply hosed in somefundamental way.
    • TheGoogleJavaScriptLinter(gjslint)fixjsstyleyardstickProjectMessDetector(PMD)Copy-PasteDetector(CPD)CSSLintTidyforHTML5PHPCodeSniffer
    • JSONLintGoogleClosureCompilerJSHintUseandConfiguration
    • jsonlint myFile.jsonJSONLintinaction
    • GoogleClosureCompilerinaction
    • jslint jquery.jsJSLintinaction
    • jshint jquery.jsJSHintinaction
    • ConfigureJSHintandClosureCompiler
    • .jshintrcfile
    • Usea.jshintrcfile
    • OutputTuninghttp://www.jslint.com/lint.html#optionshttp://www.jshint.com/docs/#enforcing_optionshttp://jslinterrors.comhttps://developers.google.com/closure/compiler/docs/error-ref
    • In-the-wildexamplesofoutputtuning
    • RegularExpressionsjslint jquery.js | egrep -v is OK.$ | egrep -v ^ *$This relatively simple regex suppresses statusmessages from JSLint. The only lines that will beprinted are lines containing errors and warnings.
    • RegularExpressionstidy_ignore_regex=(DOCTYPE|title|notapproved|proprietary attribute|implicit <body>|trimming empty|missing <li>)|"tabindex" has invalidvalue "-1"|missing </template> before<li>|inserting implicit <ul>|missing</ul> before </template>|missingquote mark for attribute value
    • TunetheToolsToMatchTheCodejslint --predef Meteor --predef Template --predef $ --predef _ --predef Session --predef setTitle --predef Conf --predef google --predef Npm --predef makeInfoWindowEvent --predef IS_DEV --predef IS_PRODUCTION --plusplus --devel --vars --nomen --sloppy --white --terse --browser jquery.js | egrep -v is OK.$ | egrep -v ^ *$
    • TunetheToolsToMatchTheCodejava compiler.jar jquery.js --warning_level DEFAULT --jscomp_off missingProperties --compilation_level ADVANCED_OPTIMIZATIONS --externs ../../tests/conf/externs.js | > /dev/null
    • Don’tFeartheFilteryardstick_runner () {reasonable_upper_bound_for_CCN=10result=$(echo $* | xargs yardstick | grep -v @ | egrep -v ^ | perl -lnwe s{^(S+)(s+)(d+).*}{$3$2$1} and print | sort -rn | head -n1 | xargs -I @ echo @: high cyclomatic complexity.)count=`echo $result | cut -d -f1`if [ $count -gt $reasonable_upper_bound_for_CCN ]thenecho WARNING: $result >&2fi}
    • Don’tFeartheFilter
    • ThewholetimeI’mwritingcode,I’mconstantlytestingmyassumptions.—RasmusLerdorf
    • Questions?@noahsussmanns@noahsussman.cominfiniteundo.com