Skip to content

Commit e5ade2a

Browse files
committed
Write some tests for device controller
1 parent 0c10215 commit e5ade2a

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
defmodule DevicesControllerTest do
2+
use CadetWeb.ConnCase
3+
4+
alias Cadet.Devices.DeviceRegistration
5+
alias Cadet.Repo
6+
7+
setup do
8+
device = insert(:device)
9+
%{device: device}
10+
end
11+
12+
describe "GET /devices" do
13+
@tag authenticate: :student
14+
test "succeeds if authenticated", %{conn: conn, device: device} do
15+
registration = insert_registration(conn, device)
16+
17+
assert [
18+
%{
19+
"id" => registration.id,
20+
"secret" => device.secret,
21+
"title" => registration.title,
22+
"type" => device.type
23+
}
24+
] ==
25+
conn
26+
|> get("/v1/devices")
27+
|> json_response(200)
28+
end
29+
30+
test "401 if unauthenticated", %{conn: conn} do
31+
assert conn
32+
|> get("/v1/devices")
33+
|> response(401)
34+
end
35+
end
36+
37+
describe "POST /devices" do
38+
@tag authenticate: :student
39+
test "succeeds if authenticated", %{conn: conn, device: device} do
40+
registration = make_json_registration(device)
41+
42+
assert response =
43+
conn
44+
|> post("/v1/devices", registration)
45+
|> json_response(200)
46+
47+
assert registration["title"] == response["title"]
48+
assert device.secret == response["secret"]
49+
assert device.type == response["type"]
50+
end
51+
52+
@tag authenticate: :student
53+
test "fails if conflicting type", %{conn: conn, device: device} do
54+
registration = %{make_json_registration(device) | "type" => "installation 00"}
55+
56+
assert conn
57+
|> post("/v1/devices", registration)
58+
|> response(400)
59+
end
60+
61+
@tag authenticate: :student
62+
test "fails if invalid", %{conn: conn, device: device} do
63+
registration = %{make_json_registration(device) | "secret" => ""}
64+
65+
assert conn
66+
|> post("/v1/devices", registration)
67+
|> response(400)
68+
end
69+
70+
test "401 if unauthenticated", %{conn: conn, device: device} do
71+
registration = make_json_registration(device)
72+
73+
assert conn
74+
|> post("/v1/devices", registration)
75+
|> response(401)
76+
end
77+
end
78+
79+
defp make_json_registration(device) do
80+
%{
81+
"title" => Faker.App.name(),
82+
"type" => device.type,
83+
"secret" => device.secret
84+
}
85+
end
86+
87+
defp insert_registration(conn, device) do
88+
%DeviceRegistration{}
89+
|> DeviceRegistration.changeset(%{
90+
title: Faker.App.name(),
91+
user_id: conn.assigns.current_user.id,
92+
device_id: device.id
93+
})
94+
|> Repo.insert()
95+
|> elem(1)
96+
end
97+
end

0 commit comments

Comments
 (0)