File size: 11,867 Bytes
6778ee0 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | defmodule Plausible.AssertMatches do
@moduledoc """
Pattern match assertions wrapper macro extending it with checks expressed
directly within the pattern.
The idea here is that the pin (^) operator does not only rebind existing
binding in the scope but also allows embedding basically any other expression
to match against the given part of the pattern. Normal pattern matching is
also supported and both can be mixed. The only caveat so far is that when
normal patterns fail, only they are listed in the error even if there are
potentially failing expressions. However, once the normal pattern is fixed,
they surface.
Currently, the following expressions can be pinned:
* `any(:atom)`
* `any(:string)`
* `any(:binary)`
* `any(:integer)`
* `any(:pos_integer)`
* `any(:number)`
* `any(:float)`
* `any(:boolean)`
* `any(:map)`
* `any(:list)`
* `any(:tuple)`
* `any(:iso8601_date)`
* `any(:iso8601_datetime)`
* `any(:iso8601_naive_datetime)`
* all above variants of any with a one argument predicate function accepting
value and returning a boolean, like: `any(:integer, & &1 > 20)`
* a special case of `any(:string, ~r/regex pattern/)` checking that value is
a string and matches a pattern
* shorthand version of the above, `~r/regex pattern/`
* any artibrary one argument function returning a boolean, like `&is_float/1`
or `&(&1 < 40 or &1 > 300)`
* exactly(expression) where expression is compared using equality, so that can
enforce full equality inside a pattern, like: `exactly(%{foo: 2})` which will
fail if the value is something like `%{foo: 2, other: "something}`
* any other arbitrary expression which is compared the way as if it was wrapped
with `exactly()`; this allows "interpolating" values from schemas and maps without
rebinding like `user.id` (instead of having to rebind to `user_id` first)
There's also a special pin type, `strict_map(...)` which can wrap around any map
in the pattern. It's enforcing that the pattern has enumerated all the keys
present in the respective map in the pattern matched value. All the above mentioned
pin expressions can be also used inside `strict_map(...)` and `strict_map()` pins
can be nested.
Usage example:
n = %{z: 2}
assert_matches %{
a: ^any(:integer, &(&1 > 2)),
b: ^any(:string, ~r/baz/),
d: [_ | _],
e: ^~r/invalid/,
f: ^n.z,
g: ^(&is_float/1),
h: ^exactly(%{foo: :bar})
} = %{
a: 1,
b: "twofer",
c: :other,
d: [1, 2, 3],
e: "another string",
f: 1,
g: 4.2,
h: %{foo: :bar, other: "stuff"}
}
"""
@doc @moduledoc
defmacro assert_matches({:=, meta, [pattern, value]}) do
{base_strict_pattern, strict_vars} = build_base_strict_pattern(pattern)
base_strict_pattern = clear_bindings_except(base_strict_pattern, :match_var)
strict_patterns =
Enum.map(strict_vars, fn strict_var ->
build_strict_pattern(base_strict_pattern, strict_var)
end)
strict_pattern_matches =
Enum.map(strict_patterns, fn {strict_pattern, _} ->
quote do
assert unquote(strict_pattern) = unquote(value)
end
end)
strict_pattern_checks =
Enum.map(strict_patterns, fn {strict_pattern, [{strict_var, map_pattern_keys}]} ->
build_strict_pattern_check(strict_pattern, strict_var, map_pattern_keys, pattern, value)
end)
{var_pattern, pins} = build_var_pattern(pattern)
clean_pattern =
Enum.reduce(pins, var_pattern, fn {var, _predicate}, pattern ->
Macro.postwalk(pattern, fn
^var -> {:_, [], __MODULE__}
other -> other
end)
end)
var_pattern = clear_bindings_except(var_pattern, :assert_match)
predicate_pattern = build_predicate_pattern(var_pattern, pins)
quote do
value = unquote(value)
assert unquote(clean_pattern) = value
unquote(strict_pattern_matches)
unquote(strict_pattern_checks)
assert unquote(var_pattern) = value
if unquote(length(pins) > 0) do
{errors?, predicate_pattern} = unquote(predicate_pattern)
if errors? do
raise ExUnit.AssertionError,
message: "match (=) failed",
left: predicate_pattern,
right: value,
expr:
{:assert_matches, unquote(meta),
[{:=, [], [unquote(Macro.escape(pattern)), Macro.escape(value)]}]},
context: {:match, []}
end
end
end
end
defp build_base_strict_pattern(pattern) do
Macro.postwalk(pattern, [], fn
{:^, _, [{:strict_map, _, _}]} = pin, acc ->
pinned_var = Macro.unique_var(:match, __MODULE__)
pin = Macro.update_meta(pin, &Keyword.put(&1, :match_var, pinned_var))
{pin, [pinned_var | acc]}
{:^, _, _}, acc ->
{{:_, [], __MODULE__}, acc}
other, acc ->
{other, acc}
end)
end
defp build_strict_pattern(base_strict_pattern, strict_var) do
Macro.postwalk(base_strict_pattern, [], fn
{:^, meta, [{:strict_map, _, [pinned]}]}, acc ->
if meta[:match_var] == strict_var do
{:%{}, _, map_pattern_values} = pinned
map_pattern_keys = map_pattern_values |> Enum.map(&elem(&1, 0)) |> Enum.sort()
{strict_var, [{strict_var, map_pattern_keys} | acc]}
else
{
Macro.postwalk(pinned, fn
{:^, _, _} ->
{:_, [], __MODULE__}
other ->
other
end),
acc
}
end
other, acc ->
{other, acc}
end)
end
defp build_strict_pattern_check(strict_pattern, strict_var, map_pattern_keys, pattern, value) do
quote bind_quoted: [
pattern: Macro.escape(pattern),
value: value,
strict_pattern: Macro.escape(strict_pattern),
var: strict_var,
escaped_var: Macro.escape(strict_var),
pattern_keys: map_pattern_keys
] do
var_keys = var |> Map.keys() |> Enum.sort()
if pattern_keys != var_keys do
missing_keys = var_keys -- pattern_keys
map_pattern_values =
pattern_keys
|> Enum.map(&{&1, {:_, [], __MODULE__}})
|> Enum.concat(Enum.map(missing_keys, &{&1, :_MISSING_KEY__}))
error_pattern =
Macro.postwalk(strict_pattern, fn
^escaped_var -> {:%{}, [], map_pattern_values}
other -> other
end)
raise ExUnit.AssertionError,
message: "match (=) failed",
left: error_pattern,
right: value,
expr: {:assert_matches, [], [{:=, [], [pattern, Macro.escape(value)]}]},
context: {:match, []}
end
end
end
defp build_predicate_pattern(var_pattern, pins) do
quote bind_quoted: [
var_pattern: Macro.escape(var_pattern),
escaped_pins: Macro.escape(pins),
pins: pins
] do
escaped_pins
|> Enum.zip(pins)
|> Enum.reduce({false, var_pattern}, fn {{escaped_var, escaped_predicate}, {var, predicate}},
{errors?, pattern} ->
result =
if is_function(predicate, 1) do
not predicate.(var)
else
predicate != var
end
if result do
escaped_predicate = Plausible.AssertMatches.Internal.strip_prefix(escaped_predicate)
{true,
Macro.postwalk(pattern, fn
^escaped_var -> escaped_predicate
other -> other
end)}
else
{errors?,
Macro.postwalk(pattern, fn
^escaped_var -> {:_, [], __MODULE__}
other -> other
end)}
end
end)
end
end
defp build_var_pattern(pattern) do
Macro.postwalk(pattern, [], fn
{:^, _meta, [{pinned, _, module}]} = normal_pin, acc
when is_atom(pinned) and is_atom(module) ->
{normal_pin, acc}
{:^, _meta, [{:strict_map, _, [pinned]}]}, acc ->
{pinned, acc}
{:^, _meta, [pinned]}, acc ->
pinned = Plausible.AssertMatches.Internal.transform_predicate(pinned)
pinned_var =
Macro.unique_var(:match, __MODULE__)
|> Macro.update_meta(&Keyword.put(&1, :assert_match, true))
{pinned_var, [{pinned_var, pinned} | acc]}
other, acc ->
{other, acc}
end)
end
defp clear_bindings_except(pattern, except_meta) do
pattern
|> Macro.postwalk(fn
{:^, _, [{name, meta, module}]} = pin when is_atom(name) and is_atom(module) ->
if meta[except_meta] do
pin
else
{:_, [], __MODULE__}
end
other ->
other
end)
|> Macro.postwalk(fn
{name, meta, module} = var when is_atom(name) and is_atom(module) ->
if meta[except_meta] do
var
else
{:_, [], __MODULE__}
end
other ->
other
end)
end
defmodule Internal do
@moduledoc false
def transform_predicate({:any, _, [value]}) do
quote do
Plausible.AssertMatches.Internal.any(unquote(value))
end
end
def transform_predicate({:exactly, _, [value]}) do
quote do
Plausible.AssertMatches.Internal.exactly(unquote(value))
end
end
def transform_predicate({:any, _, [value, extra_predicate]}) do
quote do
Plausible.AssertMatches.Internal.any(
unquote(value),
unquote(extra_predicate)
)
end
end
def transform_predicate({:sigil_r, _, _} = regex) do
quote do
Plausible.AssertMatches.Internal.regex(unquote(regex))
end
end
def transform_predicate(other), do: other
def strip_prefix({{:., _, [_prefix, f]}, _, args}) when f in [:any, :regex, :exactly] do
{f, [], args}
end
def strip_prefix(predicate) do
predicate
end
def any(:atom), do: &is_atom/1
def any(:string), do: &is_binary/1
def any(:binary), do: &is_binary/1
def any(:integer), do: &is_integer/1
def any(:number), do: &is_number/1
def any(:float), do: &is_float/1
def any(:boolean), do: &is_boolean/1
def any(:map), do: &is_map/1
def any(:list), do: &is_list/1
def any(:tuple), do: &is_tuple/1
def any(:pos_integer) do
fn value ->
is_integer(value) and value > 0
end
end
def any(:iso8601_date) do
fn value ->
case Date.from_iso8601(value) do
{:ok, _} -> true
_ -> false
end
end
end
def any(:iso8601_datetime) do
fn value ->
case DateTime.from_iso8601(value) do
{:ok, _, _} -> true
_ -> false
end
end
end
def any(:iso8601_naive_datetime) do
fn value ->
case NaiveDateTime.from_iso8601(value) do
{:ok, _} -> true
_ -> false
end
end
end
def any(:string, %Regex{} = regex) do
fn value ->
any(:string).(value) and regex(regex).(value)
end
end
def any(type, predicate_fn) when is_function(predicate_fn, 1) do
fn value ->
any(type).(value) and predicate_fn.(value)
end
end
def regex(regex) do
fn value ->
String.match?(value, regex)
end
end
def exactly(expr) do
fn value ->
value == expr
end
end
end
end
|