towerops/test/towerops/devices/device_query_test.exs

126 lines
3.4 KiB
Elixir

defmodule Towerops.Devices.DeviceQueryTest do
use Towerops.DataCase, async: true
use ExUnitProperties
import Towerops.DevicesFixtures
alias Towerops.Devices.Device
alias Towerops.Devices.DeviceQuery
alias Towerops.Repo
describe "base/0" do
test "returns the Device schema" do
assert DeviceQuery.base() == Device
end
end
describe "for_organization/2" do
test "scopes to a single organization" do
d = device_fixture()
_other = device_fixture()
[%{id: id}] =
DeviceQuery.base()
|> DeviceQuery.for_organization(d.organization_id)
|> Repo.all()
assert id == d.id
end
end
describe "for_organizations/2" do
test "matches any of the given org ids" do
d1 = device_fixture()
d2 = device_fixture()
_ = device_fixture()
ids =
[d1.organization_id, d2.organization_id]
|> DeviceQuery.for_organizations()
|> Repo.all()
|> MapSet.new(& &1.id)
assert MapSet.member?(ids, d1.id)
assert MapSet.member?(ids, d2.id)
end
end
describe "for_site/2 and for_sites/2" do
test "for_site narrows to one site" do
d = device_fixture()
_ = device_fixture()
[%{id: id}] = d.site_id |> DeviceQuery.for_site() |> Repo.all()
assert id == d.id
end
test "for_sites matches any in list" do
d1 = device_fixture()
d2 = device_fixture()
ids =
[d1.site_id, d2.site_id]
|> DeviceQuery.for_sites()
|> Repo.all()
|> MapSet.new(& &1.id)
assert ids == MapSet.new([d1.id, d2.id])
end
end
describe "with_status/2" do
test "filters by status" do
d_down = device_fixture(%{status: "down"})
_d_up = device_fixture(%{status: "up"})
[%{id: id}] = "down" |> DeviceQuery.with_status() |> Repo.all()
assert id == d_down.id
end
end
describe "order_by_display/1" do
test "orders by display_order ascending then name" do
d_a = device_fixture(%{name: "Alpha", display_order: 2})
d_b = device_fixture(%{name: "Bravo", display_order: 1})
d_c = device_fixture(%{name: "Charlie", display_order: 1})
ids =
DeviceQuery.base()
|> DeviceQuery.for_organizations([
d_a.organization_id,
d_b.organization_id,
d_c.organization_id
])
|> DeviceQuery.order_by_display()
|> Repo.all()
|> Enum.map(& &1.id)
# display_order: b,c (=1) come before a (=2). Within (=1), alphabetical name
assert Enum.find_index(ids, &(&1 == d_a.id)) > Enum.find_index(ids, &(&1 == d_b.id))
assert Enum.find_index(ids, &(&1 == d_a.id)) > Enum.find_index(ids, &(&1 == d_c.id))
end
end
describe "property: composing for_organization with another filter narrows results" do
property "for_organization + with_status returns subset of for_organization" do
check all(status <- StreamData.member_of(["up", "down", "unknown"]), max_runs: 6) do
d = device_fixture(%{status: status})
a =
d.organization_id
|> DeviceQuery.for_organization()
|> Repo.all()
|> MapSet.new(& &1.id)
b =
d.organization_id
|> DeviceQuery.for_organization()
|> DeviceQuery.with_status(status)
|> Repo.all()
|> MapSet.new(& &1.id)
assert MapSet.subset?(b, a)
end
end
end
end