Commit fadc906

mo khan <mo.khan@gmail.com>
2019-11-02 15:16:26
Play with pointers
1 parent 727fcdf
bin/lint
@@ -0,0 +1,5 @@
+#!/bin/sh
+
+./bin/setup
+
+errcheck .
bin/setup
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+go get -u github.com/kisielk/errcheck
wallet.go
@@ -0,0 +1,37 @@
+package main
+
+import (
+	"errors"
+	"fmt"
+)
+
+type Bitcoin int
+
+func (b Bitcoin) String() string {
+	return fmt.Sprintf("%d BTC", b)
+}
+
+type Wallet struct {
+	balance Bitcoin
+}
+
+var InsufficientFundsError = errors.New("cannot withdraw, insufficient funds")
+
+func (w *Wallet) Deposit(amount Bitcoin) {
+	fmt.Printf("address of balance in test is %v \n", &w.balance)
+	w.balance += amount
+}
+
+func (w *Wallet) Balance() Bitcoin {
+	fmt.Printf("address of balance in test is %v \n", &w.balance)
+	return w.balance
+}
+
+func (w *Wallet) Withdraw(amount Bitcoin) error {
+	if amount > w.balance {
+		return InsufficientFundsError
+	}
+
+	w.balance -= amount
+	return nil
+}
wallet_test.go
@@ -0,0 +1,54 @@
+package main
+
+import (
+	"fmt"
+	"testing"
+)
+
+func TestWallet(t *testing.T) {
+	t.Run("Deposit", func(t *testing.T) {
+		wallet := Wallet{}
+		wallet.Deposit(Bitcoin(10))
+		fmt.Printf("address of balance in test is %v \n", &wallet.balance)
+		assertBalance(t, wallet, Bitcoin(10))
+	})
+
+	t.Run("Withdraw with funds", func(t *testing.T) {
+		wallet := Wallet{balance: Bitcoin(20)}
+		err := wallet.Withdraw(Bitcoin(10))
+		assertBalance(t, wallet, Bitcoin(10))
+		assertNoError(t, err)
+	})
+
+	t.Run("Withdraw insufficient funds", func(t *testing.T) {
+		wallet := Wallet{balance: Bitcoin(20)}
+		err := wallet.Withdraw(Bitcoin(100))
+		assertBalance(t, wallet, Bitcoin(20))
+		assertError(t, err, InsufficientFundsError)
+	})
+}
+
+func assertBalance(t *testing.T, wallet Wallet, want Bitcoin) {
+	t.Helper()
+	got := wallet.Balance()
+	if got != want {
+		t.Errorf("got %s want %s", got, want)
+	}
+}
+
+func assertError(t *testing.T, got error, want error) {
+	t.Helper()
+	if got == nil {
+		t.Fatal("wanted an error but didn't get one")
+	}
+	if got != want {
+		t.Errorf("got %q, want %q", got, want)
+	}
+}
+
+func assertNoError(t *testing.T, got error) {
+	t.Helper()
+	if got != nil {
+		t.Fatal("wanted an error but didn't get one")
+	}
+}