Skip to content

Instantly share code, notes, and snippets.

@ckampfe
Last active May 20, 2025 19:10
Show Gist options
  • Select an option

  • Save ckampfe/28a1380530f5ffad3d533705aff568c6 to your computer and use it in GitHub Desktop.

Select an option

Save ckampfe/28a1380530f5ffad3d533705aff568c6 to your computer and use it in GitHub Desktop.
defmodule SpecTest do
require Integer
use ExUnit.Case
doctest Spec
test "valid?/2" do
assert Spec.valid?(&Integer.is_even/1, 2)
refute Spec.valid?(&Integer.is_even/1, 1)
assert Spec.valid?(MapSet.new([1, 2, 3]), 1)
refute Spec.valid?(MapSet.new([1, 2, 3]), 9)
end
test "conform/2" do
assert Spec.conform(&Integer.is_even/1, 2) == 2
assert Spec.conform(&Integer.is_even/1, 1) == Spec.Invalid
assert Spec.conform(MapSet.new([1, 2, 3]), 1) == 1
assert Spec.conform(MapSet.new([1, 2, 3]), 9) == Spec.Invalid
end
test "and" do
specs = [&Integer.is_even/1, fn v -> v < 10 end]
assert Spec.conform({:and, specs}, 4) == 4
assert Spec.conform({:and, specs}, 12) == Spec.Invalid
assert Spec.valid?({:and, specs}, 4)
refute Spec.valid?({:and, specs}, 12)
end
test "or" do
specs = [even: &Integer.is_even/1, less_than_10: fn v -> v < 10 end]
assert Spec.conform({:or, specs}, 4) == {:even, 4}
assert Spec.conform({:or, specs}, 9) == {:less_than_10, 9}
assert Spec.conform({:or, specs}, 12) == {:even, 12}
assert Spec.valid?({:or, specs}, 4)
assert Spec.valid?({:or, specs}, 12)
refute Spec.valid?({:or, specs}, 31)
end
test "keys" do
specs = [
required: [
a: {:and, [&is_binary/1, fn v -> String.length(v) < 5 end]},
b: &is_integer/1
],
optional: [c: &is_atom/1]
]
# required keys only
assert Spec.conform({:keys, specs}, %{a: "hi", b: 8}) == %{a: "hi", b: 8}
assert Spec.conform({:keys, specs}, %{a: "longer than 5", b: 8}) == Spec.Invalid
assert Spec.conform({:keys, specs}, %{a: "hi"}) == Spec.Invalid
assert Spec.conform({:keys, specs}, %{a: 842_848_024, b: "not an int"}) == Spec.Invalid
# with opt
assert Spec.conform({:keys, specs}, %{a: "hi", b: 8, c: :foo}) == %{a: "hi", b: 8, c: :foo}
assert Spec.conform({:keys, specs}, %{a: "hi", b: 8, c: "nope"}) == Spec.Invalid
# valid?
assert Spec.valid?({:keys, specs}, %{a: "hi", b: 8})
refute Spec.valid?({:keys, specs}, %{a: "longer than 5", b: 8})
refute Spec.valid?({:keys, specs}, %{a: "hi"})
refute Spec.valid?({:keys, specs}, %{a: 842_848_024, b: "not an int"})
assert Spec.valid?({:keys, specs}, %{a: "hi", b: 8, c: :foo})
refute Spec.valid?({:keys, specs}, %{a: "hi", b: 8, c: "nope"})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment