...
1 package qr
2
3 import (
4 "fmt"
5 "image/png"
6 "os"
7 "testing"
8
9 "github.com/boombuler/barcode"
10 )
11
12 type test struct {
13 Text string
14 Mode Encoding
15 ECL ErrorCorrectionLevel
16 Result string
17 }
18
19 var tests = []test{
20 test{
21 Text: "hello world",
22 Mode: Unicode,
23 ECL: H,
24 Result: `
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 func Test_GetUnknownEncoder(t *testing.T) {
54 if unknownEncoding.getEncoder() != nil {
55 t.Fail()
56 }
57 }
58
59 func Test_EncodingStringer(t *testing.T) {
60 tests := map[Encoding]string{
61 Auto: "Auto",
62 Numeric: "Numeric",
63 AlphaNumeric: "AlphaNumeric",
64 Unicode: "Unicode",
65 unknownEncoding: "",
66 }
67
68 for enc, str := range tests {
69 if enc.String() != str {
70 t.Fail()
71 }
72 }
73 }
74
75 func Test_InvalidEncoding(t *testing.T) {
76 _, err := Encode("hello world", H, Numeric)
77 if err == nil {
78 t.Fail()
79 }
80 }
81
82 func imgStrToBools(str string) []bool {
83 res := make([]bool, 0, len(str))
84 for _, r := range str {
85 if r == '+' {
86 res = append(res, true)
87 } else if r == '.' {
88 res = append(res, false)
89 }
90 }
91 return res
92 }
93
94 func Test_Encode(t *testing.T) {
95 for _, tst := range tests {
96 res, err := Encode(tst.Text, tst.ECL, tst.Mode)
97 if err != nil {
98 t.Error(err)
99 }
100 qrCode, ok := res.(*qrcode)
101 if !ok {
102 t.Fail()
103 }
104 testRes := imgStrToBools(tst.Result)
105 if (qrCode.dimension * qrCode.dimension) != len(testRes) {
106 t.Fail()
107 }
108 t.Logf("dim %d", qrCode.dimension)
109 for i := 0; i < len(testRes); i++ {
110 x := i % qrCode.dimension
111 y := i / qrCode.dimension
112 if qrCode.Get(x, y) != testRes[i] {
113 t.Errorf("Failed at index %d", i)
114 }
115 }
116 }
117 }
118
119 func ExampleEncode() {
120 f, _ := os.Create("qrcode.png")
121 defer f.Close()
122
123 qrcode, err := Encode("hello world", L, Auto)
124 if err != nil {
125 fmt.Println(err)
126 } else {
127 qrcode, err = barcode.Scale(qrcode, 100, 100)
128 if err != nil {
129 fmt.Println(err)
130 } else {
131 png.Encode(f, qrcode)
132 }
133 }
134 }
135
View as plain text