-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
fiskalhr_test.go
404 lines (321 loc) · 11.9 KB
/
fiskalhr_test.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package fiskalhrgo
// SPDX-License-Identifier: MIT
// Copyright (c) 2024 L. D. T. d.o.o.
// Copyright (c) contributors for their respective contributions. See https://github.com/l-d-t/fiskalhrgo/graphs/contributors
import (
"encoding/base64"
"encoding/xml"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"math/rand"
)
var testEntity *FiskalEntity
var testOIB, certPath, certPassword string
// TestMain is run before any other tests. It sets up the shared instances and read env variables.
func TestMain(m *testing.M) {
fmt.Println(`
___________.__ __ .__ ___ _____________ ________
\_ _____/|__| _____| | _______ | | / | \______ \ / _____/ ____
| __) | |/ ___/ |/ /\__ \ | | / ~ \ _/ / \ ___ / _ \
| \ | |\___ \| < / __ \| |_\ Y / | \ \ \_\ ( <_> )
\___ / |__/____ >__|_ \(____ /____/\___|_ /|____|_ / \______ /\____/
\/ \/ \/ \/ \/ \/ \/
`)
fmt.Println("Setting up...")
certBase64 := os.Getenv("CIS_P12_BASE64")
certPassword = os.Getenv("FISKALHRGO_TEST_CERT_PASSWORD")
testOIB = os.Getenv("FISKALHRGO_TEST_CERT_OIB")
if certBase64 == "" || certPassword == "" || testOIB == "" {
fmt.Println("CIS_P12_BASE64 or FISKALHRGO_TEST_CERT_PASSWORD or FISKALHRGO_TEST_CERT_OIB environment variables are not set")
fmt.Println(`
The CIS_P12_BASE64 environment variable must contain a single-line base64
encoded string of the original valid Fiskal certificate in P12 format. This
encoded string is essential for the tests to interact with the CIS
(Croatian Fiscalization System).
To encode your P12 certificate file (e.g., fiskalDemo1.p12) to a single-line
base64 string on a Linux system, use the following command:
base64 -w 0 fiskal1.p12
Then, set the CIS_P12_BASE64 environment variable with the encoded string.
Additionally, ensure that the FISKALHRGO_TEST_CERT_PASSWORD and
FISKALHRGO_TEST_CERT_OIB environment variables are set with the appropriate
certificate password and OIB (Personal Identification Number) respectively.
This system is used for the tests because these tests will run in CI
(Continuous Integration), so secrets, for example on GitHub, are passed as
environment variables. This makes it easy and convenient to manage. The
certificate, password, and OIB for tests can be easily stored as GitHub
Action secrets, for example.`)
os.Exit(1)
}
fmt.Printf("Test OIB: %s\n", testOIB)
// Decode the base64 certificate
certData, err := base64.StdEncoding.DecodeString(certBase64)
if err != nil {
fmt.Printf("Failed to decode base64 certificate: %v\n", err)
os.Exit(1)
}
// Create a temporary file to store the certificate
tempDir := os.TempDir()
certPath = filepath.Join(tempDir, "fiskal.p12")
err = os.WriteFile(certPath, certData, 0644)
if err != nil {
fmt.Printf("Failed to write certificate to temp file: %v\n", err)
os.Exit(1)
}
testEntity, err = NewFiskalEntity(testOIB, true, "TEST3", true, true, true, certPath, certPassword)
if err != nil {
fmt.Printf("Failed to create FiskalEntity: %v\n", err)
os.Exit(1)
}
fmt.Println("Running tests...")
// Run tests
code := m.Run()
// Exit with the code returned by m.Run()
os.Exit(code)
}
func TestCertOutput(t *testing.T) {
t.Logf("Testing certificate output...")
fmt.Println(testEntity.DisplayCertInfoText())
testEntity.DisplayCertInfoKeyPoints()
testEntity.DisplayCertInfoMarkdown()
testEntity.DisplayCertInfoHTML()
if testEntity.IsExpiringSoon() {
fmt.Println("WARNING: Certificate is expiring soon!")
}
fmt.Printf("Test certificate expires in %d days\n", testEntity.DaysUntilExpire())
}
// TestGenerateZKI tests the ZKI generation using the previously loaded certificate
func TestGenerateZKI(t *testing.T) {
t.Logf("Testing ZKI generation...")
// Reuse the loaded certManager to generate ZKI
zki, err := testEntity.GenerateZKI(time.Now(), 1, 1, "100.00")
if err != nil {
t.Fatalf("Failed to generate ZKI: %v", err)
}
if zki == "" {
t.Fatalf("Expected non-empty ZKI, but got an empty string")
}
t.Logf("Generated ZKI: %s", zki)
}
// Note: The ZKI (Protection Code) is dependent on the private key used during its generation.
// Any change in the private key will result in a different ZKI, even with the same input data.
// The ZKI generated in this test is based on a specific known certificate and corresponding data.
//
// For external contributors: It is normal for this test to fail if you do not have the required test certificate.
// You can specify a different ZKI to check against using the FISKALHRGO_TEST_KNOWN_ZKI environment variable.
// Alternatively, you can allow this test to fail locally. This test should pass successfully in the official
// GitHub repository and CI environment, where the correct test certificate is available.
func TestKnownZKI(t *testing.T) {
if os.Getenv("FISKALHRGO_TEST_KNOWN_ZKI") == "" {
t.Skip("Skipping TestKnownZKI because FISKALHRGO_TEST_KNOWN_ZKI environment variable is not set")
}
t.Logf("Testing Known LDT ZKI generation...")
expectedZKI := os.Getenv("FISKALHRGO_TEST_KNOWN_ZKI") // This is the ZKI for the test certificate
if !ValidateZKI(expectedZKI) {
t.Fatalf("Invalid ZKI provided in FISKALHRGO_TEST_KNOWN_ZKI environment variable")
}
timeString := "17.05.2024 16:00:38"
// Define the layout (format) for parsing
layout := "02.01.2006 15:04:05"
// Parse the time string into a time.Time object
parsedTime, err := time.Parse(layout, timeString)
if err != nil {
t.Fatalf("Error parsing time: %v", err)
}
// Reuse the loaded certManager to generate ZKI
zki, err := testEntity.GenerateZKI(parsedTime, 13, 1, "90.00")
if err != nil {
t.Fatalf("Failed to generate ZKI: %v", err)
}
if zki == "" {
t.Fatalf("Expected non-empty ZKI, but got an empty string")
}
if zki != expectedZKI {
t.Error("Note:")
t.Error("- The ZKI (Protection Code) is dependent on the private key used.")
t.Error("- Use the FISKALHRGO_TEST_KNOWN_ZKI environment variable to specify your expected ZKI for testing.")
t.Error("- This test should pass on the official GitHub and CI setup where the correct certificate and ZKI pair is available.")
t.Fatalf("ERROR - Expected ZKI: %s, got %s", expectedZKI, zki)
} else {
t.Log("ZKI matched the expected value.")
}
}
// Test CISEcho
func TestCISEcho(t *testing.T) {
t.Logf("Testing CISEcho...")
msg := "Hello, CIS, from FiskalhrGo!"
t.Logf("Sending message to CIS: %s", msg)
// Reuse the loaded certManager to generate ZKI
resp, err := testEntity.EchoRequest(msg)
if err != nil {
t.Fatalf("Failed to make CISEcho request: %v", err)
}
t.Logf("CISEcho Response: %v", resp)
if resp != msg {
t.Fatalf("Expected the sent message returned!")
}
}
func TestPing(t *testing.T) {
t.Log("Testing Ping...")
err := testEntity.PingCIS()
if err != nil {
t.Fatalf("Failed to make Ping request: %v", err)
}
t.Log("Ping OK!")
}
// Test CIS production ping
// This test just the SSL connection and production cert verification pool and ping message to the CIS production server
// The rest should be identical to the demo environment and the rest can only be tested in the demo environment ofc.
func TestProductionPing(t *testing.T) {
if os.Getenv("CISTESTPRODPING") == "" {
t.Skip("Skipping TestProductionPing because CISTESTPRODPING environment variable is not set")
}
t.Log("Testing Production Ping...")
// The path is still to the demo cert, but is not important since we will test only the SSL connection and Echo message
// that is not signed by the user certificate
prodEntity, err := NewFiskalEntity(testEntity.oib, false, "TEST3", true, false, false, certPath, certPassword)
if err != nil {
t.Fatalf("Failed to create production FiskalEntity: %v", err)
}
err = prodEntity.PingCIS()
if err != nil {
t.Fatalf("Failed to make Production Ping request: %v", err)
}
t.Log("Production Ping OK!")
}
// Test CIS invoice with helper functions
func TestNewCISInvoice(t *testing.T) {
pdvValues := [][]interface{}{
{"25.00", "1000.00", "250.00"},
}
pnpValues := [][]interface{}{
{"3.00", "1000.00", "30.00"},
}
ostaliPorValues := [][]interface{}{
{"Other Tax", "5.00", "1000.00", "50.00"},
}
naknadeValues := [][]string{
{"Povratna", "0.50"},
}
dateTime := time.Now()
brOznRac := uint(rand.Intn(6901) + 100)
oznNapUr := uint(1)
iznosUkupno := "1330.50"
oibOper := "12345678901"
invoice, zki, err := testEntity.NewCISInvoice(
dateTime,
brOznRac,
oznNapUr,
pdvValues,
pnpValues,
ostaliPorValues,
"0.00",
"0.00",
"0.00",
naknadeValues,
iznosUkupno,
CISCash,
oibOper,
)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if invoice.Oib != testEntity.oib {
t.Errorf("Expected Oib %v, got %v", testEntity.oib, invoice.Oib)
}
if invoice.USustPdv != true {
t.Errorf("Expected USustPdv true, got %v", invoice.USustPdv)
}
if invoice.DatVrijeme != dateTime.Format("02.01.2006T15:04:05") {
t.Errorf("Expected DatVrijeme %v, got %v", dateTime.Format("02.01.2006T15:04:05"), invoice.DatVrijeme)
}
if invoice.OznSlijed != "P" {
t.Errorf("Expected OznSlijed %v, got %v", "P", invoice.OznSlijed)
}
if invoice.BrRac.BrOznRac != brOznRac {
t.Errorf("Expected BrOznRac %v, got %v", brOznRac, invoice.BrRac.BrOznRac)
}
if invoice.BrRac.OznPosPr != "TEST3" {
t.Errorf("Expected OznPosPr %v, got %v", "TEST3", invoice.BrRac.OznPosPr)
}
if invoice.BrRac.OznNapUr != oznNapUr {
t.Errorf("Expected OznNapUr %v, got %v", oznNapUr, invoice.BrRac.OznNapUr)
}
if invoice.IznosUkupno != iznosUkupno {
t.Errorf("Expected IznosUkupno %v, got %v", iznosUkupno, invoice.IznosUkupno)
}
if invoice.NacinPlac != "G" {
t.Errorf("Expected NacinPlac G, got %v", invoice.NacinPlac)
}
if invoice.OibOper != oibOper {
t.Errorf("Expected OibOper %v, got %v", oibOper, invoice.OibOper)
}
if invoice.ZastKod != zki {
t.Errorf("Expected ZastKod %v, got %v", zki, invoice.ZastKod)
}
// Additional checks for nullable fields
if invoice.Pdv == nil {
t.Errorf("Expected Pdv to be non-nil")
}
if invoice.Pnp == nil {
t.Errorf("Expected Pnp to be non-nil")
}
if invoice.OstaliPor == nil {
t.Errorf("Expected OstaliPor to be non-nil")
}
if invoice.Naknade == nil {
t.Errorf("Expected Naknade to be non-nil")
}
//marshal invoice and log XML
xmlData, err := xml.MarshalIndent(invoice, "", " ")
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
t.Logf("Invoice XML: %s", xmlData)
// Send test invoice to CIS with InvoiceRequest
jir, zkiR, err := invoice.InvoiceRequest()
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if zkiR != zki {
t.Errorf("Expected ZKI %v, got %v", zki, zkiR)
}
t.Logf("We got a JIR!: %v, ZKI: %v", jir, zkiR)
}
func TestSimpleInvoiceFromReadme(t *testing.T) {
invoice, _, err := testEntity.NewCISInvoice(
time.Now(),
uint(1236), // invoice number
uint(1), // register id number
[][]interface{}{ // PDV
{"25.00", "1000.00", "250.00"},
},
nil, // PNP
nil, // Other taxes
"0.00", // total amount of exemptions on the issued invoice.
// Exemptions in cases where goods are delivered or services are
// provided that are exempt from VAT payment.
"0.00", // amount subject to the special margin taxation procedure
// if exist
"0.00", // total amount not subject to taxation on the issued invoice.
// This information is submitted to the Tax Administration only
// if there is an amount on the invoice that is not subject to
// taxation.
nil, // naknade
"1250.00", // total
CISCash, // payment method G - cash, K - credit card, T -
// transfer, O - other, C - check (deprecated)
"12345678901", // operator OIB
)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
// Send test invoice to CIS with InvoiceRequest
jir, zkiR, err := invoice.InvoiceRequest()
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
t.Logf("We got a JIR!: %v, ZKI: %v", jir, zkiR)
}