2018-09-04-tdd-chef-cookbooks-chefspec-inspec.md 77.1 KB
Newer Older
Jamie Tanna's avatar
Jamie Tanna committed
1 2 3
---
title: Test-Driven Chef Cookbook Development Using ChefSpec (and a sprinkling of InSpec)
description: Using the example of deploying and running a Java JAR file as a way to show the lifecycle of a fully test-driven Chef cookbook.
4 5 6 7 8 9 10 11 12 13 14 15 16
categories:
- blogumentation
- chef
- tdd
tags:
- howto
- blogumentation
- chef
- test-kitchen
- chefspec
- tdd
- testing
- guide
17
image: /img/vendor/chef-logo.png
18
date: 2018-09-04T14:52:10+01:00
19 20
license_prose: CC-BY-NC-SA-4.0
license_code: Apache-2.0
21
slug: tdd-chef-cookbooks-chefspec-inspec
Jamie Tanna's avatar
Jamie Tanna committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
---
For the example of how to create a Chef cookbook in a truly test-driven manner, we'll be building a _relatively_ simple Chef cookbook for downloading and running a Java JAR file. Note that this post won't be going into the intricacies of _why_ you would practice TDD, just _how_ you'd do it with Chef through ChefSpec.

This will require us to:

- Install Java
- Download the required JAR file
- Run that JAR file as a system service

We'll be following the [<i class="fa fa-gitlab"></i> jar-deploy-cookbook][jar-deploy-cookbook] for this blog post, and are using ChefDK version 3.1.0:

```
Chef Development Kit Version: 3.1.0
chef-client version: 14.2.0
delivery version: master (6862f27aba89109a9630f0b6c6798efec56b4efe)
berks version: 7.0.4
kitchen version: 1.22.0
inspec version: 2.1.72
```

I'll assume some familiarity with Chef and how we write recipes for it, but will not expect any knowledge of ChefSpec.

Also note that although this is a fairly Java-specific example, all the practices are transferable and hopefully make sense - if not, please contact me (via the details in the footer) and let me know.

Finally, you'll notice there is are no FoodCritic, CookStyle, or other checks that are performed as part of the cookbook written as part of this article. These definitely should be practiced, but for the purpose of this cookbook, we won't bother.

48
# A note about versioning
Jamie Tanna's avatar
Jamie Tanna committed
49 50 51 52 53 54 55 56 57 58 59 60

Chef cookbooks in and around the community are built with [Semantic Versioning] as their versioning scheme.

Although I'd recommend reading the specification in full, the TL;DR is:

- we start our version as 0.1.0
- the `1` in `0.1` is a minor release, which indicates functional changes
- as we're in a `0.x` release, we're able to push out breaking changes, as a `0.x` release does not promise backwards compatibility
- when we're happy with the API for the cookbook, we'll release it as `1.0`
- if you have any functional changes, that **are** backwards compatible, the cookbook will be released as a minor bump, i.e as `0.2.0`.
- if you have any bug/security fixes, that **are** backwards compatible, the cookbook will be released as a patch bump, i.e as `0.1.1`.

61
# jar-deploy-cookbook v0.1
Jamie Tanna's avatar
Jamie Tanna committed
62

63
## Bootstrapping our Cookbook
Jamie Tanna's avatar
Jamie Tanna committed
64 65 66 67 68 69 70 71 72

We want to start by generating our cookbook boilerplate:

```
$ chef generate cookbook jar-deploy-cookbook
```

This will give us the basic structure of our cookbook.

73
## Contract-Driven Tests with InSpec and Test Kitchen
Jamie Tanna's avatar
Jamie Tanna committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

In a very test-first manner, we'll write our smoke tests using InSpec to give us confidence that our cookbook converges successfully.

```ruby
# test/integration/default/default_test.rb

describe command('java -version') do
  its('exit_status') { should eq 0 }
  its('stderr') { should match(/openjdk version "1\.8\..*"/) }
end

describe service('jar') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe port(8080) do
  it { should be_listening }
  its('processes') { should include 'java' }
end
```

Notice that we're not checking every aspect of our converged node, as we can cover our core functionality in our unit tests. We then have our smoke tests to just verify that things look alright, as we've got a lot of confidence in our recipes through our unit tests.

We also want to set up our `.kitchen.yml` to specify how we want the attributes and recipe(s) to be used:

```yaml
run_list:
- recipe[jar-deploy-cookbook::default]
attributes:
  java:
    jdk_version: '8'
  jar:
    user: jar_user
    group: jar_group
    directory: /var/wibble/foo
    jar_uri: https://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.18.0/wiremock-standalone-2.18.0.jar
```

This has helped us drive our contract for the cookbook and defines how it'll be consumed. While implementing the cookbook itself, we'll be able to find out if our contract isn't as clear/obvious as we thought.

116
## Installing Java
Jamie Tanna's avatar
Jamie Tanna committed
117 118 119

Now we've set up what our initial cookbook attributes and recipes should look like, we need perform our first piece of required functionality - installing Java.

120
### Manually installing the package
Jamie Tanna's avatar
Jamie Tanna committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217

The quickest path to getting Java installed is to simply install package with the `package` resource:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all attributes are default, on Ubuntu 16.04' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
      runner.converge(described_recipe)
    end

    it 'installs the OpenJDK' do
      expect(chef_run).to install_package('install OpenJDK')
        .with(package_name: 'openjdk-8-jre-headless')
    end

    # ...
  end

  context 'When all attributes are default, on CentOS 7.4.1708' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708')
      runner.converge(described_recipe)
    end

    it 'installs the OpenJDK' do
      expect(chef_run).to install_package('install OpenJDK')
        .with(package_name: 'java-1.8.0-openjdk-headless')
    end

    # ...
  end
end
```

Notice that we're supporting multiple platforms, which isn't necessarily a requirement, as that'll depend on your own reasoning for creating the cookbook. However, it does enable me to show how you'd interact with different platforms and in this case, install different packages per platform.

In true TDD fashion, we'll make sure we have failing (red) tests and then make them pass (green):

```
F.F.

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs the OpenJDK
     Failure/Error:
       expect(chef_run).to install_package('install OpenJDK')
         .with(package_name: 'openjdk-8-jre-headless')

       expected "package[install OpenJDK]" with action :install to be in Chef run. Other package resources:



     # ./spec/unit/recipes/default_spec.rb:17:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs the OpenJDK
     Failure/Error:
       expect(chef_run).to install_package('install OpenJDK')
         .with(package_name: 'java-1.8.0-openjdk-headless')

       expected "package[install OpenJDK]" with action :install to be in Chef run. Other package resources:



     # ./spec/unit/recipes/default_spec.rb:33:in `block (3 levels) in <top (required)>'

Finished in 0.67644 seconds (files took 2.52 seconds to load)
4 examples, 2 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:16 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs the OpenJDK
rspec ./spec/unit/recipes/default_spec.rb:32 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs the OpenJDK
```

And now we can implement it using [Ohai's] magic attributes to determine which platform we're on:

```ruby
package 'install OpenJDK' do
  case node['platform']
  when 'ubuntu'
    package_name 'openjdk-8-jre-headless'
  when 'centos'
    package_name 'java-1.8.0-openjdk-headless'
  end
end
```

These pass our tests - great stuff!

```
....

Finished in 0.68183 seconds (files took 2.51 seconds to load)
4 examples, 0 failures
```

218
### Supporting multiple platforms
Jamie Tanna's avatar
Jamie Tanna committed
219 220 221

As we can see, this is already getting a little complex, and will be made more difficult for each and every platform that we want to support. Not only that but there may be different versions of Java we want to install, or we may want to have different flavours, i.e. the Oracle JDK or the IBM JDK.

222
### Re-using the `java` community cookbook
Jamie Tanna's avatar
Jamie Tanna committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

To reduce the complexity within this cookbook, we can instead delegate the installation of the package to the [Java community cookbook], which is well-maintained and is much more configurable.

We have a few choices for how we'd want to pin the version:

```ruby
# pull in any changes, including breaking ones, after the version we've specified
depends 'java', '>= 2.1.1'
# pull in major version changes
depends 'java', '~> 2'
# pull in minor version changes
depends 'java', '~> 2.2'
# pull in patch version changes
depends 'java', '~> 2.2.0'
# pin to this exact version
depends 'java', '2.2.0'
```

In the interest of stability, we will opt for only pulling in patch bumps, and make it manual work to update for new functional changes.

We then, in each `context` block we have, ensure it matches `include_recipe`s, such as:

We want to test that the new recipe is used by our tests, so as per ['Testing `include_recipe`s with Chef and ChefSpec'][include_recipe], we can add the following in our spec:

```ruby
describe 'jar-deploy-cookbook::default' do
  context '...' do
    # ...

    before :each do
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
        .with('java::default')
    end

    it 'installs Java using the java::default recipe' do
      expect_any_instance_of(Chef::Recipe).to receive(:include_recipe).with('java::default')
      chef_run
    end
  end
end
```

This both allows us to verify that a recipe has been `include_recipe`d, as well as making sure that the ChefSpec run doesn't actually `include_recipe` that recipe, which would slow down our Chef run dramatically.

When running our tests, we get some expected red tests:

```
F.F.

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs Java using the java::default recipe
     Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
       Exactly one instance should have received the following message(s) but didn't: include_recipe
     #   (large stacktrace)
     #
     #   Showing full backtrace because every line was filtered out.
     #   See docs for RSpec::Configuration#backtrace_exclusion_patterns and
     #   RSpec::Configuration#backtrace_inclusion_patterns for more information.

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs Java using the java::default recipe
     Failure/Error: DEFAULT_FAILURE_NOTIFIER = lambda { |failure, _opts| raise failure }
       Exactly one instance should have received the following message(s) but didn't: include_recipe
     #   (large stacktrace)
     #
     #   Showing full backtrace because every line was filtered out.
     #   See docs for RSpec::Configuration#backtrace_exclusion_patterns and
     #   RSpec::Configuration#backtrace_inclusion_patterns for more information.

Finished in 3.08 seconds (files took 2.42 seconds to load)
4 examples, 2 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:22 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs Java using the java::default recipe
rspec ./spec/unit/recipes/default_spec.rb:44 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs Java using the java::default recipe
```

Which can now be resolved by adding the following to our `default` recipe:

```ruby
include_recipe 'java::default'
```

Which gives us our passing tests again:

```
....

Finished in 6.56 seconds (files took 2.41 seconds to load)
4 examples, 0 failures
```

317
## Downloading the JAR
Jamie Tanna's avatar
Jamie Tanna committed
318 319 320

Now we've installed Java, we can go about getting our JAR file onto the box.

321
### Creating a directory structure
Jamie Tanna's avatar
Jamie Tanna committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

First, we need to create a directory for the JAR to be pulled into. Following the practice of least privileges, we'll also need a user to be created, which can then own the directory.

Notice that we're creating two sets of test cases for our new configurable attributes - we need one set of tests to test our defaults, and one where they're overridden. We have separate test cases for the defaults to catch any inadvertent breaking changes if someone were to make a change to the defaults, and accidentally break backwards compatibility. We also override it to make sure that we _can_ actually override it and we've not accidentally hardcoded it.

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all attributes are default, on Ubuntu 16.04' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
      runner.converge(described_recipe)
    end

    # ...

    it 'creates the user and group' do
      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar')
        .with(group: 'jar')
    end

    it 'creates the containing directory' do
      expect(chef_run).to create_directory('creates the containing directory')
        .with(path: '/var/jar')
        .with(owner: 'jar')
        .with(group: 'jar')
    end

    # ...
  end

  context 'When all attributes are default, on CentOS 7.4.1708' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708')
      runner.converge(described_recipe)
    end

    # ...

    it 'creates the user and group' do
      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar')
        .with(group: 'jar')
    end

    it 'creates the containing directory' do
      expect(chef_run).to create_directory('creates the containing directory')
        .with(path: '/var/jar')
        .with(owner: 'jar')
        .with(group: 'jar')
    end

    # ...
  end

  context 'When overriding user and group, when the platform is irrelevant' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
        node.automatic['jar']['user'] = 'jar_user'
        node.automatic['jar']['group'] = 'deployment'
      end
      runner.converge(described_recipe)
    end

    before :each do
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
        .with('java::default')
    end

    it 'creates the user and group' do
      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar_user')
        .with(group: 'deployment')
    end

    it 'creates the containing directory' do
      # notice we're not checking the `path`
      expect(chef_run).to create_directory('creates the containing directory')
        .with(owner: 'jar_user')
        .with(group: 'deployment')
    end
  end
end
```

Note that when we override the user/group, we only check that the `owner` and `group` on `directory[creates the containing directory]` is updated, as they're the only parameters we care about in that case. We can do this because we're confident that the other parameters are checked as part of the default cases.

Now we've used our test to define what the default should be for our attributes, we'd want to specify them within the `attributes/default.rb` file:

```ruby
node.default['jar']['user'] = 'jar'
node.default['jar']['group'] = 'jar'
```

These tests will then rightly fail, as we've not yet implemented the recipe:

```
...FF.FF

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the user and group
     Failure/Error:
       expect(chef_run).to create_user('creates the user')
         .with(username: 'jar')
         .with(group: 'jar')

       expected "user[creates the user]" with action :create to be in Chef run. Other user resources:



     # ./spec/unit/recipes/default_spec.rb:50:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
     Failure/Error:
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar')
         .with(owner: 'jar')
         .with(group: 'jar')

       expected "directory[creates the containing directory]" with action :create to be in Chef run. Other directory resources:



     # ./spec/unit/recipes/default_spec.rb:56:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the user and group
     Failure/Error:
       expect(chef_run).to create_user('creates the user')
         .with(username: 'jar_user')
         .with(group: 'deployment')

       expected "user[creates the user]" with action :create to be in Chef run. Other user resources:



     # ./spec/unit/recipes/default_spec.rb:83:in `block (3 levels) in <top (required)>'

  4) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the containing directory
     Failure/Error:
       expect(chef_run).to create_directory('creates the containing directory')
         .with(owner: 'jar_user')
         .with(group: 'deployment')

       expected "directory[creates the containing directory]" with action :create to be in Chef run. Other directory resources:



     # ./spec/unit/recipes/default_spec.rb:90:in `block (3 levels) in <top (required)>'

Finished in 5.32 seconds (files took 2.49 seconds to load)
8 examples, 4 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:49 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the user and group
rspec ./spec/unit/recipes/default_spec.rb:55 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:82 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the user and group
rspec ./spec/unit/recipes/default_spec.rb:88 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the containing directory
```

Allowing us to add the following implementation into `recipes/default.rb`:


```ruby
# ...

directory 'creates the containing directory' do
  path '/var/jar'
  owner node['jar']['user']
  group node['jar']['group']
end
```

Which gives us passing tests:

```
..........

Finished in 6.44 seconds (files took 2.5 seconds to load)
10 examples, 0 failures
```

506
### Making that directory configurable
Jamie Tanna's avatar
Jamie Tanna committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

Now although we've created that directory for the JAR to be run from, consumers of the cookbook want to make it configurable, for instance provide some logging agent access to it. In fact, we'd even specified it should be configurable in our `.kitchen.yml`!

So let's update our tests to make it configurable. First, we add a new test, to check that when we do change the attribute, the `directory` resource is configured with the overriden directory attribute. We're only checking that `path` and `recursive` are set to the correct values, because we're using the default values of the `user` and `group`:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When overriding jar.directory, when the platform is irrelevant' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
        node.automatic['jar']['directory'] = '/var/jar-deploy'
      end
      runner.converge(described_recipe)
    end

    before :each do
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
        .with('java::default')
    end

    it 'creates the containing directory' do
      # notice we're not checking `user` or `group`
      expect(chef_run).to create_directory('creates the containing directory')
        .with(path: '/var/jar-deploy')
        .with(recursive: true)
    end
  end
end
```

Next, we update our existing tests to ensure that we are creating the directory in a `recursive` fashion. This is because we don't know exactly _where_ the directory is going to be created, so it could be that the parent directory structure may not exist, so we need to make sure that we create it.

This is unfortunately not something that ChefSpec will warn you about - it's not until we get to integration testing with Test Kitchen that you'll see errors. I've preemptively put this change in as it's bitten me before!

```diff
 describe 'jar-deploy-cookbook::default' do
   context 'When all attributes are default, on Ubuntu 16.04' do
     # ...

     it 'creates the containing directory' do
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar')
         .with(owner: 'jar')
         .with(group: 'jar')
+        .with(recursive: true)
     end

     # ...
   end

   context 'When all attributes are default, on CentOS 7.4.1708' do
     # ...

     it 'creates the containing directory' do
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar')
         .with(owner: 'jar')
         .with(group: 'jar')
+        .with(recursive: true)
     end

     # ...
   end

   context 'When overriding user and group, when the platform is irrelevant' do
     # ...

     it 'creates the containing directory' do
-      # notice we're not checking the `path`
+      # notice we're not checking the `path` or `recursive`
       expect(chef_run).to create_directory('creates the containing directory')
         .with(owner: 'jar_user')
         .with(group: 'deployment')
     end

     # ...
   end
 end
```

And then set the default value of `jar.directory` in our `attributes/default.rb`:

```ruby
node.default['jar']['directory'] = '/var/jar'
```

Our tests will fail:

```
..F...F...F

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the containing directory
     Failure/Error:
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar')
         .with(owner: 'jar')
         .with(group: 'jar')
         .with(recursive: true)

       expected "directory[creates the containing directory]" to have parameters:

         recursive true, was false
     # ./spec/unit/recipes/default_spec.rb:34:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
     Failure/Error:
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar')
         .with(owner: 'jar')
         .with(group: 'jar')
         .with(recursive: true)

       expected "directory[creates the containing directory]" to have parameters:

         recursive true, was false
     # ./spec/unit/recipes/default_spec.rb:70:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates the containing directory
     Failure/Error:
       expect(chef_run).to create_directory('creates the containing directory')
         .with(path: '/var/jar-deploy')

       expected "directory[creates the containing directory]" to have parameters:

         path "/var/jar-deploy", was "/var/jar"
     # ./spec/unit/recipes/default_spec.rb:127:in `block (3 levels) in <top (required)>'

Finished in 6.99 seconds (files took 2.53 seconds to load)
11 examples, 3 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:33 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:69 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:125 # jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates the containing directory
```

To make this tests green, we'll need to make `path` configurable and specify `recursive true`:

```diff
 directory 'creates the containing directory' do
-  path '/var/jar'
+  path node['jar']['directory']
   owner node['jar']['user']
   group node['jar']['group']
+  recursive true
 end
```

Which gives us passing tests!

```
...........

Finished in 6.89 seconds (files took 2.56 seconds to load)
11 examples, 0 failures
```

668
### What's the default JAR file?
Jamie Tanna's avatar
Jamie Tanna committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

It turns out that we can't actually default this cookbook to a JAR file, as there's no default generic JAR a consumer would want. Instead, we want to throw an error when no JAR is specified:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When the jar.jar_uri is not specified, when the platform is irrelevant' do
    let(:runner) do
      ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
      # note we don't converge here
    end

    before :each do
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
        .with('java::default')
    end

    it 'raises an error' do
      expect { runner.converge(described_recipe) }.to raise_error('jar.jar_uri is not specified')
    end
  end
end
```

We need to make sure that we're explicitly defaulting the `jar.jar_uri` to `nil`, otherwise Chef will complain we don't have the attribute set:

```ruby
# attributes/default.rb
node.default['jar']['jar_uri'] = nil
```

Now when we run our tests, we get an expected test failure where we don't have an exception raised:

```
F...........

Failures:

  1) jar-deploy-cookbook::default When the jar.jar_uri is not specified, when the platform is irrelevant raises an error
     Failure/Error: expect { runner.converge(described_recipe) }.to raise_error('jar.jar_uri is not specified')
       expected Exception with "jar.jar_uri is not specified" but nothing was raised
     # ./spec/unit/recipes/default_spec.rb:22:in `block (3 levels) in <top (required)>'

Finished in 7.69 seconds (files took 2.56 seconds to load)
12 examples, 1 failure

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:21 # jar-deploy-cookbook::default When the jar.jar_uri is not specified, when the platform is irrelevant raises an error
```

We can update our `default` recipe to throw an error to get our tests passing:

```diff
+raise 'jar.jar_uri is not specified' if node['jar']['jar_uri'].nil?
+
 include_recipe 'java::default'

 # ...
```

However, when we run our tests now we've actually got a _tonne_ of failures! Oops.

```
.FFFFFFFFFFF

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs Java using the java::default recipe
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:29:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:40:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the user and group
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:29:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:44:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the containing directory
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:29:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:50:in `block (3 levels) in <top (required)>'

  4) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 converges successfully
     Failure/Error: expect { chef_run }.to_not raise_error

       expected no Exception, got #<RuntimeError: jar.jar_uri is not specified> with backtrace:
         # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
         # ./spec/unit/recipes/default_spec.rb:29:in `block (3 levels) in <top (required)>'
         # ./spec/unit/recipes/default_spec.rb:58:in `block (4 levels) in <top (required)>'
         # ./spec/unit/recipes/default_spec.rb:58:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:58:in `block (3 levels) in <top (required)>'

  5) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs Java using the java::default recipe
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:65:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:76:in `block (3 levels) in <top (required)>'

  6) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the user and group
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:65:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:80:in `block (3 levels) in <top (required)>'

  7) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:65:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:86:in `block (3 levels) in <top (required)>'

  8) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 converges successfully
     Failure/Error: expect { chef_run }.to_not raise_error

       expected no Exception, got #<RuntimeError: jar.jar_uri is not specified> with backtrace:
         # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
         # ./spec/unit/recipes/default_spec.rb:65:in `block (3 levels) in <top (required)>'
         # ./spec/unit/recipes/default_spec.rb:94:in `block (4 levels) in <top (required)>'
         # ./spec/unit/recipes/default_spec.rb:94:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:94:in `block (3 levels) in <top (required)>'

  9) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the user and group
     Failure/Error: runner.converge(described_recipe)

     RuntimeError:
       jar.jar_uri is not specified
     # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
     # ./spec/unit/recipes/default_spec.rb:104:in `block (3 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:114:in `block (3 levels) in <top (required)>'

  10) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the containing directory
      Failure/Error: runner.converge(described_recipe)

      RuntimeError:
        jar.jar_uri is not specified
      # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
      # ./spec/unit/recipes/default_spec.rb:104:in `block (3 levels) in <top (required)>'
      # ./spec/unit/recipes/default_spec.rb:121:in `block (3 levels) in <top (required)>'

  11) jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates the containing directory
      Failure/Error: runner.converge(described_recipe)

      RuntimeError:
        jar.jar_uri is not specified
      # /tmp/chefspec20180903-26075-1fhni1tfile_cache_path/cookbooks/jar-deploy-cookbook/recipes/default.rb:6:in `from_file'
      # ./spec/unit/recipes/default_spec.rb:132:in `block (3 levels) in <top (required)>'
      # ./spec/unit/recipes/default_spec.rb:143:in `block (3 levels) in <top (required)>'

Finished in 7.31 seconds (files took 2.41 seconds to load)
12 examples, 11 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:38 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 installs Java using the java::default recipe
rspec ./spec/unit/recipes/default_spec.rb:43 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the user and group
rspec ./spec/unit/recipes/default_spec.rb:49 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:57 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 converges successfully
rspec ./spec/unit/recipes/default_spec.rb:74 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 installs Java using the java::default recipe
rspec ./spec/unit/recipes/default_spec.rb:79 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the user and group
rspec ./spec/unit/recipes/default_spec.rb:85 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:93 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 converges successfully
rspec ./spec/unit/recipes/default_spec.rb:113 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the user and group
rspec ./spec/unit/recipes/default_spec.rb:119 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates the containing directory
rspec ./spec/unit/recipes/default_spec.rb:141 # jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates the containing directory
```

As we can see, we now need to set the `jar.jar_uri` in each of our other tests, otherwise the `raise` will be triggered as `jar.jar_uri` is defaulted to `nil`.

```diff
 require 'spec_helper'

 describe 'jar-deploy-cookbook::default' do
-  context 'When all attributes are default, on Ubuntu 16.04' do
+  context 'When all but the jar.jar_uri attributes are default, on Ubuntu 16.04' do
     let(:chef_run) do
-      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
+      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
+        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
+      end
       runner.converge(described_recipe)
     end

     # ...
   end

-  context 'When all attributes are default, on CentOS 7.4.1708' do
+  context 'When all all but the jar.jar_uri attributes are default, on CentOS 7.4.1708' do
     let(:chef_run) do
-      runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708')
+      runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708') do |node|
+        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
+      end
+
       runner.converge(described_recipe)
     end

     # ...
   end

   context 'When overriding user and group, when the platform is irrelevant' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
+        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
         node.automatic['jar']['user'] = 'jar_user'
         node.automatic['jar']['group'] = 'deployment'
       end
     end

     # ...
   end

   context 'When overriding jar.directory, when the platform is irrelevant' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
+        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
         node.automatic['jar']['directory'] = '/var/jar-deploy'
       end
       runner.converge(described_recipe)
     end

     # ...
   end
 end
```

Once this is in, our tests will pass successfully.

917
### Actually downloading it
Jamie Tanna's avatar
Jamie Tanna committed
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

Now, we've checked that there's a `jar.jar_uri`, but we don't actually pull that JAR. We can do that using the `remote_file` resource built in to Chef:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all but the jar.jar_uri attributes are default, on Ubuntu 16.04' do
    # ...

    it 'downloads the JAR' do
      expect(chef_run).to create_remote_file('download the JAR')
        .with(source: 'https://example.com/jar')
        .with(path: '/var/jar/jar.jar')
        .with(owner: 'jar')
        .with(group: 'jar')
    end
  end

  context 'When all all but the jar.jar_uri attributes are default, on CentOS 7.4.1708' do
    # ...

    it 'downloads the JAR' do
      expect(chef_run).to create_remote_file('download the JAR')
        .with(source: 'https://example.com/jar')
        .with(path: '/var/jar/jar.jar')
        .with(owner: 'jar')
        .with(group: 'jar')
    end
  end

  context 'When overriding user and group, when the platform is irrelevant' do
    # ...

    it 'downloads the JAR' do
      # notice we only care about `owner` and `group`
      expect(chef_run).to create_remote_file('download the JAR')
        .with(owner: 'jar_user')
        .with(group: 'deployment')
    end
  end

  context 'When overriding jar.directory, when the platform is irrelevant' do
    # ...

    it 'downloads the JAR' do
      # notice we only care about `path`
      expect(chef_run).to create_remote_file('download the JAR')
        .with(path: '/var/jar-deploy/jar.jar')
    end
  end
end
```

We'll find that we'll have some red tests as the `remote_file`s aren't matched:

```
....F....F...F.F

Failures:

  1) jar-deploy-cookbook::default When all but the jar.jar_uri attributes are default, on Ubuntu 16.04 downloads the JAR
     Failure/Error:
       expect(chef_run).to create_remote_file('download the JAR')
         .with(source: 'https://example.com/jar')
         .with(path: '/var/jar/jar.jar')
         .with(owner: 'jar')
         .with(group: 'jar')

       expected "remote_file[download the JAR]" with action :create to be in Chef run. Other remote_file resources:



     # ./spec/unit/recipes/default_spec.rb:60:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all all but the jar.jar_uri attributes are default, on CentOS 7.4.1708 downloads the JAR
     Failure/Error:
       expect(chef_run).to create_remote_file('download the JAR')
         .with(source: 'https://example.com/jar')
         .with(path: '/var/jar/jar.jar')
         .with(owner: 'jar')
         .with(group: 'jar')

       expected "remote_file[download the JAR]" with action :create to be in Chef run. Other remote_file resources:



     # ./spec/unit/recipes/default_spec.rb:107:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant downloads the JAR
     Failure/Error:
       expect(chef_run).to create_remote_file('download the JAR')
         .with(owner: 'jar_user')
         .with(group: 'deployment')

       expected "remote_file[download the JAR]" with action :create to be in Chef run. Other remote_file resources:



     # ./spec/unit/recipes/default_spec.rb:150:in `block (3 levels) in <top (required)>'

  4) jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant downloads the JAR
     Failure/Error:
       expect(chef_run).to create_remote_file('download the JAR')
         .with(path: '/var/jar-deploy/jar.jar')

       expected "remote_file[download the JAR]" with action :create to be in Chef run. Other remote_file resources:



     # ./spec/unit/recipes/default_spec.rb:180:in `block (3 levels) in <top (required)>'

Finished in 10.01 seconds (files took 2.42 seconds to load)
16 examples, 4 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:59 # jar-deploy-cookbook::default When all but the jar.jar_uri attributes are default, on Ubuntu 16.04 downloads the JAR
rspec ./spec/unit/recipes/default_spec.rb:106 # jar-deploy-cookbook::default When all all but the jar.jar_uri attributes are default, on CentOS 7.4.1708 downloads the JAR
rspec ./spec/unit/recipes/default_spec.rb:148 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant downloads the JAR
rspec ./spec/unit/recipes/default_spec.rb:178 # jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant downloads the JAR

```

Which we can implement with the following addition to our recipe:

```diff
 directory 'creates the containing directory' do
 # ...
 end

+remote_file 'download the JAR' do
+  source node['jar']['jar_uri']
+  path "#{node['jar']['directory']}/jar.jar"
+  owner node['jar']['user']
+  group node['jar']['group']
+end
```

Which gives us our green tests:

```
................

Finished in 9.87 seconds (files took 2.59 seconds to load)
16 examples, 0 failures
```

1064
### Note about `remote_file`
Jamie Tanna's avatar
Jamie Tanna committed
1065 1066 1067 1068 1069 1070 1071 1072 1073

`remote_file` is an awesome way to download artefacts from various locations, from [the Chef documentation][remote_file]:

> The location of the source file may be HTTP (`http://`), FTP (`ftp://`), SFTP (`sftp://`), local (`file:///`), or UNC (`\\host\share\file.tar.gz`).

This is useful for when you have locally cached dependencies i.e. in a VM share from your host, or if you want to pull from an external service.

It also allows for a vast amount of goodness such as being able to provide remote authentication, HTTP headers, and more.

1074
### Splitting Complexity Out
Jamie Tanna's avatar
Jamie Tanna committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297

When developing using TDD, if you encounter a method to a method/class being too complex, you look to refactor it as it feels painful to work with. We're also seeing that here, where due to the `raise`, we have to complicate the required attributes for the recipe.

```diff
 require 'spec_helper'

 describe 'jar-deploy-cookbook::default' do
-  context 'When the jar.jar_uri is not specified, when the platform is irrelevant' do
-    let(:runner) do
-      ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
-    end
-
-    before :each do
-      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
-      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
-        .with('java::default')
-    end
-
-    it 'raises an error' do
-      expect { runner.converge(described_recipe) }.to raise_error('jar.jar_uri is not specified')
-    end
-  end
-
-  context 'When all but the jar.jar_uri attributes are default, on Ubuntu 16.04' do
+  context 'When all attributes are default, on Ubuntu 16.04' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
-        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
       end
       runner.converge(described_recipe)
     end

     before :each do
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
+      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
+        .with('jar-deploy-cookbook::download_jar')
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
         .with('java::default')
     end
@@ -56,15 +41,19 @@ describe 'jar-deploy-cookbook::default' do
         .with(recursive: true)
     end

+    it 'downloads the JAR using the ::download_jar recipe' do
+      expect_any_instance_of(Chef::Recipe).to receive(:include_recipe).with('jar-deploy-cookbook::download_jar')
+      chef_run
+    end
+
     it 'converges successfully' do
       expect { chef_run }.to_not raise_error
     end
   end

-  context 'When all all but the jar.jar_uri attributes are default, on CentOS 7.4.1708' do
+  context 'When all attributes are default, on CentOS 7.4.1708' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'centos', version: '7.4.1708') do |node|
-        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
       end

       runner.converge(described_recipe)
@@ -72,6 +61,8 @@ describe 'jar-deploy-cookbook::default' do

     before :each do
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
+      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
+        .with('jar-deploy-cookbook::download_jar')
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
         .with('java::default')
     end
@@ -95,6 +86,11 @@ describe 'jar-deploy-cookbook::default' do
         .with(recursive: true)
     end

+    it 'downloads the JAR using the ::download_jar recipe' do
+      expect_any_instance_of(Chef::Recipe).to receive(:include_recipe).with('jar-deploy-cookbook::download_jar')
+      chef_run
+    end
+
     it 'converges successfully' do
       expect { chef_run }.to_not raise_error
     end
@@ -103,7 +99,6 @@ describe 'jar-deploy-cookbook::default' do
   context 'When overriding user and group, when the platform is irrelevant' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
-        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
         node.automatic['jar']['user'] = 'jar_user'
         node.automatic['jar']['group'] = 'deployment'
       end
@@ -112,6 +107,8 @@ describe 'jar-deploy-cookbook::default' do

     before :each do
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
+      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
+        .with('jar-deploy-cookbook::download_jar')
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
         .with('java::default')
     end
@@ -133,7 +130,6 @@ describe 'jar-deploy-cookbook::default' do
   context 'When overriding jar.directory, when the platform is irrelevant' do
     let(:chef_run) do
       runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
-        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
         node.automatic['jar']['directory'] = '/var/jar-deploy'
       end
       runner.converge(described_recipe)
@@ -141,6 +137,8 @@ describe 'jar-deploy-cookbook::default' do

     before :each do
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
+      allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
+        .with('jar-deploy-cookbook::download_jar')
       allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
         .with('java::default')
     end
```

And create a new recipe, driven through a new spec file:

```ruby
require 'spec_helper'

describe 'jar-deploy-cookbook::download_jar' do
  context 'When the jar.jar_uri is not specified, when the platform is irrelevant' do
    let(:runner) do
      ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
    end

    it 'raises an error' do
      expect { runner.converge(described_recipe) }.to raise_error('jar.jar_uri is not specified')
    end
  end

  context 'When the jar.jar_uri is specified and other attributes are default, when the platform is irrelevant' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
      end
      runner.converge(described_recipe)
    end

    it 'downloads the JAR' do
      expect(chef_run).to create_remote_file('download the JAR')
        .with(source: 'https://example.com/jar')
        .with(path: '/var/jar/jar.jar')
        .with(user: 'jar')
        .with(group: 'jar')
    end
  end

  context 'When the jar.jar_uri is specified and user and group are overriden, when the platform is irrelevant' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
        node.automatic['jar']['user'] = 'abc'
        node.automatic['jar']['group'] = 'def'
      end
      runner.converge(described_recipe)
    end

    it 'downloads the JAR' do
      # notice we don't check for `path`
      expect(chef_run).to create_remote_file('download the JAR')
        .with(source: 'https://example.com/jar')
        .with(user: 'abc')
        .with(group: 'def')
    end
  end

  context 'When the jar.jar_uri is specified and jar.directory is overriden, when the platform is irrelevant' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
        node.automatic['jar']['jar_uri'] = 'https://example.com/jar'
        node.automatic['jar']['directory'] = '/opt/directory'
      end
      runner.converge(described_recipe)
    end

    it 'downloads the JAR' do
      # notice we don't check `user` and `group`
      expect(chef_run).to create_remote_file('download the JAR')
        .with(source: 'https://example.com/jar')
        .with(path: '/opt/directory/jar.jar')
    end
  end
end
```

We update our `default` recipe to include the `download_jar` recipe:

```diff
@@ -3,8 +3,6 @@
 # Recipe:: default
 #
 # Copyright:: 2018, Jamie Tanna, Apache-2.0
-raise 'jar.jar_uri is not specified' if node['jar']['jar_uri'].nil?
-
 include_recipe 'java::default'

 # ...
+
+include_recipe 'jar-deploy-cookbook::download_jar'
```

Which in turn will `raise` if the `jar.jar_uri` is not specified:

```ruby
#
# Cookbook:: jar-deploy-cookbook
# Recipe:: download_jar
#
# Copyright:: 2018, Jamie Tanna, Apache-2.0
raise 'jar.jar_uri is not specified' if node['jar']['jar_uri'].nil?

remote_file 'download the JAR' do
  source node['jar']['jar_uri']
  path "#{node['jar']['directory']}/jar.jar"
  owner node['jar']['user']
  group node['jar']['group']
end
```

1298
## Creating a systemd service
Jamie Tanna's avatar
Jamie Tanna committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539

To create a systemd service to run our JAR file, we need to interact with a Chef `template` resource:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all attributes are default, on Ubuntu 16.04' do
    # ...

    it 'creates a systemd service file' do
      expect(chef_run).to create_template('create a systemd service file')
        .with(source: 'unit.service.erb')
        .with(path: '/etc/systemd/system/jar.service')
        .with(owner: 'root')
        .with(group: 'root')
        .with(variables: {
                path_to_jar: '/var/jar/jar.jar',
                user: 'jar'
              })

      expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
        .with_content do |content|
          expect(content).to match %r{^User=jar$}
          expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar/jar\.jar$}
        end)
    end
  end
  context 'When all attributes are default, on CentOS 7.4.1708' do
    # ...

    it 'creates a systemd service file' do
      expect(chef_run).to create_template('create a systemd service file')
        .with(source: 'unit.service.erb')
        .with(path: '/etc/systemd/system/jar.service')
        .with(owner: 'root')
        .with(group: 'root')
        .with(variables: {
                path_to_jar: '/var/jar/jar.jar',
                user: 'jar'
              })

      expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
        .with_content do |content|
          expect(content).to match %r{^User=jar$}
          expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar/jar\.jar$}
        end)
    end
  end

  context 'When overriding user and group, when the platform is irrelevant' do
    # ...

    it 'creates a systemd service file' do
      expect(chef_run).to create_template('create a systemd service file')
        .with(variables: {
                path_to_jar: '/var/jar/jar.jar',
                user: 'jar_user'
              })

      expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
        .with_content do |content|
          expect(content).to match %r{^User=jar_user$}
        end)
    end
  end

  context 'When overriding jar.directory, when the platform is irrelevant' do
    # ...

    it 'creates a systemd service file' do
      expect(chef_run).to create_template('create a systemd service file')
        .with(variables: {
                path_to_jar: '/var/jar-deploy/jar.jar',
                user: 'jar'
              })

      expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
        .with_content do |content|
          expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar-deploy/jar\.jar$}
        end)
    end
  end
end
```

Notice how we're not currently verifying our systemd service file is all generated successfully, only the sections that are configuration-specific, and again, only testing where relevant.

This gives us the following failing tests:

```
....F.....F...F.F....

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(source: 'unit.service.erb')
         .with(path: '/etc/systemd/system/jar.service')
         .with(owner: 'root')
         .with(group: 'root')
         .with(variables: {
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" with action :create to be in Chef run. Other template resources:



     # ./spec/unit/recipes/default_spec.rb:50:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(source: 'unit.service.erb')
         .with(path: '/etc/systemd/system/jar.service')
         .with(owner: 'root')
         .with(group: 'root')
         .with(variables: {
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" with action :create to be in Chef run. Other template resources:



     # ./spec/unit/recipes/default_spec.rb:113:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(variables: {
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar_user'
               })

       expected "template[create a systemd service file]" with action :create to be in Chef run. Other template resources:



     # ./spec/unit/recipes/default_spec.rb:166:in `block (3 levels) in <top (required)>'

  4) jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(variables: {
                 path_to_jar: '/var/jar-deploy/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" with action :create to be in Chef run. Other template resources:



     # ./spec/unit/recipes/default_spec.rb:203:in `block (3 levels) in <top (required)>'

Finished in 13.02 seconds (files took 2.45 seconds to load)
21 examples, 4 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:49 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:112 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:165 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:202 # jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates a systemd service file
```

We use the `template` resource to create the file with its expected configuration:

```ruby
template 'create a systemd service file' do
  source 'unit.service.erb'
  path '/etc/systemd/system/jar.service'
  owner 'root'
  group 'root'
  variables path_to_jar: "#{node['jar']['directory']}/jar.jar",
            user: node['jar']['user']
end
```

Which needs a corresponding file in `templates/default/unit.service.erb`:

```eruby
[Unit]
Description=Run Java JAR

[Service]
User=<%= @user %>
Type=simple
ExecStart=/usr/bin/java -jar <%= @path_to_jar %>
```

However, once we've created the service file, we still need to start and enable the service:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all attributes are default, on Ubuntu 16.04' do
    # ...

    it 'enables the service' do
      expect(chef_run).to enable_service('enables the jar service')
        .with(service_name: 'jar')
    end

    it 'starts the service' do
      expect(chef_run).to start_service('starts the jar service')
        .with(service_name: 'jar')
    end
  end

  context 'When all attributes are default, on CentOS 7.4.1708' do
    # ...

    it 'enables the service' do
      expect(chef_run).to enable_service('enables the jar service')
        .with(service_name: 'jar')
    end

    it 'starts the service' do
      expect(chef_run).to start_service('starts the jar service')
        .with(service_name: 'jar')
    end
  end
end
```

Which is then implemented with:

```ruby
service 'enables the jar service' do
  service_name 'jar'
  action :enable
end

service 'starts the jar service' do
  service_name 'jar'
  action :start
end
```

1540
## Converging the Node
Jamie Tanna's avatar
Jamie Tanna committed
1541 1542 1543 1544 1545 1546 1547

Wow, we're finally at the stage that we can converge our recipe on a node!

If you think of it, we've been able to iterate much quicker, allowing us to breeze through our unit test writing, without worrying how long it'll take to i.e. actually download and install Java.

If we run it in Test Kitchen, via `kitchen test`, you can see we hit some issues:

1548
<asciinema-player src="/casts/tdd-chef/pre-group.json"></asciinema-player>
Jamie Tanna's avatar
Jamie Tanna committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

Which if you can't read the full error easily, it is:

```
Recipe: jar-deploy-cookbook::default
  * linux_user[creates the user] action create

    ================================================================================
    Error executing action `create` on resource 'linux_user[creates the user]'
    ================================================================================

    Mixlib::ShellOut::ShellCommandFailed
    ------------------------------------
    Expected process to exit with [0], but received '6'
    ---- Begin output of ["useradd", "-g", "jar_group", "-M", "jar_user"] ----
    STDOUT:
    STDERR: useradd: group 'jar_group' does not exist
    ---- End output of ["useradd", "-g", "jar_group", "-M", "jar_user"] ----
    Ran ["useradd", "-g", "jar_group", "-M", "jar_user"] returned 6

    Resource Declaration:
    ---------------------
    # In /opt/kitchen/cache/cookbooks/jar-deploy-cookbook/recipes/default.rb

      8: user 'creates the user' do
      9:   username node['jar']['user']
     10:   group node['jar']['group']
     11: end
     12:

    Compiled Resource:
    ------------------
    # Declared in /opt/kitchen/cache/cookbooks/jar-deploy-cookbook/recipes/default.rb:8:in `from_file'

    linux_user("creates the user") do
      action [:create]
      default_guard_interpreter :default
      username "jar_user"
      uid nil
      gid "jar_group"
      home nil
      iterations 27855
      declared_type :user
      cookbook_name "jar-deploy-cookbook"
      recipe_name "default"
    end

    System Info:
    ------------
    chef_version=14.4.56
    platform=ubuntu
    platform_version=18.04
    ruby=ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
    program_name=/opt/chef/embedded/bin/chef-client
    executable=/opt/chef/embedded/bin/chef-client
```

1606
### Creating the `jar.group` before we create the `jar.user`
Jamie Tanna's avatar
Jamie Tanna committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

Woops! It looks like the `jar.group` that we thought was created at the same time as the `jar.user` is configured was _not_.

It looks like instead we need to create the resource that will set up the `group`:

```ruby
describe 'jar-deploy-cookbook::default' do
  context 'When all attributes are default, on Ubuntu 16.04' do
      # ...

    it 'creates the user and group' do
      expect(chef_run).to create_group('creates the group')
        .with(group_name: 'jar')

      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar')
        .with(group: 'jar')
    end
  end

  context 'When all attributes are default, on CentOS 7.4.1708' do
    it 'creates the user and group' do
      expect(chef_run).to create_group('creates the group')
        .with(group_name: 'jar')

      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar')
        .with(group: 'jar')
    end
  end

  context 'When overriding user and group, when the platform is irrelevant' do
    it 'creates the user and group' do
      expect(chef_run).to create_group('creates the group')
        .with(group_name: 'deployment')

      expect(chef_run).to create_user('creates the user')
        .with(username: 'jar_user')
        .with(group: 'deployment')
    end
  end
end
```

And our implementation:

```diff
 include_recipe 'java::default'

+group 'creates the group' do
+  group_name node['jar']['group']
+end
+
 user 'creates the user' do
```

And now if we re-test:

1665
<asciinema-player src="/casts/tdd-chef/post-group.json"></asciinema-player>
Jamie Tanna's avatar
Jamie Tanna committed
1666 1667 1668

We can set that out as v0.1 happily!

1669
# jar-deploy-cookbook v0.2
Jamie Tanna's avatar
Jamie Tanna committed
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033

Wait, what about any run-time configuration?

Let us say that we have an application that we want to inject in certain configuration, such as running on different ports, or accessing a different S3 bucket for secrets.

In the Java world, we have a few choices:

- command-line arguments
- configuration via i.e. Spring
- Java System properties

In this example, we'll look at the command-line arguments, as the Wiremock JAR allows us to configure it as such. However, you may well want to allow for different use cases, for instance with the following example schema:

```yaml
attributes:
  jar:
    configuration:
      application.properties:
        key: value          # key=value
        integer_value: 1    # integer_value=1
        list:               # list=abc,def,ghi
        - abc
        - def
        - ghi
      commandline_arguments:
        port: 1234          # --port=1234
        hostname: abcd1234  # --hostname=abcd1234
      system_properties:
        skipTests: true      # -DskipTests=true
```

The exact mapping is likely language- or file-format-specific, but you can see that in this example, we've created three separate types of configuration which are mapped differently.

However, one use of this pattern for configuration, over the use of creating a set of specific attributes, is that i.e. 2 months down the road, we'll be able to add a new command-line flag that's added, without needing to update our cookbook. This benefit is obvious in this cookbook, which is written to be generic, but even in i.e. a wiremock cookbook, you'd gain extensibility without requiring maintenance of all the possible configuration values.

As with starting work on v0.1, we'll start v0.2 by defining the contract, in a new Test Kitchen test suite:

```yaml
suites:
- name: default
  # ...
- name: override-port
  attributes:
    jar:
      configuration:
        commandline_arguments:
          port: 9000
```

We'll then write our InSpec tests, which expect it to be up and running, but on a different port:

```ruby
describe command('java -version') do
  its('exit_status') { should eq 0 }
  its('stderr') { should match(/openjdk version "1\.8\..*"/) }
end

describe service('jar') do
  it { should be_installed }
  it { should be_enabled }
  it { should be_running }
end

describe port(9000) do
  it { should be_listening }
  its('processes') { should include 'java' }
end
```

As we need to update the arguments within our systemd service file, we'll need to update the tests around the `template` resource to note the new argument:

```diff
 context 'When all attributes are default, on Ubuntu 16.04' do
   # ...

  it 'creates a systemd service file' do
    expect(chef_run).to create_template('create a systemd service file')
      .with(source: 'unit.service.erb')
      .with(path: '/etc/systemd/system/jar.service')
      .with(owner: 'root')
      .with(group: 'root')
      .with(variables: {
+             commandline_arguments: {},
              path_to_jar: '/var/jar/jar.jar',
              user: 'jar'
            })

    expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
      .with_content do |content|
        expect(content).to match %r{^User=jar$}
        expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar/jar\.jar$}
      end)
  end
 end
 context 'When all attributes are default, on CentOS 7.4.1708' do
   # ...

  it 'creates a systemd service file' do
    expect(chef_run).to create_template('create a systemd service file')
      .with(source: 'unit.service.erb')
      .with(path: '/etc/systemd/system/jar.service')
      .with(owner: 'root')
      .with(group: 'root')
      .with(variables: {
+             commandline_arguments: {},
              path_to_jar: '/var/jar/jar.jar',
              user: 'jar'
            })

    expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
      .with_content do |content|
        expect(content).to match %r{^User=jar$}
        expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar/jar\.jar$}
      end)
  end
 end

 context 'When overriding user and group, when the platform is irrelevant' do
   # ...

  it 'creates a systemd service file' do
    expect(chef_run).to create_template('create a systemd service file')
      .with(variables: {
+             commandline_arguments: {},
              path_to_jar: '/var/jar/jar.jar',
              user: 'jar_user'
            })

    expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
      .with_content do |content|
        expect(content).to match %r{^User=jar_user$}
      end)
  end
 end

 context 'When overriding jar.directory, when the platform is irrelevant' do
   # ...

  it 'creates a systemd service file' do
    expect(chef_run).to create_template('create a systemd service file')
      .with(variables: {
+             commandline_arguments: {},
              path_to_jar: '/var/jar-deploy/jar.jar',
              user: 'jar'
            })

    expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
      .with_content do |content|
        expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar-deploy/jar\.jar$}
      end)
  end
 end
```

As well as adding the new test case:

```ruby
context 'When overriding jar.configuration.commandline_arguments, when the platform is irrelevant' do
  let(:chef_run) do
    runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04') do |node|
      node.automatic['jar']['directory'] = '/var/jar-deploy'
      node.automatic['jar']['configuration']['commandline_arguments']['port'] = 1234
      node.automatic['jar']['configuration']['commandline_arguments']['version'] = nil
    end
    runner.converge(described_recipe)
  end

  before :each do
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).and_raise('include_recipe not matched')
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
      .with('jar-deploy-cookbook::download_jar')
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
      .with('java::default')
  end

  it 'creates a systemd service file' do
    expect(chef_run).to create_template('create a systemd service file')
      .with(variables: {
              commandline_arguments: {
                'port' => 1234,
                'version' => nil
              },
              path_to_jar: '/var/jar-deploy/jar.jar',
              user: 'jar'
            })

    expect(chef_run).to(render_file('/etc/systemd/system/jar.service')
      .with_content do |content|
        expect(content).to match %r{^ExecStart=/usr/bin/java -jar /var/jar-deploy/jar\.jar --port=1234 --version$}
      end)
  end
end
```

As well as ensure that the `jar.configuration.commandline_arguments` is a Hash:

```ruby
node.default['jar']['configuration']['commandline_arguments'] = {}
```

If we run our tests, we'll see them going red:

```
....F.......F.....F.FF....

Failures:

  1) jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(source: 'unit.service.erb')
         .with(path: '/etc/systemd/system/jar.service')
         .with(owner: 'root')
         .with(group: 'root')
         .with(variables: {
                 commandline_arguments: {},
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" to have parameters:

         variables {:commandline_arguments=>{}, :path_to_jar=>"/var/jar/jar.jar", :user=>"jar"}, was {:path_to_jar=>"/var/jar/jar.jar", :user=>"jar"}
       Diff:
       @@ -1,4 +1,3 @@
       -:commandline_arguments => {},
        :path_to_jar => "/var/jar/jar.jar",
        :user => "jar",
     # ./spec/unit/recipes/default_spec.rb:53:in `block (3 levels) in <top (required)>'

  2) jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(source: 'unit.service.erb')
         .with(path: '/etc/systemd/system/jar.service')
         .with(owner: 'root')
         .with(group: 'root')
         .with(variables: {
                 commandline_arguments: {},
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" to have parameters:

         variables {:commandline_arguments=>{}, :path_to_jar=>"/var/jar/jar.jar", :user=>"jar"}, was {:path_to_jar=>"/var/jar/jar.jar", :user=>"jar"}
       Diff:
       @@ -1,4 +1,3 @@
       -:commandline_arguments => {},
        :path_to_jar => "/var/jar/jar.jar",
        :user => "jar",
     # ./spec/unit/recipes/default_spec.rb:130:in `block (3 levels) in <top (required)>'

  3) jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(variables: {
                 commandline_arguments: {},
                 path_to_jar: '/var/jar/jar.jar',
                 user: 'jar_user'
               })

       expected "template[create a systemd service file]" to have parameters:

         variables {:commandline_arguments=>{}, :path_to_jar=>"/var/jar/jar.jar", :user=>"jar_user"}, was {:path_to_jar=>"/var/jar/jar.jar", :user=>"jar_user"}
       Diff:
       @@ -1,4 +1,3 @@
       -:commandline_arguments => {},
        :path_to_jar => "/var/jar/jar.jar",
        :user => "jar_user",
     # ./spec/unit/recipes/default_spec.rb:197:in `block (3 levels) in <top (required)>'

  4) jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(variables: {
                 commandline_arguments: {},
                 path_to_jar: '/var/jar-deploy/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" to have parameters:

         variables {:commandline_arguments=>{}, :path_to_jar=>"/var/jar-deploy/jar.jar", :user=>"jar"}, was {:path_to_jar=>"/var/jar-deploy/jar.jar", :user=>"jar"}
       Diff:
       @@ -1,4 +1,3 @@
       -:commandline_arguments => {},
        :path_to_jar => "/var/jar-deploy/jar.jar",
        :user => "jar",
     # ./spec/unit/recipes/default_spec.rb:235:in `block (3 levels) in <top (required)>'

  5) jar-deploy-cookbook::default When overriding jar.configuration.commandline_arguments, when the platform is irrelevant creates a systemd service file
     Failure/Error:
       expect(chef_run).to create_template('create a systemd service file')
         .with(variables: {
                 commandline_arguments: {
                   'port' => 1234,
                   'version' => nil
                 },
                 path_to_jar: '/var/jar-deploy/jar.jar',
                 user: 'jar'
               })

       expected "template[create a systemd service file]" to have parameters:

         variables {:commandline_arguments=>{"port"=>1234, "version"=>nil}, :path_to_jar=>"/var/jar-deploy/jar.jar", :user=>"jar"}, was {:path_to_jar=>"/var/jar-deploy/jar.jar", :user=>"jar"}
       Diff:
       @@ -1,4 +1,3 @@
       -:commandline_arguments => {"port"=>1234, "version"=>nil},
        :path_to_jar => "/var/jar-deploy/jar.jar",
        :user => "jar",
     # ./spec/unit/recipes/default_spec.rb:268:in `block (3 levels) in <top (required)>'

Finished in 16.2 seconds (files took 2.45 seconds to load)
26 examples, 5 failures

Failed examples:

rspec ./spec/unit/recipes/default_spec.rb:52 # jar-deploy-cookbook::default When all attributes are default, on Ubuntu 16.04 creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:129 # jar-deploy-cookbook::default When all attributes are default, on CentOS 7.4.1708 creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:196 # jar-deploy-cookbook::default When overriding user and group, when the platform is irrelevant creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:234 # jar-deploy-cookbook::default When overriding jar.directory, when the platform is irrelevant creates a systemd service file
rspec ./spec/unit/recipes/default_spec.rb:267 # jar-deploy-cookbook::default When overriding jar.configuration.commandline_arguments, when the platform is irrelevant creates a systemd service file
```

Now we can update our recipe to pass in the `commandline_arguments` attribute to the `template`:

```diff
template 'create a systemd service file' do
   path '/etc/systemd/system/jar.service'
   owner 'root'
   group 'root'
-  variables path_to_jar: "#{node['jar']['directory']}/jar.jar",
+  variables commandline_arguments: node['jar']['configuration']['commandline_arguments'],
+            path_to_jar: "#{node['jar']['directory']}/jar.jar",
             user: node['jar']['user']
 end
```

We'll update our actual Erubis template to expand the arguments:

```diff
 [Unit]
 Description=Run Java JAR

+<%
+  arguments = @commandline_arguments.map do |k, v|
+    if v
+      "--#{k}=#{v}"
+    else
+      "--#{k}"
+    end
+  end
+%>
+
 [Service]
 User=<%= @user %>
 Type=simple
-ExecStart=/usr/bin/java -jar <%= @path_to_jar %>
+ExecStart=/usr/bin/java -jar <%= @path_to_jar %><%= ' ' + arguments.join(' ') unless arguments.length.zero? %>
```

Finally we need to verify in Test Kitchen:

2034
<asciinema-player src="/casts/tdd-chef/arguments.json"></asciinema-player>
Jamie Tanna's avatar
Jamie Tanna committed
2035 2036 2037 2038 2039 2040 2041 2042

Now we're happy with it, we'll perform a minor bump on the cookbook version in our `metadata.rb`, resulting in `0.2.0`:

```diff
-version '0.1.0'
+version '0.2.0'
```

2043
# Reflections
Jamie Tanna's avatar
Jamie Tanna committed
2044

2045
## Refactoring Choices
Jamie Tanna's avatar
Jamie Tanna committed
2046

2047
### Using `context` blocks more effectively
Jamie Tanna's avatar
Jamie Tanna committed
2048 2049 2050

In a few places, we've got uses of Ubuntu / CentOS, but they're actually irrelevant to the tests, as there's nothing platform-specific. It'd be good to refactor this out, and make it more clear what is actually platform-specific.

2051
### Making `context` block nest better
Jamie Tanna's avatar
Jamie Tanna committed
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062

We could also update our context blocks:

```diff
-context 'When all attributes are default, on Ubuntu 16.04' do
+context 'On Ubuntu 16.04' do
+  context 'when all attributes are default' do
```

Which gives us the end result of i.e. `On Ubuntu 16.04 when all attributes are default installs Java using the java::default recipe`.

2063
## Test Coverage
Jamie Tanna's avatar
Jamie Tanna committed
2064 2065 2066 2067 2068

You'll notice that we've been making decisions about _where_ we test attributes and how they get passed into resources. There currently is no way to test your coverage of parameters to resources, which unfortunately means it's something you need to be conscious of while writing a cookbook.

I'm looking to write some tooling around it, but until then, it's something that needs to be remembered!

2069
# Conclusion
Jamie Tanna's avatar
Jamie Tanna committed
2070 2071 2072 2073 2074 2075 2076

We've discovered how best to test-drive a Chef cookbook, using ChefSpec as our main weapon of choice, but supported by Test Kitchen and InSpec to ensure that the converged cookbook works as expected. We've seen the power of unit testing in both speed and ease of use, and can see how we'd be able to apply the principles of TDD to developing Chef cookbooks.

[Semantic Versioning]: https://semver.org
[Java community cookbook]: https://supermarket.chef.io/cookbooks/java
[jar-deploy-cookbook]: https://gitlab.com/jamietanna/jar-deploy-cookbook
[remote_file]: https://docs.chef.io/resource_remote_file.html
2077
[include_recipe]: {{< ref 2017-07-16-chef-testing-include_recipe >}}
Jamie Tanna's avatar
Jamie Tanna committed
2078
[Ohai's]: https://github.com/chef/ohai