1// Copyright 2021 The TCell Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use file except in compliance with the License.
5// You may obtain a copy of the license at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package terminfo
16
17import (
18	"bytes"
19	"testing"
20	"time"
21)
22
23// This terminfo entry is a stripped down version from
24// xterm-256color, but I've added some of my own entries.
25var testTerminfo = &Terminfo{
26	Name:      "simulation_test",
27	Columns:   80,
28	Lines:     24,
29	Colors:    256,
30	Bell:      "\a",
31	Blink:     "\x1b2ms$<20>something",
32	Reverse:   "\x1b[7m",
33	SetFg:     "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m",
34	SetBg:     "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m",
35	AltChars:  "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~",
36	Mouse:     "\x1b[M",
37	SetCursor: "\x1b[%i%p1%d;%p2%dH",
38	PadChar:   "\x00",
39}
40
41func TestTerminfoExpansion(t *testing.T) {
42
43	ti := testTerminfo
44
45	// Tests %i and basic parameter strings too
46	if ti.TGoto(7, 9) != "\x1b[10;8H" {
47		t.Error("TGoto expansion failed")
48	}
49
50	// This tests some conditionals
51	if ti.TParm("A[%p1%2.2X]B", 47) != "A[2F]B" {
52		t.Error("TParm conditionals failed")
53	}
54
55	// Color tests.
56	if ti.TParm(ti.SetFg, 7) != "\x1b[37m" {
57		t.Error("SetFg(7) failed")
58	}
59	if ti.TParm(ti.SetFg, 15) != "\x1b[97m" {
60		t.Error("SetFg(15) failed")
61	}
62	if ti.TParm(ti.SetFg, 200) != "\x1b[38;5;200m" {
63		t.Error("SetFg(200) failed")
64	}
65}
66
67func TestTerminfoDelay(t *testing.T) {
68	ti := testTerminfo
69	buf := bytes.NewBuffer(nil)
70	now := time.Now()
71	ti.TPuts(buf, ti.Blink)
72	then := time.Now()
73	s := string(buf.Bytes())
74	if s != "\x1b2mssomething" {
75		t.Errorf("Terminfo delay failed: %s", s)
76	}
77	if then.Sub(now) < time.Millisecond*20 {
78		t.Error("Too short delay")
79	}
80	if then.Sub(now) > time.Millisecond*50 {
81		t.Error("Too late delay")
82	}
83}
84
85func BenchmarkSetFgBg(b *testing.B) {
86	ti := testTerminfo
87
88	for i := 0; i < b.N; i++ {
89		ti.TParm(ti.SetFg, 100, 200)
90		ti.TParm(ti.SetBg, 100, 200)
91	}
92}
93