#!/bin/bash
# Test list2typedef
#
#   Copyright (C) 2014-2023 Ryan Specialty, LLC.
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

cd "$( dirname "$0" )"


# just to ensure that we run all the tests (sum of primes)
declare -i testsum=0


test-typedef-gen()
{
  ((testsum += 1))

  # this list should contain characters that are not valid in constants
  declare -r input='First
Second'\''s @     @Line

# comment
!!!THIRD!!!
'

  declare -r expected='<?xml version="1.0"?>
<package xmlns="http://www.lovullo.com/rater"
         xmlns:c="http://www.lovullo.com/calc"
         xmlns:t="http://www.lovullo.com/rater/apply-template"
         title="FooType Type">
  <typedef name="FooType" desc="FooType">
    <enum type="integer">
      <item name="FOOTYPE_NONE" value="0" desc="NONE" />
      <item name="FOOTYPE_FIRST" value="2706493105" desc="First" />
      <item name="FOOTYPE_SECONDS_LINE" value="3512333918" desc="Second'\''s @     @Line" />
      <item name="FOOTYPE_THIRD" value="519392729" desc="!!!THIRD!!!" />
    </enum>
  </typedef>
</package>'

  # SUT invocation
  declare -r given=$( ../list2typedef FooType < <( cat <<< "$input" ) )

  # expected output
  diff <( cat <<< "$expected" ) <( cat <<< "$given" )
}


test-collision-name-check()
{
  ((testsum += 2))

  # different value, but same generated constant
  local err=$( ../list2typedef Foo 2>&1 >/dev/null <<< '@@@One
Foo
!!!One
' && echo 'EXPECTED FAILURE' )

  [[ "$err" =~ FOO_ONE ]] || {
    echo 'expecting useful error message for name collion' >&2
    return 1
  }
}


test-collision-value-check()
{
  ((testsum += 5))

  # we can easily force a collision by reducing the number of bytes to 1 and
  # calculating hashes from /usr/share/dict/words; this is one example
  local err=$( ../list2typedef Foo 1 2>&1 >/dev/null <<< 'abase
abate
' && echo 'EXPECTED FAILURE' )

  [[ "$err" =~ ABATE && "$err" =~ '157' ]] || {
    echo 'expecting useful error message for value collion' >&2
    return 1
  }
}


test-typedef-gen \
  && test-collision-name-check \
  && test-collision-value-check \
  || {
    echo 'list2typedef test failed' >&2
    exit 1
  }

# safety check
test "$testsum" -eq 8 || {
  echo 'error: did not run all list2typedef tests!' >&2
  exit 1
}
