1# frozen_string_literal: true
2
3require 'spec_helper'
4
5RSpec.describe Gitlab::Utils::JsonSizeEstimator do
6  RSpec::Matchers.define :match_json_bytesize_of do |expected|
7    match do |actual|
8      actual == expected.to_json.bytesize
9    end
10  end
11
12  def estimate(object)
13    described_class.estimate(object)
14  end
15
16  [
17    [],
18    [[[[]]]],
19    [1, "str", 3.14, ["str", { a: -1 }]],
20    {},
21    { a: {} },
22    { a: { b: { c: [1, 2, 3], e: Time.now, f: nil } } },
23    { 100 => 500 },
24    { '狸' => '狸' },
25    nil
26  ].each do |example|
27    it { expect(estimate(example)).to match_json_bytesize_of(example) }
28  end
29
30  it 'calls #to_s on unknown object' do
31    klass = Class.new do
32      def to_s
33        'hello'
34      end
35    end
36
37    expect(estimate(klass.new)).to match_json_bytesize_of(klass.new.to_s) # "hello"
38  end
39end
40