Skip to content
This repository has been archived by the owner on Oct 8, 2020. It is now read-only.

Commit

Permalink
Implement Implement Xgit.Util.TrailingHashReadDevice.valid?/1. (#99)
Browse files Browse the repository at this point in the history
* Implement Implement Xgit.Util.TrailingHashReadDevice.valid?/1.

* Add tests and bug fixes.
  • Loading branch information
scouten committed Aug 19, 2019
1 parent c864bfb commit 7f88ddb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/xgit/util/trailing_hash_read_device.ex
Expand Up @@ -50,6 +50,17 @@ defmodule Xgit.Util.TrailingHashReadDevice do
def open_string(s) when is_binary(s) and byte_size(s) >= 20,
do: GenServer.start_link(__MODULE__, {:string, s})

@doc ~S"""
Returns `true` if this is process is an `TrailingHashReadDevice` instance.
Note the difference between this function and `valid_hash?/1`.
"""
@spec valid?(v :: any) :: boolean
def valid?(v) when is_pid(v),
do: GenServer.call(v, :valid_trailing_hash_read_device?) == :valid_trailing_hash_read_device

def valid?(_), do: false

@doc ~S"""
Returns `true` if the hash at the end of the file matches the hash
generated while reading the file.
Expand Down Expand Up @@ -96,6 +107,9 @@ defmodule Xgit.Util.TrailingHashReadDevice do
end

@impl true
def handle_call(:valid_trailing_hash_read_device?, _from_, state),
do: {:reply, :valid_trailing_hash_read_device, state}

def handle_call(:valid_hash?, _from, %{remaining_bytes: 0, crypto: :done} = state),
do: {:reply, :already_called, state}

Expand Down
15 changes: 15 additions & 0 deletions test/xgit/util/trailing_hash_read_device_test.exs
Expand Up @@ -21,6 +21,7 @@ defmodule Xgit.Util.TrailingHashReadDeviceTest do
describe "open_file/1" do
test "simple file" do
assert {:ok, device} = open_file_with_trailing_hash("hello")
assert THR.valid?(device)

assert "hello" = IO.binread(device, 5)
assert :eof = IO.binread(device, 5)
Expand Down Expand Up @@ -107,6 +108,8 @@ defmodule Xgit.Util.TrailingHashReadDeviceTest do

assert capture_log(fn ->
send(device, :random_unknown_message)
Process.sleep(10)
# Give time for message to land.
end) =~ "TrailingHashReadDevice received unexpected message :random_unknown_message"
end

Expand All @@ -122,6 +125,7 @@ defmodule Xgit.Util.TrailingHashReadDeviceTest do
describe "open_string/1" do
test "simple file" do
assert {:ok, device} = open_string_with_trailing_hash("hello")
assert THR.valid?(device)

assert "hello" = IO.binread(device, 5)
assert :eof = IO.binread(device, 5)
Expand All @@ -145,6 +149,17 @@ defmodule Xgit.Util.TrailingHashReadDeviceTest do
end
end

describe "valid?/1" do
test "other process" do
{:ok, pid} = GenServer.start_link(NotValid, nil)
refute THR.valid?(pid)
end

test "not a PID" do
refute THR.valid?("blah")
end
end

defp open_file_with_trailing_hash(s) do
Temp.track!()
path = Temp.path!()
Expand Down

0 comments on commit 7f88ddb

Please sign in to comment.