File: parsejson_spec.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 5.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 2,804 kB
  • sloc: ruby: 16,417; sh: 46; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 2,351 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'spec_helper'

describe 'parsejson' do
  it 'exists' do
    is_expected.not_to eq(nil)
  end

  it 'raises an error if called without any arguments' do
    is_expected.to run.with_params
                      .and_raise_error(%r{wrong number of arguments}i)
  end

  context 'with correct JSON data' do
    it 'is able to parse JSON data with a Hash' do
      is_expected.to run.with_params('{"a":"1","b":"2"}')
                        .and_return('a' => '1', 'b' => '2')
    end

    it 'is able to parse JSON data with an Array' do
      is_expected.to run.with_params('["a","b","c"]')
                        .and_return(['a', 'b', 'c'])
    end

    it 'is able to parse empty JSON values' do
      actual_array = ['[]', '{}']
      expected = [[], {}]
      actual_array.each_with_index do |actual, index|
        is_expected.to run.with_params(actual).and_return(expected[index])
      end
    end

    it 'is able to parse JSON data with a mixed structure' do
      is_expected.to run.with_params('{"a":"1","b":2,"c":{"d":[true,false]}}')
                        .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [true, false] })
    end

    it 'is able to parse JSON data with a UTF8 and double byte characters' do
      is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}')
                        .and_return('×' => 'これ', 'ý' => '記号', 'です' => { '©' => ['Á', 'ß'] })
    end

    it 'does not return the default value if the data was parsed correctly' do
      is_expected.to run.with_params('{"a":"1"}', 'default_value')
                        .and_return('a' => '1')
    end
  end

  context 'with incorrect JSON data' do
    it 'raises an error with invalid JSON and no default' do
      is_expected.to run.with_params('')
                        .and_raise_error(PSON::ParserError)
    end

    it 'supports a structure for a default value' do
      is_expected.to run.with_params('', 'a' => '1')
                        .and_return('a' => '1')
    end

    ['', 1, 1.2, nil, true, false, [], {}, :yaml].each do |value|
      it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do
        is_expected.to run.with_params(value, 'default_value')
                          .and_return('default_value')
      end
    end
  end
end