Skip to content

Commit 0a5beb7

Browse files
dnicallebtc
andauthored
[FEAT] Improve tests (#296)
* test cli arent async tests * unused SERVER_ENDPOINT var * async test werent marked async * make test didnt use correct ports * enable more verbose test logging * refactor conftest variable * not needed anymore are set in conftest * using test_data now for conftest * formatting * comment out invalid hex * remove test dir before creating it to be sure * keep data from altest testrun and ad test_data to ignore * ignore error for CI * add duplicate env var * fix confest * Update pyproject.toml * fix up tests * short p2pk locktimes for faster tests --------- Co-authored-by: callebtc <[email protected]>
1 parent ca2b8e7 commit 0a5beb7

11 files changed

+85
-97
lines changed

Diff for: .env.example

+1-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ TOR=TRUE
1717

1818
# NOSTR
1919
# nostr private key to which to receive tokens to
20-
NOSTR_PRIVATE_KEY=nostr_privatekey_here_hex_or_bech32_nsec
20+
# NOSTR_PRIVATE_KEY=nostr_privatekey_here_hex_or_bech32_nsec
2121
# nostr relays (comma separated list)
2222
NOSTR_RELAYS=["wss://nostr-pub.wellorder.net"]
2323

@@ -38,7 +38,6 @@ MINT_INFO_CONTACT=[["email","[email protected]"], ["twitter","@me"], ["nostr", "np
3838
MINT_INFO_MOTD="Message to users"
3939

4040
MINT_PRIVATE_KEY=supersecretprivatekey
41-
MINT_DATABASE=data/mint
4241
# increment derivation path to rotate to a new keyset
4342
MINT_DERIVATION_PATH="0/0/0/0"
4443

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ tor.pid
133133

134134
# Default data directory
135135
/data
136+
/test_data
136137

137138
# MacOS
138139
.DS_Store

Diff for: Makefile

-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,6 @@ package:
3232
python setup.py sdist bdist_wheel
3333

3434
test:
35-
LIGHTNING=false \
36-
TOR=false \
3735
poetry run pytest tests --cov-report xml --cov cashu
3836

3937
install:

Diff for: cashu/wallet/api/router.py

+27-23
Original file line numberDiff line numberDiff line change
@@ -38,32 +38,35 @@
3838
router: APIRouter = APIRouter()
3939

4040

41-
def create_wallet(
42-
url=settings.mint_url, dir=settings.cashu_dir, name=settings.wallet_name
43-
):
44-
return Wallet(
45-
url=url,
46-
db=os.path.join(dir, name),
47-
name=name,
41+
async def mint_wallet(mint_url: Optional[str] = None):
42+
wallet: Wallet = await Wallet.with_db(
43+
mint_url or settings.mint_url,
44+
db=os.path.join(settings.cashu_dir, settings.wallet_name),
45+
name=settings.wallet_name,
4846
)
49-
50-
51-
async def load_mint(wallet: Wallet, mint: Optional[str] = None):
52-
if mint:
53-
wallet = create_wallet(mint)
54-
await init_wallet(wallet)
5547
await wallet.load_mint()
5648
return wallet
5749

5850

59-
wallet = create_wallet()
51+
wallet: Wallet = Wallet(
52+
settings.mint_url,
53+
db=os.path.join(settings.cashu_dir, settings.wallet_name),
54+
name=settings.wallet_name,
55+
)
6056

6157

6258
@router.on_event("startup")
6359
async def start_wallet():
60+
global wallet
61+
wallet = await Wallet.with_db(
62+
settings.mint_url,
63+
db=os.path.join(settings.cashu_dir, settings.wallet_name),
64+
name=settings.wallet_name,
65+
)
66+
6467
if settings.tor and not TorProxy().check_platform():
6568
raise Exception("tor not working.")
66-
await init_wallet(wallet)
69+
await wallet.load_mint()
6770

6871

6972
@router.post("/pay", name="Pay lightning invoice", response_model=PayResponse)
@@ -78,7 +81,7 @@ async def pay(
7881
raise Exception("lightning not enabled.")
7982

8083
global wallet
81-
wallet = await load_mint(wallet, mint)
84+
wallet = await mint_wallet(mint)
8285

8386
total_amount, fee_reserve_sat = await wallet.get_pay_amount_with_fees(invoice)
8487
assert total_amount > 0, "amount has to be larger than zero."
@@ -116,7 +119,7 @@ async def invoice(
116119
print(f"Requesting split with {n_splits}*{split} sat tokens.")
117120

118121
global wallet
119-
wallet = await load_mint(wallet, mint)
122+
wallet = await mint_wallet(mint)
120123
if not settings.lightning:
121124
await wallet.mint(amount, split=optional_split)
122125
return InvoiceResponse(
@@ -150,16 +153,16 @@ async def swap(
150153
):
151154
if not settings.lightning:
152155
raise Exception("lightning not supported")
153-
incoming_wallet = await load_mint(wallet, mint=incoming_mint)
154-
outgoing_wallet = await load_mint(wallet, mint=outgoing_mint)
156+
incoming_wallet = await mint_wallet(incoming_mint)
157+
outgoing_wallet = await mint_wallet(outgoing_mint)
155158
if incoming_wallet.url == outgoing_wallet.url:
156159
raise Exception("mints for swap have to be different")
157160

158161
# request invoice from incoming mint
159162
invoice = await incoming_wallet.request_mint(amount)
160163

161164
# pay invoice from outgoing mint
162-
await outgoing_wallet.load_proofs()
165+
await outgoing_wallet.load_proofs(reload=True)
163166
total_amount, fee_reserve_sat = await outgoing_wallet.get_pay_amount_with_fees(
164167
invoice.pr
165168
)
@@ -174,7 +177,7 @@ async def swap(
174177

175178
# mint token in incoming mint
176179
await incoming_wallet.mint(amount, hash=invoice.hash)
177-
await incoming_wallet.load_proofs()
180+
await incoming_wallet.load_proofs(reload=True)
178181
mint_balances = await incoming_wallet.balance_per_minturl()
179182
return SwapResponse(
180183
outgoing_mint=outgoing_mint,
@@ -191,7 +194,7 @@ async def swap(
191194
response_model=BalanceResponse,
192195
)
193196
async def balance():
194-
await wallet.load_proofs()
197+
await wallet.load_proofs(reload=True)
195198
keyset_balances = wallet.balance_per_keyset()
196199
mint_balances = await wallet.balance_per_minturl()
197200
return BalanceResponse(
@@ -229,6 +232,7 @@ async def receive_command(
229232
nostr: bool = Query(default=False, description="Receive tokens via nostr"),
230233
all: bool = Query(default=False, description="Receive all pending tokens"),
231234
):
235+
wallet = await mint_wallet()
232236
initial_balance = wallet.available_balance
233237
if token:
234238
tokenObj: TokenV3 = deserialize_token_from_string(token)
@@ -269,7 +273,7 @@ async def burn(
269273
):
270274
global wallet
271275
if not delete:
272-
wallet = await load_mint(wallet, mint)
276+
wallet = await mint_wallet(mint)
273277
if not (all or token or force or delete) or (token and all):
274278
raise Exception(
275279
"enter a token or use --all to burn all pending tokens, --force to check all tokens"

Diff for: tests/conftest.py

+24-32
Original file line numberDiff line numberDiff line change
@@ -16,42 +16,36 @@
1616
from cashu.mint import migrations as migrations_mint
1717
from cashu.mint.ledger import Ledger
1818

19-
SERVER_ENDPOINT = "http://localhost:3337"
19+
SERVER_PORT = 3337
20+
SERVER_ENDPOINT = f"http://localhost:{SERVER_PORT}"
21+
22+
settings.cashu_dir = "./test_data/"
23+
settings.mint_host = "localhost"
24+
settings.mint_port = SERVER_PORT
25+
settings.mint_host = "0.0.0.0"
26+
settings.mint_listen_port = SERVER_PORT
27+
settings.mint_url = SERVER_ENDPOINT
28+
settings.lightning = False
29+
settings.tor = False
30+
settings.mint_lightning_backend = "FakeWallet"
31+
settings.mint_database = "./test_data/test_mint"
32+
settings.mint_derivation_path = "0/0/0/0"
33+
settings.mint_private_key = "TEST_PRIVATE_KEY"
34+
35+
shutil.rmtree(settings.cashu_dir, ignore_errors=True)
36+
Path(settings.cashu_dir).mkdir(parents=True, exist_ok=True)
2037

2138

2239
class UvicornServer(multiprocessing.Process):
23-
def __init__(self, config: Config, private_key: str = "TEST_PRIVATE_KEY"):
40+
def __init__(self, config: Config):
2441
super().__init__()
2542
self.server = Server(config=config)
2643
self.config = config
27-
self.private_key = private_key
2844

2945
def stop(self):
3046
self.terminate()
3147

3248
def run(self, *args, **kwargs):
33-
settings.lightning = False
34-
settings.mint_lightning_backend = "FakeWallet"
35-
settings.mint_database = "data/test_mint"
36-
settings.mint_private_key = self.private_key
37-
settings.mint_derivation_path = "0/0/0/0"
38-
39-
dirpath = Path(settings.mint_database)
40-
if dirpath.exists() and dirpath.is_dir():
41-
shutil.rmtree(dirpath)
42-
43-
dirpath = Path("data/wallet1")
44-
if dirpath.exists() and dirpath.is_dir():
45-
shutil.rmtree(dirpath)
46-
47-
dirpath = Path("data/wallet2")
48-
if dirpath.exists() and dirpath.is_dir():
49-
shutil.rmtree(dirpath)
50-
51-
dirpath = Path("data/wallet3")
52-
if dirpath.exists() and dirpath.is_dir():
53-
shutil.rmtree(dirpath)
54-
5549
self.server.run()
5650

5751

@@ -62,13 +56,13 @@ async def start_mint_init(ledger: Ledger):
6256
await ledger.load_used_proofs()
6357
await ledger.init_keysets()
6458

65-
db_file = "data/mint/test.sqlite3"
59+
db_file = "test_data/mint/test.sqlite3"
6660
if os.path.exists(db_file):
6761
os.remove(db_file)
6862
ledger = Ledger(
69-
db=Database("test", "data/mint"),
70-
seed="TEST_PRIVATE_KEY",
71-
derivation_path="0/0/0/0",
63+
db=Database("test", "test_data/mint"),
64+
seed=settings.mint_private_key,
65+
derivation_path=settings.mint_derivation_path,
7266
lightning=FakeWallet(),
7367
)
7468
await start_mint_init(ledger)
@@ -77,12 +71,10 @@ async def start_mint_init(ledger: Ledger):
7771

7872
@pytest.fixture(autouse=True, scope="session")
7973
def mint():
80-
settings.mint_listen_port = 3337
81-
settings.mint_url = "http://localhost:3337"
8274
config = uvicorn.Config(
8375
"cashu.mint.app:app",
8476
port=settings.mint_listen_port,
85-
host="127.0.0.1",
77+
host=settings.mint_listen_host,
8678
)
8779

8880
server = UvicornServer(config=config)

Diff for: tests/test_cli.py

+4-18
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,13 @@ def cli_prefix():
1616
async def init_wallet():
1717
wallet = await Wallet.with_db(
1818
url=settings.mint_host,
19-
db="data/test_cli_wallet",
19+
db="test_data/test_cli_wallet",
2020
name="wallet",
2121
)
2222
await wallet.load_proofs()
2323
return wallet
2424

2525

26-
@pytest.mark.asyncio
2726
def test_info(cli_prefix):
2827
runner = CliRunner()
2928
result = runner.invoke(
@@ -37,7 +36,6 @@ def test_info(cli_prefix):
3736
assert result.exit_code == 0
3837

3938

40-
@pytest.mark.asyncio
4139
def test_info_with_mint(cli_prefix):
4240
runner = CliRunner()
4341
result = runner.invoke(
@@ -51,7 +49,6 @@ def test_info_with_mint(cli_prefix):
5149
assert result.exit_code == 0
5250

5351

54-
@pytest.mark.asyncio
5552
def test_info_with_mnemonic(cli_prefix):
5653
runner = CliRunner()
5754
result = runner.invoke(
@@ -65,7 +62,6 @@ def test_info_with_mnemonic(cli_prefix):
6562
assert result.exit_code == 0
6663

6764

68-
@pytest.mark.asyncio
6965
def test_balance(cli_prefix):
7066
runner = CliRunner()
7167
result = runner.invoke(
@@ -80,7 +76,6 @@ def test_balance(cli_prefix):
8076
assert result.exit_code == 0
8177

8278

83-
@pytest.mark.asyncio
8479
def test_invoice(mint, cli_prefix):
8580
runner = CliRunner()
8681
result = runner.invoke(
@@ -96,7 +91,6 @@ def test_invoice(mint, cli_prefix):
9691
assert result.exit_code == 0
9792

9893

99-
@pytest.mark.asyncio
10094
def test_invoice_with_split(mint, cli_prefix):
10195
runner = CliRunner()
10296
result = runner.invoke(
@@ -108,7 +102,6 @@ def test_invoice_with_split(mint, cli_prefix):
108102
# assert wallet.proof_amounts.count(1) >= 10
109103

110104

111-
@pytest.mark.asyncio
112105
def test_wallets(cli_prefix):
113106
runner = CliRunner()
114107
result = runner.invoke(
@@ -123,7 +116,6 @@ def test_wallets(cli_prefix):
123116
assert result.exit_code == 0
124117

125118

126-
@pytest.mark.asyncio
127119
def test_send(mint, cli_prefix):
128120
runner = CliRunner()
129121
result = runner.invoke(
@@ -136,7 +128,6 @@ def test_send(mint, cli_prefix):
136128
assert "cashuA" in result.output, "output does not have a token"
137129

138130

139-
@pytest.mark.asyncio
140131
def test_send_without_split(mint, cli_prefix):
141132
runner = CliRunner()
142133
result = runner.invoke(
@@ -149,7 +140,6 @@ def test_send_without_split(mint, cli_prefix):
149140
assert "cashuA" in result.output, "output does not have a token"
150141

151142

152-
@pytest.mark.asyncio
153143
def test_send_without_split_but_wrong_amount(mint, cli_prefix):
154144
runner = CliRunner()
155145
result = runner.invoke(
@@ -159,7 +149,6 @@ def test_send_without_split_but_wrong_amount(mint, cli_prefix):
159149
assert "No proof with this amount found" in str(result.exception)
160150

161151

162-
@pytest.mark.asyncio
163152
def test_receive_tokenv3(mint, cli_prefix):
164153
runner = CliRunner()
165154
token = (
@@ -181,10 +170,10 @@ def test_receive_tokenv3(mint, cli_prefix):
181170
print(result.output)
182171

183172

184-
@pytest.mark.asyncio
185173
def test_receive_tokenv3_no_mint(mint, cli_prefix):
186-
# this test works only if the previous test succeeds because we simulate the case where the mint URL is not in the token
187-
# therefore, we need to know the mint keyset already and have the mint URL in the db
174+
# this test works only if the previous test succeeds because we simulate the case
175+
# where the mint URL is not in the token therefore, we need to know the mint keyset
176+
# already and have the mint URL in the db
188177
runner = CliRunner()
189178
token = (
190179
"cashuAeyJ0b2tlbiI6IFt7InByb29mcyI6IFt7ImlkIjogIjFjQ05JQVoyWC93MSIsICJhbW91bnQiOiAyLCAic2VjcmV0IjogIi1oM0ZXMFFoX1FYLW9ac1V2c0RuNlEiLC"
@@ -205,7 +194,6 @@ def test_receive_tokenv3_no_mint(mint, cli_prefix):
205194
print(result.output)
206195

207196

208-
@pytest.mark.asyncio
209197
def test_receive_tokenv2(mint, cli_prefix):
210198
runner = CliRunner()
211199
token = (
@@ -223,7 +211,6 @@ def test_receive_tokenv2(mint, cli_prefix):
223211
print(result.output)
224212

225213

226-
@pytest.mark.asyncio
227214
def test_receive_tokenv1(mint, cli_prefix):
228215
runner = CliRunner()
229216
token = (
@@ -240,7 +227,6 @@ def test_receive_tokenv1(mint, cli_prefix):
240227
print(result.output)
241228

242229

243-
@pytest.mark.asyncio()
244230
def test_nostr_send(mint, cli_prefix):
245231
runner = CliRunner()
246232
result = runner.invoke(

Diff for: tests/test_mint.py

-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,6 @@
88
from cashu.core.settings import settings
99
from cashu.mint.ledger import Ledger
1010

11-
SERVER_ENDPOINT = "http://localhost:3338"
12-
1311

1412
async def assert_err(f, msg):
1513
"""Compute f() and expect an error message 'msg'."""

0 commit comments

Comments
 (0)