summaryrefslogtreecommitdiffstats
path: root/tests/modules/lib/terminal.py
blob: 540135dc6a152db23d79ed2224d929b2daf72587 (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
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
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)

import threading
import os

from time import sleep
from itertools import groupby
from signal import SIGKILL
from difflib import ndiff

import pexpect

from powerline.lib.unicode import u

from tests.modules.lib.vterm import VTerm, Dimensions


class MutableDimensions(object):
	def __init__(self, rows, cols):
		super(MutableDimensions, self).__init__()
		self._list = [rows, cols]

	def __getitem__(self, idx):
		return self._list[idx]

	def __setitem__(self, idx, val):
		self._list[idx] = val

	def __iter__(self):
		return iter(self._list)

	def __len__(self):
		return 2

	def __nonzero__(self):
		return True

	__bool__ = __nonzero__

	rows = property(
		fget = lambda self: self._list[0],
		fset = lambda self, val: self._list.__setitem__(0, val),
	)
	cols = property(
		fget = lambda self: self._list[1],
		fset = lambda self, val: self._list.__setitem__(1, val),
	)


class ExpectProcess(threading.Thread):
	def __init__(self, lib, dim, cmd, args, cwd=None, env=None):
		super(ExpectProcess, self).__init__()
		self.vterm = VTerm(lib, dim)
		self.lock = threading.Lock()
		self.dim = Dimensions(*dim)
		self.cmd = cmd
		self.args = args
		self.cwd = cwd
		self.env = env
		self.buffer = []
		self.child_lock = threading.Lock()
		self.shutdown_event = threading.Event()
		self.started_event = threading.Event()

	def run(self):
		with self.child_lock:
			child = pexpect.spawn(self.cmd, self.args, cwd=self.cwd,
			                      env=self.env)
			sleep(0.5)
			child.setwinsize(self.dim.rows, self.dim.cols)
			sleep(0.5)
			self.child = child
			self.started_event.set()
		status = None
		while status is None and not self.shutdown_event.is_set():
			try:
				with self.child_lock:
					s = child.read_nonblocking(size=1024, timeout=0)
					status = child.status
			except pexpect.TIMEOUT:
				pass
			except pexpect.EOF:
				break
			else:
				with self.lock:
					self.vterm.push(s)
					self.buffer.append(s)

		if status is None:
			child.kill(SIGKILL)

	def kill(self):
		self.shutdown_event.set()

	def resize(self, dim):
		with self.child_lock:
			self.dim = Dimensions(*dim)
			self.child.setwinsize(self.dim.rows, self.dim.cols)
			self.vterm.resize(self.dim)

	def __getitem__(self, position):
		with self.lock:
			return self.vterm.vtscreen[position]

	def read(self):
		with self.lock:
			ret = b''.join(self.buffer)
			del self.buffer[:]
			return ret

	def send(self, data):
		with self.child_lock:
			self.child.send(data)

	def get_highlighted_text(self, text, attrs, default_props=(),
	                         use_escapes=False):
		ret = []
		new_attrs = attrs.copy()
		for cell_properties, segment_text in text:
			if use_escapes:
				escapes = ('\033[38;2;{0};{1};{2};48;2;{3};{4};{5}'.format(
					*(cell_properties[0] + cell_properties[1]))) + (
						';1' if cell_properties[2] else ''
					) + (
						';3' if cell_properties[3] else ''
					) + (
						';4' if cell_properties[4] else ''
					) + 'm'
				ret.append(escapes + segment_text + '\033[0m')
			else:
				segment_text = segment_text.translate({'{': '{{', '}': '}}'})
				if cell_properties not in new_attrs:
					new_attrs[cell_properties] = len(new_attrs) + 1
				props_name = new_attrs[cell_properties]
				if props_name in default_props:
					ret.append(segment_text)
				else:
					ret.append('{' + str(props_name) + ':' + segment_text + '}')
		return ''.join(ret), new_attrs

	def get_row(self, row, attrs, default_props=(), use_escapes=False):
		with self.lock:
			return self.get_highlighted_text((
				(key, ''.join((cell.text for cell in subline)))
				for key, subline in groupby((
					self.vterm.vtscreen[row, col]
					for col in range(self.dim.cols)
				), lambda cell: cell.cell_properties_key)
			), attrs, default_props, use_escapes)

	def get_screen(self, attrs, default_props=(), use_escapes=False):
		lines = []
		for row in range(self.dim.rows):
			line, attrs = self.get_row(row, attrs, default_props, use_escapes)
			lines.append(line)
		return '\n'.join(lines), attrs


def test_expected_result(p, test, last_attempt, last_attempt_cb, attempts):
	debugging_tests = not not os.environ.get('_POWERLINE_DEBUGGING_TESTS')
	expected_text, attrs = test['expected_result']
	result = None
	while attempts:
		if 'row' in test:
			row = test['row']
		else:
			row = p.dim.rows - 1
			while row >= 0 and not p[row, 0].text:
				row -= 1
			if row < 0:
				row = 0
		actual_text, all_attrs = p.get_row(row, attrs)
		if actual_text == expected_text:
			return True
		attempts -= 1
		print('Actual result does not match expected for row {0}. Attempts left: {1}.'.format(
			row, attempts))
		sleep(2)
	print('Result (row {0}):'.format(row))
	print(actual_text)
	print('Expected:')
	print(expected_text)
	print('Attributes:')
	for v, k in sorted(
		((v, k) for k, v in all_attrs.items()),
		key=(lambda t: '%02u'.format(t[0]) if isinstance(t[0], int) else t[0]),
	):
		print('{k!r}: {v!r},'.format(v=v, k=k))
	print('Screen:')
	screen, screen_attrs = p.get_screen(attrs, use_escapes=debugging_tests)
	print(screen)
	print(screen_attrs)
	print('_' * 80)
	print('Diff:')
	print('=' * 80)
	print(''.join((
		u(line) for line in ndiff([actual_text + '\n'], [expected_text + '\n']))
	))
	if last_attempt and last_attempt_cb:
		last_attempt_cb()
	return False


ENV_BASE = {
	# Reasoning:
	# 1. vt* TERMs (used to be vt100 here) make tmux-1.9 use different and
	#    identical colors for inactive windows. This is not like tmux-1.6: 
	#    foreground color is different from separator color and equal to (0, 
	#    102, 153) for some reason (separator has correct color). tmux-1.8 is 
	#    fine, so are older versions (though tmux-1.6 and tmux-1.7 do not have 
	#    highlighting for previously active window) and my system tmux-1.9a.
	# 2. screen, xterm and some other non-256color terminals both have the same
	#    issue and make libvterm emit complains like `Unhandled CSI SGR 3231`.
	# 3. screen-256color, xterm-256color and other -256color terminals make
	#    libvterm emit complains about unhandled escapes to stderr.
	# 4. `st-256color` does not have any of the above problems, but it may be
	#    not present on the target system because it is installed with 
	#    x11-terms/st and not with sys-libs/ncurses.
	#
	# For the given reasons decision was made: to fix tmux-1.9 tests and not 
	# make libvterm emit any data to stderr st-256color $TERM should be used, up 
	# until libvterm has its own terminfo database entry (if it ever will). To 
	# make sure that relevant terminfo entry is present on the target system it 
	# should be distributed with powerline test package. To make distribution 
	# not require modifying anything outside of powerline test directory 
	# TERMINFO variable is set.
	#
	# This fix propagates to non-tmux vterm tests just in case.
	'TERM': 'st-256color',
	# Also $TERMINFO definition in get_env

	'POWERLINE_CONFIG_PATHS': os.path.abspath('powerline/config_files'),
	'POWERLINE_COMMAND': 'powerline-render',
	'LD_LIBRARY_PATH': os.environ.get('LD_LIBRARY_PATH', ''),
	'PYTHONPATH': os.environ.get('PYTHONPATH', ''),
}


def get_env(vterm_path, test_dir, *args, **kwargs):
	env = ENV_BASE.copy()
	env.update({
		'TERMINFO': os.path.join(test_dir, 'terminfo'),
		'PATH': vterm_path,
		'SHELL': os.path.join(vterm_path, 'bash'),
	})
	env.update(*args, **kwargs)
	return env


def do_terminal_tests(tests, cmd, dim, args, env, suite, cwd=None, fin_cb=None,
                      last_attempt_cb=None, attempts=None):
	debugging_tests = not not os.environ.get('_POWERLINE_DEBUGGING_TESTS')
	default_attempts = 2 if debugging_tests else 3
	if attempts is None:
		attempts = default_attempts
	lib = os.environ.get('POWERLINE_LIBVTERM')
	if not lib:
		if os.path.exists('tests/bot-ci/deps/libvterm/libvterm.so'):
			lib = 'tests/bot-ci/deps/libvterm/libvterm.so'
		else:
			lib = 'libvterm.so'

	while attempts:
		try:
			p = ExpectProcess(
				lib=lib,
				dim=dim,
				cmd=cmd,
				args=args,
				cwd=cwd,
				env=env,
			)
			p.start()
			p.started_event.wait()

			ret = True

			for i, test in enumerate(tests):
				with suite.test(test.get('name', 'test_{0}'.format(i)),
				                attempts - 1) as ptest:
					try:
						test_prep = test['prep_cb']
					except KeyError:
						pass
					else:
						test_prep(p)
					test_result = test_expected_result(
						p, test, attempts == 0, last_attempt_cb,
						test.get('attempts', default_attempts)
					)
					if not test_result:
						ptest.fail('Result does not match expected')
				ret = ret and test_result

			if ret:
				return ret
		finally:
			if fin_cb:
				fin_cb(p=p, cmd=cmd, env=env)
			p.kill()
			p.join(10)
			assert(not p.isAlive())

		attempts -= 1

	return False