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