Skip to content

Instantly share code, notes, and snippets.

@wojtekmach
Last active June 27, 2020 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wojtekmach/2c59fb3c3c1c274e35d164014662975a to your computer and use it in GitHub Desktop.
Save wojtekmach/2c59fb3c3c1c274e35d164014662975a to your computer and use it in GitHub Desktop.
defmodule TmpDir do
defmacro __using__(_) do
quote do
import unquote(__MODULE__)
setup :setup_tmp_dir
end
end
def setup_tmp_dir(context) do
case context[:tmp_dir] do
nil ->
:ok
true ->
%{tmp_dir: tmp_dir(context.module, context.test)}
path when is_binary(path) ->
%{tmp_dir: tmp_dir(context.module, context.test, path)}
end
end
defp tmp_dir(module, function, path \\ "") do
path =
Path.join(["tmp", escape_path(inspect(module)), escape_path(to_string(function)), path])
File.rm_rf!(path)
File.mkdir_p!(path)
path
end
defp escape_path(path) do
case :os.type() do
{:win32, _} -> String.replace(path, ~R'[~#%&*{}\\:<>?/+|"]', "_")
_ -> path
end
|> String.replace("/", "_")
end
end
defmodule TmpDirTest do
use ExUnit.Case, async: true
use TmpDir
@tag tmp_dir: true
test "tmp_dir!/0", %{tmp_dir: tmp_dir} do
assert tmp_dir =~ "tmp_dir!_0"
assert File.dir?(tmp_dir)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment