Skip to content

Commit 3ba4aac

Browse files
authored
Merge pull request #2089 from hexlet-codebattle/users-from-csv
add users from csv util
2 parents 0cad5ac + a888a85 commit 3ba4aac

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
defmodule Codebattle.Utils.PopulateUsers do
2+
@moduledoc false
3+
4+
def from_csv(file) do
5+
utc_now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
6+
7+
users =
8+
File.stream!(file)
9+
|> NimbleCSV.RFC4180.parse_stream()
10+
|> Stream.map(&row_to_user(&1, utc_now))
11+
|> Enum.to_list()
12+
13+
Codebattle.Repo.insert_all(Codebattle.User, users)
14+
end
15+
16+
defp row_to_user([name, password], now) do
17+
%{
18+
name: name,
19+
password_hash: Bcrypt.hash_pwd_salt(password),
20+
inserted_at: now,
21+
updated_at: now
22+
}
23+
end
24+
end
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
defmodule Codebattle.Utils.PopulateUsersTest do
2+
use Codebattle.DataCase, async: true
3+
4+
test "from_csv" do
5+
csv = """
6+
name,password
7+
user1,p@ssw0rd!
8+
user2,adminadmin1234
9+
user3,changem3
10+
user4,"hop hey lala ley"
11+
"""
12+
13+
{fd, path} = Temp.open!()
14+
IO.write(fd, csv)
15+
File.close(fd)
16+
17+
assert {4, nil} = Codebattle.Utils.PopulateUsers.from_csv(path)
18+
assert %{name: "user1"} = Codebattle.User.authenticate("user1", "p@ssw0rd!")
19+
end
20+
end

0 commit comments

Comments
 (0)