2024-09-11 09:08:53 +00:00
|
|
|
package wallet
|
|
|
|
|
2024-09-11 09:49:10 +00:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
func ExampleWallet() {
|
|
|
|
wallet := Wallet{10}
|
|
|
|
|
|
|
|
wallet.Deposit(10)
|
|
|
|
fmt.Printf("The balance is %s\n", wallet.Balance())
|
|
|
|
|
|
|
|
err := wallet.Withdraw(10)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
}
|
|
|
|
fmt.Printf("The balance is %s\n", wallet.Balance())
|
|
|
|
|
|
|
|
// Output: The balance is 20 BTC
|
|
|
|
// The balance is 10 BTC
|
|
|
|
}
|
2024-09-11 09:08:53 +00:00
|
|
|
|
|
|
|
func TestWallet(t *testing.T) {
|
2024-09-11 09:22:04 +00:00
|
|
|
t.Run("deposit", func(t *testing.T) {
|
|
|
|
wallet := Wallet{}
|
|
|
|
wallet.Deposit(10)
|
|
|
|
assertBalance(t, wallet, Bitcoin(10))
|
|
|
|
})
|
2024-09-11 09:26:39 +00:00
|
|
|
|
2024-09-11 09:22:04 +00:00
|
|
|
t.Run("withdraw", func(t *testing.T) {
|
|
|
|
wallet := Wallet{balance: Bitcoin(20)}
|
2024-09-11 09:43:34 +00:00
|
|
|
err := wallet.Withdraw(10)
|
|
|
|
assertNoError(t, err)
|
2024-09-11 09:22:04 +00:00
|
|
|
assertBalance(t, wallet, Bitcoin(10))
|
|
|
|
})
|
2024-09-11 09:26:39 +00:00
|
|
|
|
|
|
|
t.Run("withdraw insufficient funds", func(t *testing.T) {
|
|
|
|
startingBalance := Bitcoin(20)
|
|
|
|
wallet := Wallet{balance: startingBalance}
|
|
|
|
err := wallet.Withdraw(100)
|
|
|
|
|
2024-09-11 09:35:52 +00:00
|
|
|
assertError(t, err, ErrInsufficientFunds)
|
2024-09-11 09:28:45 +00:00
|
|
|
assertBalance(t, wallet, startingBalance)
|
2024-09-11 09:26:39 +00:00
|
|
|
})
|
2024-09-11 09:08:53 +00:00
|
|
|
}
|
2024-09-11 09:35:52 +00:00
|
|
|
|
|
|
|
func assertBalance(t testing.TB, wallet Wallet, want Bitcoin) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
got := wallet.Balance()
|
|
|
|
if got != want {
|
|
|
|
t.Errorf("got %q, want %q", got, want)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func assertError(t testing.TB, got error, want error) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
if got == nil {
|
|
|
|
t.Fatal("didn't get an error but wanted one")
|
|
|
|
}
|
|
|
|
if got != want {
|
|
|
|
t.Errorf("got %q, want %q", got, want)
|
|
|
|
}
|
|
|
|
}
|
2024-09-11 09:43:34 +00:00
|
|
|
|
|
|
|
func assertNoError(t testing.TB, got error) {
|
|
|
|
t.Helper()
|
|
|
|
|
|
|
|
if got != nil {
|
|
|
|
t.Fatal("get an error but didn't want one")
|
|
|
|
}
|
|
|
|
}
|