|
| 1 | +defmodule BitcrowdEcto.FixedWidthIntegerTest do |
| 2 | + use ExUnit.Case, async: true |
| 3 | + import BitcrowdEcto.Assertions |
| 4 | + import Ecto.Changeset |
| 5 | + |
| 6 | + defmodule TestSchema do |
| 7 | + use Ecto.Schema |
| 8 | + |
| 9 | + embedded_schema do |
| 10 | + field(:int_4, BitcrowdEcto.FixedWidthInteger, width: 4) |
| 11 | + field(:int_smallint, BitcrowdEcto.FixedWidthInteger, width: :smallint) |
| 12 | + field(:int_bigserial, BitcrowdEcto.FixedWidthInteger, width: :bigserial) |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + test "casting an out-of-range value results in a changeset error" do |
| 17 | + for ok <- [-2, 2, 0, -2_147_483_648, 2_147_483_647] do |
| 18 | + cs = cast(%TestSchema{}, %{int_4: ok}, [:int_4]) |
| 19 | + assert cs.valid? |
| 20 | + end |
| 21 | + |
| 22 | + for not_ok <- [-2_147_483_649, 2_147_483_648] do |
| 23 | + cs = cast(%TestSchema{}, %{int_4: not_ok}, [:int_4]) |
| 24 | + refute cs.valid? |
| 25 | + assert_error_on(cs, :int_4, :cast) |
| 26 | + end |
| 27 | + |
| 28 | + for ok <- [-2, 2, 0, -32_768, 32_767] do |
| 29 | + cs = cast(%TestSchema{}, %{int_smallint: ok}, [:int_smallint]) |
| 30 | + assert cs.valid? |
| 31 | + end |
| 32 | + |
| 33 | + for not_ok <- [-32_769, 32_768] do |
| 34 | + cs = cast(%TestSchema{}, %{int_smallint: not_ok}, [:int_smallint]) |
| 35 | + refute cs.valid? |
| 36 | + assert_error_on(cs, :int_smallint, :cast) |
| 37 | + end |
| 38 | + |
| 39 | + for ok <- [1, 9_223_372_036_854_775_807] do |
| 40 | + cs = cast(%TestSchema{}, %{int_bigserial: ok}, [:int_bigserial]) |
| 41 | + assert cs.valid? |
| 42 | + end |
| 43 | + |
| 44 | + for not_ok <- [-1, 0, 9_223_372_036_854_775_808] do |
| 45 | + cs = cast(%TestSchema{}, %{int_bigserial: not_ok}, [:int_bigserial]) |
| 46 | + refute cs.valid? |
| 47 | + assert_error_on(cs, :int_bigserial, :cast) |
| 48 | + end |
| 49 | + end |
| 50 | +end |
0 commit comments