Monday, May 2, 2016

Testing Puppet Code, Linting Part 2

In the first post I reviewed testing Puppet code syntax.  If you are just getting starting testing Puppet code I suggest you start there and read about why we test code and how to get started with Puppet parser.  If you've already read that then let's get started!

Linting is the act of tidying up your code.  Each programming language has a certain style or way about writing.  This is just a matter of formatting spaces, tabs and newlines so that your code looks a certain way.

Linting is not related to how a program functions, whether it will compile, or anything technical.  Linting is purely a matter of style.  So why include linting in a series on testing code?  Because adhering to the language's style makes your code more readable to other programmers.  Linting is the act of testing how well your code adheres to that style and cleaning it up.

There's a nifty program for Puppet code called puppet-lint.  puppet-lint will check your Puppet code and ensure it adheres to the Puppet Style Guide.  Run this to install:

     gem install puppet-lint

Once installed run it, passing a manifest as the argument and will tell you if your code is OK.

     puppet-lint init.pp

Lets see a real example on a manifest from https://github.com/mmarseglia/puppet-sonarqube.


In the above example we can see puppet-lint has thrown some warnings and one error.  puppet-lint has full documentation explaining each error and warning in detail.  In this case it's the autoload module layout is related to the directory name not matching the module name, see http://puppet-lint.com/checks/autoloader_layout/.

We can ignore bogus errors and warnings by telling puppet-lint to turn off specific checks.


puppet-lint can also fix your poorly indented code with its handy 'fix' feature.  Here I missed an indent.


I run puppet-lint with the --fix option to fix any indentation problems.


Look back at the code and we see puppet-lint has fixed the issue for me.


Practical experience has showed me sometimes it gets confused with multiple nested hashes.  Sometimes I've wondered if the resulting linted code is easier to read or more confusing.  puppet-lint also has a thing for 80 characters in a line.  There are times when I just can't (or won't) fit a line of code into 80 characters.  I typically ignore that check every time I run puppet-lint.

puppet-lint is a great tool by turning ugly code into easily readable code.  Add it to your arsenal of tests along with "puppet parser validate" to ensure your code is top notch.  Use your best judgement when running puppet-lint.  The goal is to make your code readable in a standard format.  The style guide is just that, a guide.