Git Product home page Git Product logo

fauxhai's Introduction

ChefSpec

Gem Version CI

ChefSpec is a unit testing framework for testing Chef cookbooks. ChefSpec makes it easy to write examples and get fast feedback on cookbook changes without the need for virtual machines or cloud servers.

ChefSpec runs your cookbooks locally while skipping making actual changes. This has two primary benefits:

  • It's really fast!
  • Your tests can vary node attributes, operating systems, and other system data to assert behavior under varying conditions.

Important Notes

  • ChefSpec requires Ruby 2.5 or later and Chef 15 or later!
  • This documentation corresponds to the main branch, which may be unreleased. Please check the README of the latest git tag or the gem's source for your version's documentation!

ChefSpec aims to maintain compatibility with at least the two most recent minor versions of Chef. If you are running an older version of Chef it may work, or you will need to run an older version of ChefSpec.

As a general rule, if it is tested in the Travis CI matrix, it is a supported version.

Quick Start

When To Use ChefSpec?

As mentioned before, ChefSpec is built for speed. In order to run your tests as quickly as possible (and to allow running tests on your workstation), ChefSpec runs your recipe code with all the resource actions disabled. This means that ChefSpec excels at testing complex logic in a cookbook, but can't actually tell you if a cookbook is doing the right thing. Integration testing is provided by the Test Kitchen project, and for most simple cookbooks without much logic in them we recommend you start off with integration tests and only return to ChefSpec and unit tests as your code gets more complicated.

There are two common "units" of code in Chef cookbooks, custom resources and recipes. If you find yourself with a lot of recipes that are so complex they require unit tests, consider if they can be refactored as custom resources.

Testing a Custom Resource

If you have have a cookbook with a custom resource resources/greet.rb like:

resource_name :mycookbook_greet

property :greeting, String, default: 'Hello'

action :run do
  log "#{new_resource.greeting} world"
end

You can test that resource by creating a spec file spec/greet_spec.rb:

# Load ChefSpec and put our test into ChefSpec mode.
require 'chefspec'

# Describing our custom resource.
describe 'mycookbook_greet' do
  # Normally ChefSpec skips running resources, but for this test we want to
  # actually run this one custom resource.
  step_into :mycookbook_greet
  # Nothing in this test is platform-specific, so use the latest Ubuntu for
  # simulated data.
  platform 'ubuntu'

  # Create an example group for testing the resource defaults.
  context 'with the default greeting' do
    # Set the subject of this example group to a snippet of recipe code calling
    # our custom resource.
    recipe do
      mycookbook_greet 'test'
    end

    # Confirm that the resources created by our custom resource's action are
    # correct. ChefSpec matchers all take the form `action_type(name)`.
    it { is_expected.to write_log('Hello world') }
  end

  # Create a second example group to test a different block of recipe code.
  context 'with a custom greeting' do
    # This time our test recipe code sets a property on the custom resource.
    recipe do
      mycookbook_greet 'test' do
        greeting 'Bonjour'
      end
    end

    # Use the same kind of matcher as before to confirm the action worked.
    it { is_expected.to write_log('Bonjour world') }
  end
end

And then run your test using chef exec rspec.

Testing a Recipe

As a general rule of thumb, only very complex recipes benefit from ChefSpec unit tests. If you find yourself writing a lot of recipe unit tests, consider converting the recipes to custom resources instead. For the sake of example we'll use a simple recipe, recipes/farewell.rb:

log "#{node["mycookbook"]["farewell"]} world"

You can test that recipe by creating a spec file spec/farewell_spec.rb:

# Load ChefSpec and put our test into ChefSpec mode.
require 'chefspec'

# Describing our recipe. The group name should be the recipe string as you would
# use it with include_recipe.
describe 'mycookbook::farewell' do
  # Nothing in this test is platform-specific, so use the latest Ubuntu for
  # simulated data.
  platform 'ubuntu'

  # Create an example group for testing the recipe defaults.
  context 'with default attributes' do
    # Since there was no `recipe do .. end` block here, the default subject is
    # recipe we named in the `describe`. ChefSpec matchers all take the form
    # `action_type(name)`.
    it { is_expected.to write_log('Goodbye world') }
  end

  # Create a second example group to test with attributes.
  context 'with a custom farewell' do
    # Set an override attribute for this group.
    override_attributes['mycookbook']['farewell'] = 'Adios'

    # Use the same kind of matcher as before to confirm the recipe worked.
    it { is_expected.to write_log('Adios world') }
  end
end

Cookbook Dependencies

If your cookbook depends on other cookbooks, you must ensure ChefSpec knows how to fetch those dependencies. If you use a monorepo-style layout with all your cookbooks in a single cookbooks/ folder, you don't need to do anything.

If you are using Berkshelf, require 'chefspec/berkshelf' in your spec file (or spec_helper.rb):

require 'chefspec'
require 'chefspec/berkshelf'

If you are using a Policyfile, require 'chefspec/policyfile' in you spec file (or spec_helper.rb):

require 'chefspec'
require 'chefspec/policyfile'

Your Policyfile.rb should look something like this:

# The policy name is ignored but you need to specify one.
name 'my_cookbook'
# Pull dependent cookbooks from https://supermarket.chef.io/
default_source :supermarket
# The run list is also ignored by ChefSpec but you need to specify one.
run_list 'my_cookbook::default'
# The name here must match the name in metadata.rb.
cookbook 'my_cookbook', path: '.'

Writing Tests

ChefSpec is an RSpec library, so if you're already familiar with RSpec you can use all the normal spec-y goodness to which you are accustomed. The usual structure of an RSpec test file is a file named like spec/something_spec.rb containing:

require 'chefspec'

describe 'resource name or recipe' do
  # Some configuration for everything inside this `describe`.
  platform 'redhat', '7'
  default_attributes['value'] = 1

  context 'when some condition' do
    # Some configuration that only applies to this `context`.
    default_attributes['value'] = 2

    # `matcher` is some matcher function which we'll cover below.
    it { expect(value).to matcher }
    # There is a special value you can expect things on called `subject`, which
    # is the main thing being tested.
    it { expect(subject).to matcher }
    # And if prefer it for readability, `expect(subject)` can be written as `is_expected`.
    it { is_expected.to matcher }
  end

  context 'when some other condition' do
    # Repeat as needed.
  end
end

ChefSpec Matchers

The primary matcher used with ChefSpec are resource matchers:

it { expect(chef_run).to ACTION_RESOURCE('NAME') }
# Or equivalently.
it { is_expected.to ACTION_RESOURCE('NAME') }

This checks that a resource like RESOURCE 'NAME' would have run the specified action if the cookbook was executing normally. You can also test for specific property values:

it { is_expected.to create_user('asmithee').with(uid: 512, gid: 45) }
# You can also use other RSpec matchers to create a "compound matcher". Check
# RSpec documentation for a full reference on the built-in matchers.
it { is_expected.to install_package('myapp').with(version: starts_with("3.")) }

render_file

For the common case of testing that a file is rendered to disk via either a template, file, or cookbook_file resource, you can use a render_file matcher:

it { is_expected.to render_file('/etc/myapp.conf') }
# You can check for specific content in the file.
it { is_expected.to render_file('/etc/myapp.conf').with_content("debug = false\n") }
# Or with a regexp.
it { is_expected.to render_file('/etc/myapp.conf').with_content(/user = \d+/) }
# Or with a compound matcher.
it { is_expected.to render_file('/etc/myapp.conf').with_content(start_with('# This file managed by Chef')) }
# Or with a Ruby block of arbitrary assertions.
it do
  is_expected.to render_file('/etc/myapp.conf').with_content { |content|
    # Arbitrary RSpec code goes here.
  }
end

Notifications

As actions do not normally run in ChefSpec, testing for notifications is a special case. Unlike the resource matchers which evaluate against the ChefSpec runner, the notification matchers evaluate against a resource object:

# To match `notifies :run, 'execute[unpack]', :immediately
it { expect(chef_run.remote_file('/download')).to notify('execute[unpack]') }
# To check for a specific notification action.
it { expect(chef_run.remote_file('/download')).to notify('execute[unpack]').to(:run) }
# And to check for a specific timing.
it { expect(chef_run.remote_file('/download')).to notify('execute[unpack]').to(:run).immediately }

And similarly for subscriptions:

it { expect(chef_run.execute('unpack')).to subscribe_to('remote_file[/download]').on(:create) }

Test Subject

RSpec expectations always need a value to run against, with the main value being tested for a given example group (describe or context block) is called the subject. In ChefSpec this is almost always ChefSpec::Runner that has converge some recipe code.

There are two ways to set which recipe code should be run for the test. More commonly for testing custom resources, you use the recipe helper method in the test to provide an in-line block of recipe code:

describe 'something' do
  recipe do
    my_custom_resource 'something' do
      debug true
    end
  end
end

By using an in-line block of recipe code, you can try many variations to test different configurations of your custom resource.

If no recipe block is present, ChefSpec will use the name of the top-level describe block as a recipe name to run. So for the case of testing a recipe in your cookbook, use the cookbookname::recipename string as the label:

describe 'mycookbook'
# Or.
describe 'mycookbook::myrecipe'

Test Settings

Most ChefSpec configuration is set in your example groups (describe or context blocks) using helper methods. These all follow the RSpec convention of inheriting from a parent group to the groups inside it. So a setting in your top-level describe will automatically be set in any context unless overridden:

describe 'something' do
  platform 'ubuntu'

  # Platform is Ubuntu for any tests here.
  it { is_expected.to ... }

  context 'when something' do
    # Platform is still Ubuntu for any tests here.
  end

  context 'when something else' do
    platform 'fedora'
    # But platform here will be Fedora.
  end
end

Platform Data

To support simulating Chef runs on the same OS as you use your cookbooks on, ChefSpec loads pre-fabricated Ohai data from Fauxhai. To configure which OS' data is set for your test, use the platform helper method:

describe 'something' do
  platform 'ubuntu', '18.04'
  # ...
end

You can specify a partial version number to get the latest version of that OS matching the provided prefix, or leave the version off entirely to get the latest version overall:

# Will use the latest RedHat 7.x.
platform 'redhat', '7'
# Will use the latest version of Windows.
platform 'windows'

WARNING: If you leave off the version or use a partial version prefix, the behavior of your tests may change between versions of Chef Workstation as new data is available in Fauxhai. Only use this feature if you're certain that your tests do not (or should not) depend on the specifics of OS version.

Node Attributes

Node attributes are set using the default_attributes, normal_attributes, override_attributes, and automatic_attributes helper methods. These inherit from a parent group to its children using a deep merge, like in other places in Chef:

describe 'something' do
  default_attributes['myapp']['name'] = 'one'
  default_attributes['myapp']['email'] = '[email protected]'

  context 'when something' do
    default_attributes['myapp']['name'] = 'two'
  end
end

Any values set using automatic_attributes take priority over Fauxhai data.

Step Into

Normally ChefSpec skips all resource (and provider) actions. When testing the implementation of a custom resource, we need to tell ChefSpec to run actions on our specific custom resource so it can be tested:

describe 'something' do
  step_into :my_custom_resource
end

Other ChefSpec Configuration

You can specify any other ChefSpec configuration options using the chefspec_options helper:

describe 'something' do
  chefspec_options[:log_level] = :debug
end

Stubbing

In order to keep unit tests fast and independent of the target system, we have to make sure that any interaction with the system (either the target node or the Chef Server, both parts of the system just in opposite directions) is replaced with a fake, local version. For some thing, like ensuring that resource actions are replaced with a no-op, the stubbing is automatic. For others, we need to tell ChefSpec how to handle things.

Guards

The most common case of interacting with the system is a guard clause on a resource:

not_if 'some command'
# Or.
only_if 'some command'

In order for ChefSpec to know how to evaluate the resource, we need to tell it how the command would have returned for this test if it was running on the actual machine:

describe 'something' do
  recipe do
    execute '/opt/myapp/install.sh' do
      # Check if myapp is installed and runnable.
      not_if 'myapp --version'
    end
  end

  before do
    # Tell ChefSpec the command would have succeeded.
    stub_command('myapp --version').and_return(true)
    # Tell ChefSpec the command would have failed.
    stub_command('myapp --version').and_return(false)
    # You can also use a regexp to stub multiple commands at once.
    stub_command(/^myapp/).and_return(false)
  end
end

If using the Ruby code block form of a guard (e.g. not_if { something }), see the Ruby stubbing section below.

Search

When testing code that uses the search() API in Chef, we have to stub out the results that would normally come from the Chef Server:

describe 'something' do
  recipe do
    web_servers = search(:node, 'roles:web').map { |n| n['hostname'] }
  end

  before do
    stub_search(:node, 'roles:web').and_return([{hostname: 'one'}, {hostname: two}])
  end
end

Searches in libraries

When testing code in a library that uses Chef::Search::Query.new.search(), we have to stub out the results that would normally come from the Chef Server:

describe 'something' do
  recipe do
    results = Chef::Query::Search.new.search(:node, "tags:mytag AND chef_environment:my_env"))
  end

  before do
    query = double
    allow(query).to receive(:search) do |_, arg2|
    case arg2.downcase
    when /tags\:mytag AND chef_environment\:my_env/
        [
            [
                stub_node("server01", ohai: { hostname: "server01", ipaddress: '169.0.0.1' }, platform: 'windows', version: '2016'),
                stub_node("server02", ohai: { hostname: "server02", ipaddress: '169.0.0.2' }, platform: 'windows', version: '2016'),
            ],
            0,
            2,
        ]
    else
        [
            [],
            0,
            0
        ]
    end
    allow(Chef::Search::Query).to receive(:new).and_return(query)
  end
end

Data Bags

Similar to the Search API, the data_bag() and data_bag_item() APIs normally fetch data from Chef Server so we need to stub their results:

describe 'something' do
  recipe do
    # Side note: don't write recipe code like this. This should be `search(:users, '*:*')`.
    users = data_bag('users').map do |user|
      data_bag_item('users', user['id'])
    end
  end

  before do
    stub_data_bag('users').and_return(['asmithee'])
    stub_data_bag_item('users', 'asmithee').and_return({uid: 1234})
  end
end

Resource and Provider Methods

When testing custom resources, it is often useful to stub methods on the resource or provider instance. These can be set up using the stubs_for_resource and stubs_for_provider helpers:

describe 'something' do
  recipe do
    my_custom_resource 'something'
  end

  # Set up stubs for just the one resource.
  stubs_for_resource('my_custom_resource[something]') do |res|
    # Can use any RSpec Mocks code here, see below.
    allow(res).to receive(:something)
  end
  # Stubs for any instance of my_custom_resource.
  stubs_for_resource('my_custom_resource') do |res|
    # ...
  end
  # Stubs for any resource.
  stubs_for_resource do |res|
    # ...
  end

  # Stubs for the provider for just the one resource.
  stubs_for_provider('my_custom_resource[something]') do |res|
    # Can use any RSpec Mocks code here, see below.
    allow(res).to receive(:something)
  end
  # And similar to the above for any provider of a type or any overall.
end

By default, stubs for the resource will also be set up on the current_resource and after_resource objects that are created via load_current_value. This can be disabled by using stubs_for_resource('my_custom_resource[something]', current_value: false). You can also manually set stubs for only the current_resource and after_resource objects using stubs_for_current_value.

Ruby Code

For more complex Ruby code, in recipes, libraries, or custom resources, you have the full power of RSpec and RSpec Mocks available to you.

One issue that comes up often is stubbing filesystem checks such as File.exist?. Since those are global class methods by stubbing them they will be stubbed throughout the entire chef-client codebase that chefspec relies upon. There are many calls to File.exist? in any chefspec test that are not immediately visible to the user. In order to make the client behave correctly the pattern that should be followed is to allow all the chef-client calls to operate normally using and_call_original and then to stub the exact path the test needs:

before do
  allow(File).to receive(:exist?).and_call_original
  allow(File).to receive(:exist?).with('/test/path').and_return(true)
end

All the ruby methods off of the File, Dir and FileUtils classes along with any other global class methods that the client might use, should follow a similar pattern for stubbing.

Check out the RSpec Mocks documentation for more information about setting up Ruby method stubs.

Development

  1. Fork the repository from GitHub.
  2. Clone your fork to your local machine:
$ git clone [email protected]:USER/chefspec.git
  1. Create a git branch
$ git checkout -b my_bug_fix
  1. Write tests

  2. Make your changes/patches/fixes, committing appropriately

  3. Run the tests: bundle exec rake

  4. Push your changes to GitHub

  5. Open a Pull Request

ChefSpec is on [Travis CI][travis] which tests against multiple Chef and Ruby versions.

If you are contributing, please see the Contributing Guidelines for more information.

License

MIT - see the accompanying LICENSE file for details.

fauxhai's People

Contributors

annih avatar anujbiyani avatar cmluciano avatar coderanger avatar hartmantis avatar hynd avatar iartarisi avatar igorlg avatar jmaziarz avatar jugatsu avatar kalabiyau avatar lamont-granquist avatar mancdaz avatar mfischer-zd avatar micgo avatar miketheman avatar nathenharvey avatar nhuff avatar pbanderas avatar pschultz avatar ramereth avatar rmoriz avatar sax avatar sethvargo avatar smurawski avatar tas50 avatar trinitronx avatar yves-vogl avatar zacholauson avatar zhann avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fauxhai's Issues

difference between fauxhai and ohai output

I ran fauxhai on a 12.04 server and found some differences between that and ohai. Most notably fauxhai reports "gems_dir": "/usr/local/gems" but ohai reports "gems_dir": "/usr/local/lib/ruby/gems/1.9.1"

I noticed something similar a long time ago with the 10.04 fixture (which partially led to #18 and #19) and am now digging into the root cause because the issue reappeared in the 12.04 fixture (see https://github.com/customink/fauxhai/blob/master/lib/fauxhai/platforms/ubuntu/12.04.json#L322).

I'll update when I have more info but wanted to raise awareness on this now.

Node attributes are not being set.

I'm a bit perplexed on this one. I'm using the node setting of attributes in other chefspec w/o issue. This is the first time I've used Fauxhai and I'm seeing oddness in that I can't get node[:platform] nor node[:kernel][:machine] to budge from chefspec and i386 for the life of me.

Here's a gist:

https://gist.github.com/joestump/045969db1928537807d9

When I puts my node[:platform] (or node[:kernel][:machine]) they are never set as I'd expect (should be ubuntu and x86_64).

I was trying to add tests to my rstudio cookbook.

Fauxhai lacks the empty virtualization hash

A non-virtualized Chef system still includes the empty hash. A lot of the time people do checks like:

unless node['virtualization']['systems']['docker'] && node['virtualization']['systems']['docker'] == 'guest'

This will fail on fauxhai with a nil error. node['virtualization']['systems'] should exist which would prevent those failures.

Keeping fauxhai data in fixtures directory?

Is there any way to fetch for a local file? The seem to imply that possible but I cant seem to figure out how. In short I would like to keep a few node json files in a fixtures directory and fetch from there when I run my tests.

Centos / RHEL 7.3 missing

Centos / RHEL 7.3 are missing

I can create a PR if usage of bento boxes as source would be fine for you

Fauxhai dies a horrible when Chef isn't installed

Installing the Fauxhai gem doesn't require Chef, but the chef_packages values are used. When trying to set the package attributes on line 36 of runner.rb the nil value isn't handled and fauxhai fails. A simple check of the ohai data would prevent this from blowing up.

CONTRIBUTING.md

I tried to follow the guidelines for contributing and it errors out on executing git clone [email protected]:customink/fauxhai.git indicating permission denied. Should the directions be updated to indicate that one should fork the repo, create the branch, etc, etc?

Thanks!

Could not find a valid gem 'fauxhai' (~> 2.3) in any repository

[2016-04-18T05:47:59-07:00] ERROR: chef_gem[chefspec] (tc3-chefspec::gem_install line 41) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '2'
---- Begin output of C:/opscode/chef/embedded/bin/gem install C:\chef\cache\chefspec-4.4.0.gem -q --no-rdoc --no-ri -v "4.4.0" --local ----
STDOUT: 
STDERR: ERROR:  Could not find a valid gem 'fauxhai' (~> 2.3) in any repository
---- End output of C:/opscode/chef/embedded/bin/gem install C:\chef\cache\chefspec-4.4.0.gem -q --no-rdoc --no-ri -v "4.4.0" --local ----
Ran C:/opscode/chef/embedded/bin/gem install C:\chef\cache\chefspec-4.4.0.gem -q --no-rdoc --no-ri -v "4.4.0" --local returned 2; ignore_failure is set, continuing
[2016-04-18T05:47:59-07:00] INFO: Processing log[end tc3-chefspec::gem_install] action write (tc3-chefspec::gem_install line 54)
[2016-04-18T05:47:59-07:00] INFO: end tc3-chefspec::gem_install
[2016-04-18T05:47:59-07:00] INFO: Chef Run complete in 16.51561 seconds
[2016-04-18T05:48:00-07:00] INFO: Running report handlers
[2016-04-18T05:48:00-07:00] INFO: Report handlers complete

Network Interfaces structure doens't match current ohai

It looks like the current fauxhai files list network interfaces as:

"network": {
  "lo": { ... },
  "eth0": { ... }
}

but the current version of ohai returns the data as

"network": {
  "interfaces": {
    "lo": { ... },
    "eth0": { ... }
  }
}

Obviously, this impacts a ton of files.

Examples are incorrect

Seems like the Fauxhai.mock syntax in the examples is incorrect.

Non-working example:

Fauxhai.mock(platform:'ubuntu', version:'12.04')

Looks like it should be:

Fauxhai.mock(:platform => 'ubuntu', :version => '12.04')

Unless I'm missing something?

Should we complete windows ohai files?

Hello,

TL;DR: Do you think it would be usefull to have more specific windows ohais (i386, x64, CORE)? - could be extended to other platforms

I'm currently adding test to one of my cookbooks, and wanted to validate them using most of the windows fauxhai already available. Doing so I encounter a small issue regarding the machine architecture... sometimes I need to test theoric behavior on specific windows "setup" - 32/64bit, CORE.
I also faced the absence of older versions of windows e.g. 7 or Vista/Server 2008.

It's feasible to take one existing fauxhai and transform it to another version by overriding specifics attributes, but it's adding complexity to the tests.

Here is an updated list of possible fauxhai files - bold for already existing versions:

Name Version Windows Server Server Core
2008 6.0.6001 ✖️
7/2008R2 6.1.7600 ✔️ ✔️
8/2012 6.2.9200 ✔️
8.1/2012R2 6.3.9600 ✔️ ✔️
10 v1507 (TH1) 10.0.10240 ✖️ ✖️
10 v1511 (TH2) 10.0.10586 ✖️ ✖️
10/2016 v1607 (RS1) 10.0.14393 ✔️
10 v1703 (RS2) 10.0.15063 ✔️ ✖️ ✖️
10/2016 v1709 (RS3) 10.0.16999 ✖️

Some of the windows version I listed are old, I first chose to start with 2003R2 generation because fauxhai already support it, but hey 2003R2 is not supported by chef :)
Current fauxhai represents 7 / 19 possibilities, but maybe we don't need to support all of them - I already skip the itanium arch :)

If this issue gathers enough interest, I would be able to provide most of the missing fauxhai files; then we should also define a naming convention e.g. <version>-<arch>[-CORE]

So for people who read everything, what do you think?

cc: @aboten

Update1: removed 32bits version as they are not supported by Chef
Update2: added Windows 10 & Server 2016 versions

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

  spec.license = 'MIT'
  # or
  spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Ready for a new release

All major platform versions have been regenerated with the current Ohai release. Ready to get a new gem out so people can use the new dumps

Moving Fauxhai.mock into before :each Fails

I've been trying to stub out search for chefspec tests which requires me to do the converge inside of before :each instead of before :all. When I try moving Fauxhai.mock and converge from before :all to before :each my tests go from passing to failing. It looks like the fauxhai attributes aren't getting set.

To demonstrate I've created two branches of https://github.com/customink-webops/chef-openssh. The chefspec branch uses before :all and the chefspec-broken uses before :each with the same tests.

Thanks,
Jake.

Chef encountered an error attempting to load the node data for "fauxhai.local"

================================================================================
Chef encountered an error attempting to load the node data for "fauxhai.local"

Authentication Error:

Failed to authenticate to the chef server (http 401).

Server Response:

Relevant Config Settings:

chef_server_url "https://radche/organizations/radian"
node_name "fauxhai.local"
client_key ""

If these settings are correct, your client_key may be invalid, or
you may have a chef user with the same client name as this node.

Platform:

x86_64-linux

example at ./spec/recipes/default_spec.rb:25 (FAILED - 6)

Secondary download from github for json

It doesn't make sense to release a new version of fauxhai every time we add a new platform.json file. Instead, we should look for the JSON locally, then search the official repo on github, then throw an error.

Install new platforms outside of a test run

AFAIU, fauxhai can currently download new platforms when doing a test run that requires that platform version.

This is a problem when fauxhai is installed system-wide and tests are run under a user which does not have system-wide read-access.

It would be great to have a command line utility to install platforms manually without having to run a test. Maybe this could be a parameter to the existing fauxhai command.

Using fauxhai in production to fake ohai data

I wonder if it is possible to run a chef-client and override anything that ohai could report with this gem. Any idea how to do this?

The goal is to impersonate another server that cannot run chef directly.

lib/fauxhai/runner.rb:39:in `chef_packages': undefined method `[]' for nil:NilClass (NoMethodError)

In my environment:

$ cat /etc/issue
CentOS release 6.6 (Final)
Kernel \r on an \m

$ uname -i
x86_64
$ /opt/chef/embedded/bin/bundle --path ~/.vendor --binstubs 
Fetching gem metadata from https://rubygems.org.............
Resolving dependencies...
Installing rake 10.4.2
Installing net-ssh 2.9.2
Installing ffi 1.9.10
Installing libyajl2 1.2.0
Installing ffi-yajl 2.2.2
Installing ipaddress 0.8.0
Installing mime-types 2.6.1
Installing mixlib-cli 1.5.0
Installing mixlib-config 2.2.1
Installing mixlib-log 1.6.0
Installing mixlib-shellout 2.1.0
Installing systemu 2.6.5
Installing wmi-lite 1.0.0
Installing ohai 8.5.0
Installing fauxhai 2.3.0
Using bundler 1.7.2
Your bundle is complete!
It was installed into ./.vendor

This fails:

$ /opt/chef/embedded/bin/ruby bin/fauxhai 
/home/veetow/.vendor/ruby/2.1.0/gems/fauxhai-2.3.0/lib/fauxhai/runner.rb:39:in `chef_packages': undefined method `[]' for nil:NilClass (NoMethodError)
        from /home/veetow/.vendor/ruby/2.1.0/gems/fauxhai-2.3.0/lib/fauxhai/runner.rb:11:in `initialize'
        from /home/veetow/.vendor/ruby/2.1.0/gems/fauxhai-2.3.0/bin/fauxhai:23:in `new'
        from /home/veetow/.vendor/ruby/2.1.0/gems/fauxhai-2.3.0/bin/fauxhai:23:in `<top (required)>'
        from bin/fauxhai:16:in `load'
        from bin/fauxhai:16:in `<main>'

But running the same via Ohai is fine:

$ /opt/chef/embedded/bin/pry
[1] pry(main)> require 'ohai'
=> true
[2] pry(main)> @system = Ohai::System.new
=> #<Ohai::System:0x00000002a37cb0
 @data={},
 @loader=#<Ohai::Loader:0x00000002a37670 @controller=#<Ohai::System:0x00000002a37cb0 ...>, @v6_plugin_classes=[], @v7_plugin_classes=[]>,
 @plugin_path="",
 @provides_map=#<Ohai::ProvidesMap:0x00000002a37ad0 @map={}>,
 @runner=#<Ohai::Runner:0x00000002a373f0 @provides_map=#<Ohai::ProvidesMap:0x00000002a37ad0 @map={}>, @safe_run=true>,
 @v6_dependency_solver={}>
[3] pry(main)> @system.all_plugins
=> [#<Ohai::NamedPlugin::Hostname:0x00000003c986c0
  @data=
<snip>
[4] pry(main)> @system.data['chef_packages']
=> {"ohai"=>{"version"=>"8.5.0", "ohai_root"=>"/opt/chef/embedded/lib/ruby/gems/2.1.0/gems/ohai-8.5.0/lib/ohai"},
 "chef"=>{"version"=>"12.4.0", "chef_root"=>"/opt/chef/embedded/lib/ruby/gems/2.1.0/gems/chef-12.4.0/lib"}}

Difficulty over-riding dmi values for machine configuration

I'm trying to override some vendor information in the DMI section of the fauxhai data, but it doesn't seem to work.
Specifically I'm trying to over-ride the following value:

context "When running on a VENDORX server" do
  before do
    @chef_run_vendorx = ChefSpec::Runner.new
    stub_command("sudo -V").and_return(true)
    Fauxhai.mock(platform: 'centos', version: '5.8') do |node|
      node['dmi']['bios']['all_records'][0]['Vendor'] = "VENDORX"
    end
  end
  it "Installs sudoers permissions for VENDORTOOL " do
    @chef_run_vendorx.converge described_recipe
    expect(@chef_run_vendorx).to install_sudo 'monitor-vendorx-raid'
  end
end

However, the value of

node['dmi']['bios']['all_records'][0]['Vendor']

, when running ChefSpec always comes out as Innotek GMBH, which is the value stored in Fauxhai's json file for the platform. I realize I could create a fork of the json file with the required dmi info, but I'd rather use the over-rides. Am I doing something wrong?

Add a CentOS 6.7 platform

Centos 6.7 was release on Sep 5th. Do you think that a platform for that can be added in the future?

OpenURI based fetching should rescue socket errors too

Happens when not online so DNS resolution fails. Also the fact that Fauxhai talks to the internet at all makes me suuuuper nervous, now that most platforms are filled out maybe it would be good to remove that code?

"OpenURI::HTTPError: 404 Not Found" is returned when entering the wrong platform version

I am new to ChefSpec. But not to Rspec.

I wrote this first test where I specify the platform:

require "spec_helper"

describe_recipe "ark::default" do

  def node_properties
    { :platform => "centos" }
  end

  it "installs core packages" do
      expect(chef_run).to install_package("xz-lzma-compat")
  end

end

I get an error that is helpful:

Failure/Error: expect(chef_run).to install_package(package)
Fauxhai::Exception::InvalidVersion:
  Platform version not specified

However, when I specify an incorrect version in the test:

Failure/Error: expect(chef_run).to install_package(package)
OpenURI::HTTPError:
  404 Not Found

@someara set me straight and pointed me here.

Only skimming the code, I believe that I could setup some :host that contains a number of fake ohai data and that fauxhai is possibly reaching out for them. In the event that I haven't I imagine the 404 makes sense. Of course, what I did wrong is type in the wrong "version" number of a platform that already exists within the gem.

I would love to see an error message that tells me:

Sorry version X that you provided is not available. Available versions for this platform are: [ Y, Z, A ].

I don't want this to trump the error message when someone may configure a host badly, so you may want to augment that message to state the host or location it attempted to look.

If this is a useful feature I can fork and open a pull request unless you would love to handle it.

Bump gem version

Ohai

With the recent rhel7.1 update in #139, a new version of the gem needs to be released to rubygems. Would you please cut a new gem?

Thanks!

Fauxhai 2.2.0 not doing value_for_platform_family properly

As mentioned on Chefspec (chefspec/chefspec#477 (comment)) I am having issues with the recent release of Fauxhai. I am using a template which acts on variables set by a previous value_for_platform_family call:

config = value_for_platform_family(
  'rhel' => '/etc/vsftpd/vsftpd.conf',
  'redhat' => '/etc/vsftpd/vsftpd.conf',
  'centos' => '/etc/vsftpd/vsftpd.conf',
  'debian' => '/etc/vsftpd.conf'
)

# rubocop:disable Style/LineLength,
{ 'vsftpd.conf.erb' => config,
  'vsftpd.chroot_list.erb' => node['vsftpd']['config']['chroot_list_file'],
  'vsftpd.user_list.erb' => node['vsftpd']['config']['userlist_file'] }.each do |template, destination|
  # rubocop:enable Style/LineLength
  template destination do
    source template
    notifies :restart, 'service[vsftpd]', :delayed
  end
end

With the prior 2.1.2 version, this worked fine. Also removing that value_for_platform_family and replacing it with a static file path works fine. This is my full chefspec:

require 'spec_helper'

describe 'vsftpd::default' do
  { 'redhat' => '6.5', 'debian' => '7.5' }.each do |platform_family, platform_version|
    describe "for #{platform_family}" do
      before(:all) do
        @chef_run = ChefSpec::Runner.new('platform' => platform_family,
                                         'version' => platform_version)
        @chef_run.node.set['platform_family'] = platform_family
        @chef_run.node.set['vsftpd'] = { 'allowed' => ['vagrant'], 'chroot' => ['vagrant'] }
        @chef_run.converge(described_recipe)
      end

      it 'should install vsftpd' do
        expect(@chef_run).to install_package('vsftpd')
      end

      it 'should create configuration directory /etc/vsftpd/users.d'do
        expect(@chef_run).to create_directory('/etc/vsftpd/users.d')
      end if platform_family == 'debian'

      platform_family == 'debian' ? config = '/etc/vsftpd.conf' : config = '/etc/vsftpd/vsftpd.conf'

      { config => 'local_enable=YES',
        '/etc/vsftpd/vsftpd.chroot_list' => 'vagrant',
        '/etc/vsftpd/vsftpd.user_list' => 'vagrant' }.each do |file, content|
        it "should create file #{file} with specific content" do
          expect(@chef_run).to render_file(file)
          expect(@chef_run).to render_file(file).with_content(content)
        end
      end

      it 'should enable and start service vsftpd' do
        expect(@chef_run).to start_service('vsftpd')
        expect(@chef_run).to enable_service('vsftpd')
      end
    end
  end
end

It may be related to my versioning for Debian and Redhat? Not sure if that changed in Fauxhai.

could we go back to having regular releases of Fauxhai?

Hey Seth and friends,

I was wondering if we could go back to having regular releases of the Fauxhai gem to pick up all the OS definitions.

I realize that mocker.rb has the ability to fetch updated platforms off GitHub, but this doesn't really work when I'm on a plane and trying to write unit tests for platforms that don't exist in the released Gem (actual situation last week).

Thoughts?

Cut a new Gem?

Would you please cut a new gem? I saw that you recently merged node['lsb']['codename'] attributes. The potgresql cookbook is now utilizing these, and any cookbook of ours that depends on postgresql is failing due to these attributes not existing.

Cutting a new gem would be much appreciated.

Fedora supported?

Should there be a fedora platform supported by fauxhai? I am working on the chefspec tests for the stackforge openstack cookbooks, and we have use cases where fedora platform may do something different than redhat/centos.

The OS is different enough to deserve it's own fedora platform, right? Curious, so I now if I should create a pull request or not.

Thanks -
john

Feature request: allow user to specify directory for caching downloaded files

Hi there -- I tripped over a problem while using the ChefDK on OS X. I was running a ChefSpec test for Debian 8.2. The platform file isn't included in the version of fauxhai included in the ChefDK, so fauxhai tried to download it...only it was unable to save it locally because the permissions were restricted:

Failures:
  1) neteng_network_tools::default On debian 8.0 installs hping3
     Failure/Error: runner.converge(described_recipe)
     Errno::EACCES:
       Permission denied @ rb_sysopen - /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/fauxhai-2.3.0/lib/fauxhai/platforms/debian/8.0.json
     # ./spec/unit/recipes/default_spec.rb:26:in `block (6 levels) in <top (required)>'
     # ./spec/unit/recipes/default_spec.rb:30:in `block (6 levels) in <top (required)>'

It would be nice if fauxhai could save that somewhere else (~/.fauxhai/platforms, maybe?) -- either if configured, or just as a fallback mechanism if saving to the original directory failed.

I realize that this could also be directed at the ChefDK project to change permissions for the installation; however, I think this could potentially be useful for other fauxhai users too.

Thanks, and please let me know if you need any further information.

Windows 2008R2 Platform

I am encountering the following issue when using the Windows 2008R2 platform:

JSON::ParserError:
       757: unexpected token at '??{'
     # /Library/Ruby/Gems/2.0.0/gems/json-1.8.3/lib/json/common.rb:155:in `parse'
     # /Library/Ruby/Gems/2.0.0/gems/json-1.8.3/lib/json/common.rb:155:in `parse'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai/mocker.rb:56:in `block in fauxhai_data'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai/mocker.rb:77:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai/mocker.rb:77:in `fauxhai_data'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai/mocker.rb:26:in `initialize'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai.rb:12:in `new'
     # /Library/Ruby/Gems/2.0.0/gems/fauxhai-2.3.0/lib/fauxhai.rb:12:in `mock'
     # /Library/Ruby/Gems/2.0.0/gems/chefspec-4.4.0/lib/chefspec/solo_runner.rb:373:in `client'
     # /Library/Ruby/Gems/2.0.0/gems/chefspec-4.4.0/lib/chefspec/solo_runner.rb:141:in `node'
     # /Library/Ruby/Gems/2.0.0/gems/chefspec-4.4.0/lib/chefspec/solo_runner.rb:84:in `initialize'

I took a quick look and noticed that the 'windows/2008R2.json' file is specified as UTF-16, while the others are UTF-8. Converting the file's encoding resolved the issue for me.

If there's any additional information I can provide regarding this issue, let me know.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.