【发布时间】:2019-04-21 23:45:21
【问题描述】:
我正在编写一个测试来检查一个函数(当新文件进入文件夹时由 GenServer 自动调用),该函数使用管道调用同一模块中的其他函数以读取文件,处理其内容以插入它,如果需要并返回一个列表(:errors 和 :ok 映射)。
结果看起来像:
[
error: "Data not found",
ok: %MyModule{
field1: field1data,
field2: field2data
},
ok: %MyModule{
field1: field1data,
field2: field2data
},
error: "Data not found"
代码:
def processFile(file) do
insertResultsMap =
File.read!(file)
|> getLines()
|> extractMainData()
|> Enum.map(fn(x) -> insertLines(x) end)
|> Enum.group_by(fn x -> elem(x, 0) end)
handleErrors(Map.get(insertResultsMap, :error))
updateAnotherTableWithLines(Map.get(insertResultsMap, :ok))
end
defp getLines(docContent) do
String.split(docContent, "\n")
end
defp extractMainData(docLines) do
Enum.map(fn(x) -> String.split(x, ",") end)
end
defp insertLines([field1, field2, field3, field4]) do
Attrs = %{
field1: String.trim(field1),
field2: String.trim(field2),
field3: String.trim(field3),
field4: String.trim(field4)
}
mymodule.create_stuff(Attrs)
end
defp handleErrors(errors) do
{:ok, file} = File.open(@errorsFile, [:append])
saveErrors(file, errors)
File.close(file)
end
defp saveErrors(_, []), do: :ok
defp saveErrors(file, [{:error, changeset}|rest]) do
changes = for {key, value} <- changeset.changes do
"#{key} #{value}"
end
errors = for {key, {message, _}} <- changeset.errors do
"#{key} #{message}"
end
errorData = "data: #{Enum.join(changes, ", ")} \nErrors: #{Enum.join(errors, ", ")}\n\n"
IO.binwrite(file, errorData)
saveErrors(file, rest)
end
defp updateAnotherTableWithLines(insertedLines) do
Enum.map(insertedLines, fn {:ok, x} -> updateOtherTable(x) end)
end
defp updateOtherTable(dataForUpdate) do
"CLOSE" -> otherModule.doStuff(dataForUpdate.field1, dataForUpdate.field2)
end
我有几个问题,有些问题很基础,因为我还在学习:
- 你觉得这段代码怎么样?有什么建议吗? (考虑到我自愿混淆了名称)。
- 如果我想测试这个,只测试
processFile函数是正确的方法吗?还是我应该公开更多并单独测试它们? - 当我测试
processFile函数时,我检查我是否收到了一个列表。有什么方法可以确保此列表中只有我正在等待的元素,例如error: "String"或ok: %{}"?
【问题讨论】:
标签: testing pattern-matching elixir phoenix-framework gen-server