test_electrum.rb

  1# frozen_string_literal: true
  2
  3require "test_helper"
  4require "electrum"
  5
  6class ElectrumTest < Minitest::Test
  7	RPC_URI = "http://example.com"
  8
  9	def setup
 10		@electrum = Electrum.new(
 11			rpc_uri: RPC_URI,
 12			rpc_username: "username",
 13			rpc_password: "password",
 14			currency: "btc"
 15		)
 16	end
 17
 18	def stub_rpc(method, params)
 19		stub_request(:post, RPC_URI).with(
 20			headers: { "Content-Type" => "application/json" },
 21			basic_auth: ["username", "password"],
 22			body: hash_including(
 23				method: method,
 24				params: params
 25			)
 26		)
 27	end
 28
 29	property(:getaddresshistory) { string(:alnum) }
 30	def getaddresshistory(address)
 31		req =
 32			stub_rpc("getaddresshistory", address: address)
 33			.to_return(body: { result: "result" }.to_json)
 34		assert_equal "result", @electrum.getaddresshistory(address)
 35		assert_requested(req)
 36	end
 37
 38	property(:get_tx_status) { string(:alnum) }
 39	def get_tx_status(tx_hash)
 40		req =
 41			stub_rpc("get_tx_status", txid: tx_hash)
 42			.to_return(body: { result: "result" }.to_json)
 43		assert_equal "result", @electrum.get_tx_status(tx_hash)
 44		assert_requested(req)
 45	end
 46
 47	property(:gettransaction) { [string(:alnum), string(:xdigit)] }
 48	def gettransaction(tx_hash, dummy_tx)
 49		req1 =
 50			stub_rpc("gettransaction", txid: tx_hash)
 51			.to_return(body: { result: dummy_tx }.to_json)
 52		req2 =
 53			stub_rpc("deserialize", [dummy_tx])
 54			.to_return(body: { result: { outputs: [] } }.to_json)
 55		assert_kind_of Electrum::Transaction, @electrum.gettransaction(tx_hash)
 56		assert_requested(req1)
 57		assert_requested(req2)
 58	end
 59
 60	class TransactionTest < Minitest::Test
 61		def transaction(outputs=[])
 62			electrum_mock = Minitest::Mock.new("Electrum")
 63			[
 64				electrum_mock,
 65				Electrum::Transaction.new(
 66					electrum_mock,
 67					"txhash",
 68					"outputs" => outputs
 69				)
 70			]
 71		end
 72
 73		def test_confirmations
 74			electrum_mock, tx = transaction
 75			electrum_mock.expect(
 76				:get_tx_status,
 77				{ "confirmations" => 1234 },
 78				["txhash"]
 79			)
 80			assert_equal 1234, tx.confirmations
 81		end
 82
 83		def test_amount_for_empty
 84			_, tx = transaction
 85			assert_equal 0, tx.amount_for
 86		end
 87
 88		def test_amount_for_address_not_present
 89			_, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
 90			assert_equal 0, tx.amount_for("other_address")
 91		end
 92
 93		def test_amount_for_address_present
 94			_, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
 95			assert_equal 0.00000001, tx.amount_for("address")
 96		end
 97
 98		def test_amount_for_one_of_address_present
 99			_, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
100			assert_equal 0.00000001, tx.amount_for("boop", "address", "lol")
101		end
102	end
103end