aboutsummaryrefslogtreecommitdiffstats
path: root/internal/accounted/accounted_test.go
blob: 01ae42fcf31d57cdeb0300a9da025df00ba79fe3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package accounted

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestMoneyJSON(t *testing.T) {
	b, _ := json.Marshal(Line{Account: "1930", Debit: 123405, Credit: 7})
	want := `{"account_number":"1930","debit_amount":1234.05,"credit_amount":0.07}`
	if string(b) != want {
		t.Errorf("got %s, want %s", b, want)
	}
}

func TestCreateDraftRetriesWithSameKey(t *testing.T) {
	var keys []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		keys = append(keys, r.Header.Get("Idempotency-Key"))
		if r.URL.Path != "/api/v1/companies/c1/journal-entries" || r.Header.Get("Authorization") != "Bearer k" {
			t.Errorf("unexpected request %s %s", r.URL.Path, r.Header.Get("Authorization"))
		}
		if len(keys) == 1 {
			w.Header().Set("Retry-After", "0")
			w.WriteHeader(http.StatusTooManyRequests)
			io.WriteString(w, `{"error":{"code":"RATE_LIMITED","message_en":"slow down"}}`)
			return
		}
		w.WriteHeader(http.StatusCreated)
		io.WriteString(w, `{"data":{"id":"je1","status":"draft"},"meta":{"request_id":"req_1"}}`)
	}))
	defer srv.Close()

	c := NewClient(srv.URL, "k", "c1")
	c.Interval = 0
	id, err := c.CreateDraft(context.Background(), JournalEntry{}, "key-1", false)
	if err != nil || id != "je1" {
		t.Fatalf("id = %q, err = %v", id, err)
	}
	if len(keys) != 2 || keys[0] != "key-1" || keys[1] != "key-1" {
		t.Errorf("idempotency keys = %v", keys)
	}
}

func TestErrorEnvelope(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("dry_run") != "true" {
			t.Error("dry_run not set")
		}
		w.WriteHeader(http.StatusBadRequest)
		io.WriteString(w, `{"error":{"code":"JOURNAL_ENTRY_NOT_BALANCED","message":"Obalanserad","message_en":"Not balanced","request_id":"req_2"}}`)
	}))
	defer srv.Close()

	c := NewClient(srv.URL, "k", "c1")
	c.Interval = 0
	_, err := c.CreateDraft(context.Background(), JournalEntry{}, "key-2", true)
	if !IsCode(err, "JOURNAL_ENTRY_NOT_BALANCED") {
		t.Fatalf("err = %v", err)
	}
}