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 )
15 end
16
17 def stub_rpc(method, params)
18 stub_request(:post, RPC_URI).with(
19 headers: { "Content-Type" => "application/json" },
20 basic_auth: ["username", "password"],
21 body: hash_including(
22 method: method,
23 params: params
24 )
25 )
26 end
27
28 property(:getaddresshistory) { string(:alnum) }
29 em :test_getaddresshistory
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).sync
35 assert_requested(req)
36 end
37
38 property(:get_tx_status) { string(:alnum) }
39 em :test_get_tx_status
40 def get_tx_status(tx_hash)
41 req =
42 stub_rpc("get_tx_status", txid: tx_hash)
43 .to_return(body: { result: "result" }.to_json)
44 assert_equal "result", @electrum.get_tx_status(tx_hash).sync
45 assert_requested(req)
46 end
47
48 property(:gettransaction) { [string(:alnum), string(:xdigit)] }
49 em :test_gettransaction
50 def gettransaction(tx_hash, dummy_tx)
51 req1 =
52 stub_rpc("gettransaction", txid: tx_hash)
53 .to_return(body: { result: dummy_tx }.to_json)
54 req2 =
55 stub_rpc("deserialize", [dummy_tx])
56 .to_return(body: { result: { outputs: [] } }.to_json)
57 assert_kind_of Electrum::Transaction, @electrum.gettransaction(tx_hash).sync
58 assert_requested(req1)
59 assert_requested(req2)
60 end
61
62 class TransactionTest < Minitest::Test
63 def transaction(outputs=[])
64 electrum_mock = Minitest::Mock.new("Electrum")
65 [
66 electrum_mock,
67 Electrum::Transaction.new(
68 electrum_mock,
69 "txhash",
70 "outputs" => outputs
71 )
72 ]
73 end
74
75 def test_confirmations
76 electrum_mock, tx = transaction
77 electrum_mock.expect(
78 :get_tx_status,
79 EMPromise.resolve("confirmations" => 1234),
80 ["txhash"]
81 )
82 assert_equal 1234, tx.confirmations.sync
83 end
84 em :test_confirmations
85
86 def test_amount_for_empty
87 _, tx = transaction
88 assert_equal 0, tx.amount_for
89 end
90
91 def test_amount_for_address_not_present
92 _, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
93 assert_equal 0, tx.amount_for("other_address")
94 end
95
96 def test_amount_for_address_present
97 _, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
98 assert_equal 0.00000001, tx.amount_for("address")
99 end
100
101 def test_amount_for_one_of_address_present
102 _, tx = transaction([{ "address" => "address", "value_sats" => 1 }])
103 assert_equal 0.00000001, tx.amount_for("boop", "address", "lol")
104 end
105 end
106end