forked from os-autoinst/os-autoinst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testapi.pm
executable file
·2187 lines (1596 loc) · 64 KB
/
testapi.pm
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright © 2009-2013 Bernhard M. Wiedemann
# Copyright © 2012-2019 SUSE LLC
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
package testapi;
use base Exporter;
use Carp;
use Exporter;
use 5.018;
use warnings;
use File::Basename qw(basename dirname);
use File::Path 'make_path';
use Time::HiRes qw(sleep gettimeofday tv_interval);
use autotest 'query_isotovideo';
use Mojo::DOM;
require IPC::System::Simple;
use autodie ':all';
use OpenQA::Exceptions;
use OpenQA::Isotovideo::NeedleDownloader;
use Digest::MD5 'md5_base64';
use Carp qw(cluck croak);
use MIME::Base64 'decode_base64';
use Scalar::Util qw(looks_like_number reftype);
use B::Deparse;
require bmwqemu;
use constant OPENQA_LIBPATH => '/usr/share/openqa/lib';
our @EXPORT = qw($realname $username $password $serialdev %cmd %vars
get_var get_required_var check_var set_var get_var_array check_var_array autoinst_url
send_key send_key_until_needlematch type_string type_password
hold_key release_key
assert_screen check_screen assert_and_dclick save_screenshot
assert_and_click mouse_hide mouse_set mouse_click
mouse_dclick mouse_tclick match_has_tag click_lastmatch
assert_script_run script_run assert_script_sudo script_sudo
script_output validate_script_output
start_audiocapture assert_recorded_sound check_recorded_sound
select_console console reset_consoles current_console
upload_asset data_url check_shutdown assert_shutdown parse_junit_log parse_extra_log upload_logs
wait_screen_change assert_screen_change wait_still_screen assert_still_screen wait_serial
record_soft_failure record_info force_soft_failure
become_root x11_start_program ensure_installed eject_cd power
save_memory_dump save_storage_drives freeze_vm resume_vm
diag hashed_string
save_tmp_file get_test_data
);
our @EXPORT_OK = qw(is_serial_terminal);
our %cmd;
our $distri;
our $realname = "Bernhard M. Wiedemann";
our $username;
our $password;
our $serialdev;
our $last_matched_needle;
sub send_key;
sub check_screen;
sub type_string;
sub type_password;
=head1 introduction
=for stopwords os autoinst isotovideo openQA
This test API module provides methods exposed by the os-autoinst backend to be
used within tests.
Many methods define a timeout parameter which can be scaled by setting the
C<TIMEOUT_SCALE> variable in the test settings which are read by the isotovideo
process. The scale parameter can be used based on performance of workers to
prevent false positive timeouts based on differing worker performance.
os-autoinst is used in the openQA project.
+For more information on how to use openQA, please visit http://open.qa/documentation
=cut
=head1 internal
=for stopwords xen hvc0 xvc0 ipmi ttyS
=head2 init
Used for internal initialization, do not call from tests.
=cut
sub init {
if (get_var('OFW') || get_var('BACKEND', '') =~ /s390x|pvm_hmc/) {
$serialdev = "hvc0";
}
elsif (get_var('SERIALDEV')) {
$serialdev = get_var('SERIALDEV');
}
else {
$serialdev = 'ttyS0';
}
return;
}
=for stopwords ProhibitSubroutinePrototypes
=head2 set_distribution
set_distribution($distri);
Set distribution object.
You can use distribution object to implement distribution specific helpers.
=cut
sub set_distribution {
($distri) = @_;
return $distri->init();
}
=for stopwords SUT
=head1 video output handling
=head2 save_screenshot
save_screenshot;
Saves screenshot of current SUT screen.
=cut
sub save_screenshot {
return $autotest::current_test->take_screenshot;
}
=head2 record_soft_failure
=for stopwords softfail
record_soft_failure([$reason]);
Record a soft failure on the current test modules result. The result will
still be counted as a success. Use this to mark where workarounds are applied.
Takes an optional C<$reason> string which is recorded in the log file. See
C<force_soft_failure> to forcefully override a failed test module status from
a C<post_fail_hook> or C<record_info> when the status should not be
influenced.
=cut
sub record_soft_failure {
my ($reason) = @_;
bmwqemu::log_call(reason => $reason);
$autotest::current_test->record_soft_failure_result($reason);
}
sub _is_valid_result {
my ($result) = @_;
return $result =~ /^(ok|fail|softfail)$/;
}
=head2 record_info
=for stopwords softfail
record_info($title, $output [, result => $result] [, resultname => $resultname]);
Example:
record_info('workaround', "we know what we are doing");
Record a generic step result on the current test modules. This is meant for
informational purposes to be interpreted by a displaying system. For example
openQA can show a info box as part of the job results details. Use this
instead of C<record_soft_failure> for example when you do not want to mark the
job as a softfail. The optional value C<$result> can be 'ok' (default),
'fail', 'softfail'. C<$resultname> can be specified for the additional name
tag on the result file.
=cut
sub record_info {
my ($title, $output, %nargs) = @_;
$nargs{result} //= 'ok';
die 'unsupported $result \'' . $nargs{result} . '\'' unless _is_valid_result($nargs{result});
bmwqemu::log_call(title => $title, output => $output, %nargs);
$autotest::current_test->record_resultfile($title, $output, %nargs);
}
=head2 force_soft_failure
=for stopwords softfail
force_soft_failure([$reason]);
Similar to C<record_soft_failure> but can be used to override the test module
status to softfail from a C<post_fail_hook> if the module would be set to fail
otherwise. This can be used for easier tracking of known issues without
needing to handle failed tests a lot.
=cut
sub force_soft_failure {
my ($reason) = @_;
bmwqemu::log_call(reason => $reason);
$autotest::current_test->record_soft_failure_result($reason, force_status => 1);
}
sub _handle_found_needle {
my ($foundneedle, $rsp, $tags) = @_;
# convert the needle back to an object
$foundneedle->{needle} = needle->new($foundneedle->{needle});
my $img = tinycv::from_ppm(decode_base64($rsp->{image}));
my $frame = $rsp->{frame};
$autotest::current_test->record_screenmatch($img, $foundneedle, $tags, $rsp->{candidates}, $frame);
my $lastarea = $foundneedle->{area}->[-1];
bmwqemu::fctres(
sprintf("found %s, similarity %.2f @ %d/%d", $foundneedle->{needle}->{name}, $lastarea->{similarity}, $lastarea->{x} // 0, $lastarea->{y} // 0));
$last_matched_needle = $foundneedle;
return $foundneedle;
}
sub _check_backend_response {
my ($rsp, $check, $timeout, $mustmatch) = @_;
my $tags = $rsp->{tags};
if (my $foundneedle = $rsp->{found}) {
return _handle_found_needle($foundneedle, $rsp, $tags);
}
elsif ($rsp->{timeout}) {
my $method = $check ? 'check_screen' : 'assert_screen';
my $status_message = "match=" . join(',', @$tags) . " timed out after $timeout ($method)";
bmwqemu::fctres($status_message);
# add the final mismatch as 'unk' result to be able to create a new needle from it
# note: add the screenshot only if configured to pause on timeout - otherwise we would
# record each failure twice
my $failed_screens = $rsp->{failed_screens};
my $final_mismatch = $failed_screens->[-1];
if (query_isotovideo(is_configured_to_pause_on_timeout => {check => $check})) {
my $current_test = $autotest::current_test;
if ($final_mismatch) {
$autotest::current_test->record_screenfail(
img => tinycv::from_ppm(decode_base64($final_mismatch->{image})),
needles => $final_mismatch->{candidates},
tags => $tags,
result => 'unk',
frame => $final_mismatch->{frame},
);
}
else {
bmwqemu::fctwarn("ran into $method timeout but there's no final mismatch - just taking a screenshot");
$current_test->take_screenshot();
}
$current_test->save_test_result();
}
# do a special rpc call to isotovideo which will block if the test should be paused
# (if the test should not be paused this call will return 0; on resume (after pause) it will return 1)
query_isotovideo('report_timeout', {
tags => $tags,
msg => $status_message,
check => $check,
}) and return 'try_again';
if ($check) {
# only care for the last one
$failed_screens = [$final_mismatch];
}
for my $l (@$failed_screens) {
my $img = tinycv::from_ppm(decode_base64($l->{image}));
my $result = $check ? 'unk' : 'fail';
$result = 'unk' if ($l != $final_mismatch);
if ($rsp->{saveresult}) {
$autotest::current_test->record_screenfail(
img => $img,
needles => $l->{candidates},
tags => $tags,
result => $result,
frame => $l->{frame},
);
}
else {
$autotest::current_test->record_screenfail(
img => $img,
needles => $l->{candidates},
tags => $tags,
result => $result,
overall => $check ? undef : 'fail',
frame => $l->{frame},
);
}
}
# Handle case where a stall was detected: fail if this is an
# assert_screen, warn if it's a check_screen
if ($rsp->{stall}) {
if (!$check) {
record_info('Stall detected', 'Stall was detected during assert_screen fail', result => 'fail');
}
else {
bmwqemu::fctwarn("stall detected during check_screen failure!");
}
}
if (!$check && !$rsp->{saveresult}) {
# Must match can be only scalar or array ref.
my $needletags = $mustmatch;
if (ref($mustmatch) eq 'ARRAY') {
$needletags = join(', ', @$mustmatch);
}
OpenQA::Exception::FailedNeedle->throw(
error => "no candidate needle with tag(s) '$needletags' matched",
tags => $mustmatch
);
}
if ($rsp->{saveresult}) {
$autotest::current_test->save_test_result();
# now back into waiting for the backend
$rsp = myjsonrpc::read_json($autotest::isotovideo);
return unless $rsp;
$rsp = $rsp->{ret};
$rsp->{tags} = $tags;
return _check_backend_response($rsp, $check, $timeout, $mustmatch);
}
}
else {
die "unexpected response " . bmwqemu::pp($rsp);
}
return;
}
sub _check_or_assert {
my ($mustmatch, $check, %args) = @_;
die "no tags specified" if (!$mustmatch || (ref $mustmatch eq 'ARRAY' && scalar @$mustmatch == 0));
die "current_test undefined" unless $autotest::current_test;
$args{timeout} = bmwqemu::scale_timeout($args{timeout});
while (1) {
my $rsp = query_isotovideo('check_screen', {mustmatch => $mustmatch, check => $check, timeout => $args{timeout}, no_wait => $args{no_wait}});
# check backend response
# (implemented as separate function because it needs to call itself)
my $backend_response = _check_backend_response($rsp, $check, $args{timeout}, $mustmatch);
# return the response unless we should try again after resuming from paused state
return $backend_response if (!$backend_response || $backend_response ne 'try_again');
# download new needles
OpenQA::Isotovideo::NeedleDownloader->new()->download_missing_needles($rsp->{new_needles} // []);
# reload needles before trying again
query_isotovideo('backend_reload_needles', {});
}
}
=head2 assert_screen
assert_screen($mustmatch [, [$timeout] | [timeout => $timeout]] [, no_wait => $no_wait]);
Wait for needle with tag C<$mustmatch> to appear on SUT screen. C<$mustmatch>
can be string or C<ARRAYREF> of string (C<['tag1', 'tag2']>). The maximum
waiting time is defined by C<$timeout>. It is recommended to use a value lower
than the default timeout only when explicitly needed. C<assert_screen> is not
very suitable for checking performance expectations. Under the normal
circumstance of the screen being shown this does not imply a longer waiting
time as the method returns as soon as a successful needle match occurred.
Specify C<$no_wait> to run the screen check as fast as possible that is
possibly more than once per second which is default. Select this to check a
screen which can change in a range faster than 1-2 seconds not to miss the
screen to check for.
Returns matched needle or throws C<FailedNeedle> exception if $timeout timeout
is hit. Default timeout is 30s.
=cut
sub assert_screen {
my ($mustmatch) = shift;
my $timeout;
$timeout = shift if (@_ % 2);
my %args = (timeout => $timeout // $bmwqemu::default_timeout, @_);
bmwqemu::log_call(mustmatch => $mustmatch, %args);
return _check_or_assert($mustmatch, 0, %args);
}
=head2 check_screen
check_screen($mustmatch [, [$timeout] | [timeout => $timeout]] [, no_wait => $no_wait]);
Similar to C<assert_screen> but does not throw exceptions. Use this for optional matches.
Check C<assert_screen> for parameters.
Unlike C<assert_screen> it is recommended to use the lowest possible timeout
to prevent needless waiting time in case no match is expected behaviour. In
general a value of 0s for the timeout should suffice, that is only checking
once with no waiting time. In most cases a check_screen with a higher timeout
can be replaced by C<assert_screen> with multiple tags using an C<ARRAYREF> in
combination with C<match_has_tag> or another synchronization call in before,
for example C<wait_screen_change> or C<wait_still_screen>.
Returns matched needle or C<undef> if timeout is hit. Default timeout is 0s.
=cut
sub check_screen {
my ($mustmatch) = shift;
my $timeout;
$timeout = shift if (@_ % 2);
my %args = (timeout => $timeout // 0, @_);
bmwqemu::log_call(mustmatch => $mustmatch, %args);
return _check_or_assert($mustmatch, 1, %args);
}
=head2 match_has_tag
match_has_tag($tag);
Returns true (1) if last matched needle has C<$tag>, false (0) if last
matched needle does not have C<$tag>, and C<undef> if no needle has yet
been matched at the time of the call.
=cut
sub match_has_tag {
my ($tag) = @_;
if ($last_matched_needle) {
return $last_matched_needle->{needle}->has_tag($tag);
}
return;
}
=head2 assert_and_click
assert_and_click($mustmatch [, timeout => $timeout] [, button => $button] [, clicktime => $clicktime ] [, dclick => 1 ] [, mousehide => 1 ]);
Wait for needle with C<$mustmatch> tag to appear on SUT screen. Then click
C<$button> at the "click_point" position as defined in the needle JSON file,
or - if the JSON has not explicit "click_point" - in the middle of the last
needle area. If C<$dclick> is set, do double click instead. C<$mustmatch> can
be string or C<ARRAYREF> of strings (C<['tag1', 'tag2']>). C<$button> is by
default C<'left'>. C<'left'> and C<'right'> is supported. If C<$mousehide> is
true then always move mouse to the 'hidden' position after clicking to prevent
to hide the area where user wants to assert/click in second step.
Throws C<FailedNeedle> exception if C<$timeout> timeout is hit. Default timeout is 30s.
=cut
sub assert_and_click {
my ($mustmatch, %args) = @_;
$args{timeout} //= $bmwqemu::default_timeout;
$last_matched_needle = assert_screen($mustmatch, $args{timeout});
bmwqemu::log_call(mustmatch => $mustmatch, %args);
my %click_args = map { $_ => $args{$_} } qw(button dclick mousehide);
return click_lastmatch(%click_args);
}
=head2 click_lastmatch
click_lastmatch([, button => $button] [, clicktime => $clicktime ] [, dclick => 1 ] [, mousehide => 1 ]);
Click C<$button> at the "click_point" position as defined in the needle JSON file
of the last matched needle, or - if the JSON has not explicit "click_point" -
in the middle of the last match area. If C<$dclick> is set, do double click
instead. Supported values for C<$button> are C<'left'> and C<'right'>, C<'left'>
is the default. If C<$mousehide> is true then always move mouse to the 'hidden'
position after clicking to prevent to disturb the area where user wants to
assert/click in second step, otherwise move the mouse back to its previous
position.
=cut
sub click_lastmatch {
my %args = @_;
$args{button} //= 'left';
$args{dclick} //= 0;
$args{mousehide} //= 0;
return unless $last_matched_needle;
my $old_mouse_coords = query_isotovideo('backend_get_last_mouse_set');
# determine click coordinates from the last area which has those explicitly specified
my $relevant_area;
my $relative_click_point;
for my $area (reverse @{$last_matched_needle->{area}}) {
next unless ($relative_click_point = $area->{click_point});
$relevant_area = $area;
last;
}
# use center of the last area if no area contains click coordinates
if (!$relevant_area) {
$relevant_area = $last_matched_needle->{area}->[-1];
}
if (!$relative_click_point || $relative_click_point eq 'center') {
$relative_click_point = {
xpos => $relevant_area->{w} / 2,
ypos => $relevant_area->{h} / 2,
};
}
# calculate absolute click position and click
my $x = int($relevant_area->{x} + $relative_click_point->{xpos});
my $y = int($relevant_area->{y} + $relative_click_point->{ypos});
bmwqemu::diag("clicking at $x/$y");
mouse_set($x, $y);
if ($args{dclick}) {
mouse_dclick($args{button}, $args{clicktime});
}
else {
mouse_click($args{button}, $args{clicktime});
}
# move mouse back to where it was before we clicked, or to the 'hidden' position if it had never been
# positioned
# note: We can not move the mouse instantly. Otherwise we might end up in a click-and-drag situation.
sleep 1;
if ($old_mouse_coords->{x} > -1 && $old_mouse_coords->{y} > -1 && !$args{mousehide}) {
return mouse_set($old_mouse_coords->{x}, $old_mouse_coords->{y});
}
else {
return mouse_hide();
}
}
=head2 assert_and_dclick
assert_and_dclick($mustmatch [, timeout => $timeout] [, button => $button] [, clicktime => $clicktime ] [, dclick => 1 ] [, mousehide => 1 ]);
Alias for C<assert_and_click> with C<$dclick> set.
=cut
sub assert_and_dclick {
my ($mustmatch, %args) = @_;
$args{dclick} = 1;
return assert_and_click($mustmatch, %args);
}
=head2 wait_screen_change
wait_screen_change(CODEREF [,$timeout [, similarity_level => 50]]);
Wrapper around code that is supposed to change the screen. This is the
opposite to C<wait_still_screen>. Make sure to put the commands to change the
screen within the block to avoid races between the action and the screen
change. C<wait_screen_change> waits for a screen change after C<CODEREF> was
executed.
Example:
wait_screen_change {
send_key 'esc';
};
Notice: If you use the second parameter, you could get the following warning
Useless use of private variable in void context
To avoid it, use parentheses for the function call and the reserved word 'sub' for the callback
subroutine block.
wait_screen_change(sub {
send_key 'esc';
}, 15);
Returns true if screen changed or false on timeout. Default timeout is 10s. Default
similarity_level is 50.
=cut
sub wait_screen_change(&@) {
my ($callback, $timeout, %args) = @_;
$timeout ||= 10;
$args{similarity_level} //= 50;
bmwqemu::log_call(timeout => $timeout, %args);
$timeout = bmwqemu::scale_timeout($timeout);
# get the initial screen
query_isotovideo('backend_set_reference_screenshot');
$callback->() if $callback;
my $starttime = time;
while (time - $starttime < $timeout) {
my $sim = query_isotovideo('backend_similiarity_to_reference')->{sim};
bmwqemu::diag("waiting for screen change: " . (time - $starttime) . " $sim");
if ($sim < $args{similarity_level}) {
bmwqemu::fctres("screen change seen at " . (time - $starttime));
return 1;
}
sleep(0.5);
}
save_screenshot;
bmwqemu::fctres("timed out");
return 0;
}
=head2 assert_screen_change
assert_screen_change(CODEREF [,$timeout]);
Run C<CODEREF> with C<wait_screen_change> but C<die> if screen did not change
within timeout. Look into C<wait_screen_change> for details.
Example:
assert_screen_change { send_key 'alt-f4' };
=cut
sub assert_screen_change(&@) {
# Need to parse code reference and pass to the method explicitly as
# wait_screen_change uses prototype which expects code block as an argument
# This resolves compile time issues
my ($coderef, @args) = @_;
wait_screen_change(\&{$coderef}, @_) or die 'assert_screen_change failed to detect a screen change';
}
=head2 wait_still_screen
=for stopwords stilltime
wait_still_screen([$stilltime | [stilltime => $stilltime]] [, $timeout] | [timeout => $timeout]] [, similarity_level => $similarity_level] [, no_wait => $no_wait]);
Wait until the screen stops changing.
See C<assert_screen> for C<$no_wait>.
Returns true if screen is not changed for given C<$stilltime> (in seconds) or undef on timeout.
Default timeout is 30s, default stilltime is 7s.
=cut
sub wait_still_screen {
my $stilltime = looks_like_number($_[0]) ? shift : 7;
my $timeout = (@_ % 2) ? shift : $bmwqemu::default_timeout;
my %args = (stilltime => $stilltime, timeout => $timeout, @_);
$args{similarity_level} //= 47;
bmwqemu::log_call(%args);
$timeout = bmwqemu::scale_timeout($args{timeout});
$stilltime = $args{stilltime};
if ($timeout < $stilltime) {
bmwqemu::fctwarn("Selected timeout \'$timeout\' below stilltime \'$stilltime\', returning with false");
return 0;
}
my $starttime = time;
my $lastchangetime = [gettimeofday];
query_isotovideo('backend_set_reference_screenshot');
my $sim = 0;
while (time - $starttime < $timeout) {
$sim = query_isotovideo('backend_similiarity_to_reference')->{sim};
my $now = [gettimeofday];
if ($sim < $args{similarity_level}) {
# a change
$lastchangetime = $now;
query_isotovideo('backend_set_reference_screenshot');
}
if (($now->[0] - $lastchangetime->[0]) + ($now->[1] - $lastchangetime->[1]) / 1000000. >= $stilltime) {
bmwqemu::fctres("detected same image for $stilltime seconds, last detected similarity is $sim");
return 1;
}
# with 'no_wait' actually wait a little bit not to waste too much CPU
# corresponding to what check_screen/assert_screen also does
# internally
sleep($args{no_wait} ? 0.01 : 0.5);
}
$autotest::current_test->timeout_screenshot();
bmwqemu::fctres("wait_still_screen timed out after $timeout, last detected similarity is $sim");
return 0;
}
=head2 assert_still_screen
assert_still_screen([$args...])
Run C<wait_still_screen> but C<die> if screen changed within timeout. Look
into C<wait_still_screen> for details.
=cut
sub assert_still_screen(@) {
wait_still_screen(@_) or die 'assert_still_screen failed to detect a still screen';
}
=head1 test variable access
=head2 get_var
get_var($variable [, $default ])
Returns content of test variable C<$variable> or the C<$default> given as second argument or C<undef>
=cut
sub get_var {
my ($var, $default) = @_;
return $bmwqemu::vars{$var} // $default;
}
=head2 get_required_var
get_required_var($variable)
Similar to C<get_var> but without default value and throws exception if variable can not be retrieved.
=cut
sub get_required_var {
my ($var) = @_;
return $bmwqemu::vars{$var} // croak "Could not retrieve required variable $var";
}
=head2 set_var
set_var($variable, $value [, reload_needles => 1] );
Set test variable C<$variable> to value C<$value>.
Variables starting with C<_SECRET_> will not appear in the C<vars.json> file.
Specify a true value for the C<reload_needles> flag to trigger a reloading
of needles in the backend and call the cleanup handler with the new variables
to make sure that possibly deselected needles are now taken into account
(useful if you change scenarios during the test run)
=cut
sub set_var {
my ($var, $val, %args) = @_;
$bmwqemu::vars{$var} = $val;
if ($args{reload_needles}) {
bmwqemu::save_vars();
query_isotovideo('backend_reload_needles', {});
}
return;
}
=head2 check_var
check_var($variable, $value);
Returns true if test variable C<$variable> is equal to C<$value> or returns C<undef>.
=cut
sub check_var {
my ($var, $val) = @_;
return 1 if (defined $bmwqemu::vars{$var} && $bmwqemu::vars{$var} eq $val);
return 0;
}
=head2 get_var_array
get_var_array($variable [, $default ]);
Return the given variable as array reference (split variable value by , | or ; )
=cut
sub get_var_array {
my ($var, $default) = @_;
my @vars = split(/,|;/, $bmwqemu::vars{$var} || '');
my @default = split(/,|;/, $default || '');
return \@default if !@vars;
return \@vars;
}
=head2 check_var_array
check_var_array($variable, $value);
Boolean function to check if a value list contains a value
=cut
sub check_var_array {
my ($var, $val) = @_;
my $vars_r = get_var_array($var);
return grep { $_ eq $val } @$vars_r;
}
=head1 script execution helpers
=for stopwords os-autoinst autoinst isotovideo VNC
=head2 is_serial_terminal
is_serial_terminal;
Determines if communication with the guest is being performed purely over a
serial port. When true, the guest should have a tty attached to a serial port
and os-autoinst sends commands to it as text. This differs from when a text
console is selected in the guest, but VNC is being used to simulate key presses.
When a serial terminal is selected you will not be able to use functions which
rely on needles. This sub is not exported by default as most tests I<will not
benefit> from changing their behaviour depending on if communication happens
over serial or VNC.
For more info see consoles/virtio_console.pm and consoles/serial_screen.pm.
=cut
sub is_serial_terminal {
state $ret;
state $last_seen = '';
if (defined current_console() && current_console() ne $last_seen) {
$last_seen = current_console();
$ret = query_isotovideo('backend_is_serial_terminal', {});
}
return $ret->{yesorno};
}
=head2 wait_serial
wait_serial($regex or ARRAYREF of $regexes, [, timeout => $timeout] [, expect_not_found => $expect_not_found] [, %args]);
Deprecated mode
wait_serial($regex or ARRAYREF of $regexes [, $timeout [, $expect_not_found [, @args ]]]);
Wait for C<$regex> or anyone of C<$regexes> to appear on serial output.
Setting C<$no_regex> will cause it to do a plain string search.
Set C<$quiet>, to avoid recording serial_result.
For serial_terminal there are more options available, like C<record_output>,
C<buffer_size>. See C<consoles::serial_screen::read_unitl> for details.
Returns the string matched or C<undef> if C<$expect_not_found> is false
(default).
Returns C<undef> or (after timeout) the string that I<did _not_ match> if
C<$expect_not_found> is true. The default timeout is 90 seconds.
=cut
sub wait_serial {
my $regexp = shift;
my %args = compat_args(
{
regexp => $regexp,
timeout => 90,
expect_not_found => 0,
quiet => undef,
no_regex => 0,
buffer_size => undef,
record_output => undef,
}, ['timeout', 'expect_not_found'], @_);
bmwqemu::log_call(%args);
$args{timeout} = bmwqemu::scale_timeout($args{timeout});
my $ret = query_isotovideo('backend_wait_serial', \%args);
my $matched = $ret->{matched};
if ($args{expect_not_found}) {
$matched = !$matched;
}
bmwqemu::wait_for_one_more_screenshot() unless is_serial_terminal;
# to string, we need to feed string of result to
# record_serialresult()
$matched = $matched ? 'ok' : 'fail';
# convert dos2unix (poo#20542)
$ret->{string} =~ s,\r\n,\n,g;
$autotest::current_test->record_serialresult(bmwqemu::pp($regexp), $matched, $ret->{string}) unless ($args{quiet});
bmwqemu::fctres("$regexp: $matched");
return $ret->{string} if ($matched eq "ok");
return; # false
}
=head2 x11_start_program
x11_start_program($program[, @args]);
Start C<$program> in graphical desktop environment.
I<The implementation is distribution specific and not always available.>
=cut
sub x11_start_program {
my ($program, @args) = @_;
bmwqemu::log_call(program => $program, @args);
return $distri->x11_start_program($program, @args);
}
sub _handle_script_run_ret {
my ($ret, $cmd, %args) = @_;
croak "command '$cmd' timed out" unless (defined $ret);
my $die_msg = "command '$cmd' failed";
$die_msg .= ": $args{fail_message}" if $args{fail_message};
croak $die_msg unless ($ret == 0);
}
=head2 assert_script_run
assert_script_run($cmd [, timeout => $timeout] [, fail_message => $fail_message] [,quiet => $quiet]);
Deprecated mode
assert_script_run($cmd [, $timeout [, $fail_message]]);
Run C<$cmd> via C<$distri->script_run> and C<die> unless it returns zero (indicating
successful completion of C<$cmd>). Default timeout is 90 seconds.
Use C<script_run> instead if C<$cmd> may fail.
C<$fail_message> is returned in the die message if specified.
I<The C<script_run> implementation is distribution specific and not always available.
For this to work correctly, it must return 0 if and only if C<$command> completes
successfully. It must NOT return 0 if C<$command> times out. The default implementation
should work on *nix operating systems with a configured serial device.>
=cut
sub assert_script_run {
my $cmd = shift;
my %args = compat_args(
{
# assert_script_run originally had the implicit default timeout of
# wait_serial which we are repeating here to preserve old behaviour and
# not change default timeout.
timeout => 90,
fail_message => '',
quiet => testapi::get_var('_QUIET_SCRIPT_CALLS')
}, ['timeout', 'fail_message'], @_);
bmwqemu::log_call(cmd => $cmd, %args);
my $ret = $distri->script_run($cmd, timeout => $args{timeout}, quiet => $args{quiet});
_handle_script_run_ret($ret, $cmd, %args);
return;
}
=head2 script_run
script_run($cmd [, timeout => $timeout] [, output => ''] [, quiet => $quiet]);
Deprecated mode
script_run($cmd [, $timeout]);
Run C<$cmd> (in the default implementation, by assuming the console prompt and typing
the command). If C<$timeout> is greater than 0, wait for that length of time for
execution to complete (otherwise, returns undef immediately). See C<distri->script_run>
for default timeout.
C<$output> can be used as an explanatory text that will be displayed with the execution of
the command.
<Returns> exit code received from I<$cmd>, or undef if $timeout is 0 or execution
does not complete within $timeout.