-
Notifications
You must be signed in to change notification settings - Fork 430
/
05-map.exs
54 lines (43 loc) · 1.24 KB
/
05-map.exs
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
# https://hexdocs.pm/elixir/Map.html
ExUnit.start
defmodule MapTest do
use ExUnit.Case
def sample do
%{foo: 'bar', baz: 'quz'}
end
test "Map.get" do
assert Map.get(sample(), :foo) == 'bar'
assert Map.get(sample(), :non_existent) == nil
end
test "[]" do
assert sample()[:foo] == 'bar'
assert sample()[:non_existent] == nil
end
test "." do
assert sample().foo == 'bar'
assert_raise KeyError, fn ->
sample().non_existent
end
end
test "Map.fetch" do
{:ok, val} = Map.fetch(sample(), :foo)
assert val == 'bar'
:error = Map.fetch(sample(), :non_existent)
end
test "Map.put" do
assert Map.put(sample(), :foo, 'bob') == %{foo: 'bob', baz: 'quz'}
assert Map.put(sample(), :far, 'bar') == %{foo: 'bar', baz: 'quz', far: 'bar'}
end
test "Update map using pattern matching syntax" do
# You can only update existing keys in this way
assert %{ sample() | foo: 'bob'} == %{foo: 'bob', baz: 'quz'}
# It doesn't work if you want to add new keys
assert_raise KeyError, fn ->
%{ sample() | far: 'bob'}
end
end
test "Map.values" do
# Map does not preserve order of keys, thus we Enum.sort
assert Enum.sort(Map.values(sample())) == ['bar', 'quz']
end
end