-
Notifications
You must be signed in to change notification settings - Fork 145
/
TestUtils.pm
1192 lines (1073 loc) · 42.7 KB
/
TestUtils.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
package TestUtils;
use warnings;
use strict;
use utf8;
#########################
# Test Utils
#########################
BEGIN {
$ENV{'THRUK_MODE'} = 'TEST';
$ENV{'THRUK_TEST_NO_AUDIT_LOG'} = 1;
$ENV{'PLACK_TEST_EXTERNALSERVER_URI'} =~ s#/$##gmx if $ENV{'PLACK_TEST_EXTERNALSERVER_URI'};
binmode(STDOUT, ":encoding(UTF-8)");
binmode(STDERR, ":encoding(UTF-8)");
}
###################################################
use lib 'lib';
use Carp qw/confess/;
use Cpanel::JSON::XS qw/encode_json decode_json/;
use Data::Dumper;
use File::Temp qw/tempfile/;
use HTTP::Cookies::Netscape;
use HTTP::Request ();
use HTTP::Request::Common 6.12 qw/GET POST/;
use Plack::Test;
use Test::More;
use Time::HiRes qw/sleep/;
use URI::Escape qw/uri_unescape/;
use Thruk ();
use Thruk::UserAgent ();
use Thruk::Utils::Encode ();
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(request ctx_request);
our @EXPORT_OK = qw(request ctx_request);
my $use_html_lint;
my $lint;
my $test_token = "";
my $has_curl = 0; # does require newer curl, disabling for now (2020-06-09) # has_util("curl");
our $placktest;
#########################
sub has_util {
my($util) = @_;
for my $path (split/:/mx, $ENV{'PATH'}) {
return(1) if -x $path.'/'.$util;
}
return(0);
}
#########################
sub request {
my($url) = @_;
my($req, $res);
if(!$placktest) {
$placktest = Plack::Test->create(Thruk->startup);
}
if(ref $url eq "") {
$res = $placktest->request(GET $url);
} else {
$res = $placktest->request($url);
}
return($res);
}
#########################
sub clear {
undef $placktest;
undef $Thruk::thruk;
}
#########################
sub ctx_request {
my($url) = @_;
local $ENV{'THRUK_KEEP_CONTEXT'} = 1;
$Thruk::Globals::c = undef;
my $res = request($url);
my $c = $Thruk::Globals::c;
return($res, $c);
}
#########################
sub get_test_servicegroup {
my $request = _request('/thruk/r/servicegroups?columns=name&limit=1');
ok( $request->is_success, 'get_test_servicegroup() request succeeded' ) or diag(Dumper($request));
my $data = decode_json($request->decoded_content || $request->content);
my $name = $data->[0]->{'name'};
isnt($name, undef, "got a servicegroup from the rest api") or bail_out_req('got no test object, cannot test.', $request);
return($name);
}
#########################
sub get_test_hostgroup {
my $request = _request('/thruk/r/hostgroups?columns=name&limit=1');
ok( $request->is_success, 'get_test_hostgroup() request succeeded' ) or diag(Dumper($request));
my $data = decode_json($request->decoded_content || $request->content);
my $name = $data->[0]->{'name'};
isnt($name, undef, "got a hostgroup from the rest api") or bail_out_req('got no test object, cannot test.', $request);
return($name);
}
#########################
sub get_test_user {
our $remote_user_cache;
return $remote_user_cache if $remote_user_cache;
my $request = _request('/thruk/r/thruk/whoami?columns=id');
ok( $request->is_success, 'get_test_user() request succeeded' ) or diag(Dumper($request));
my $data = decode_json($request->decoded_content || $request->content);
my $name = $data->{'id'};
isnt($name, undef, "got a user from the rest api") or bail_out_req('got no test object, cannot test.', $request);
$remote_user_cache = $name;
return($name);
}
#########################
sub get_current_user_token {
our $remote_user_token;
return $remote_user_token if $remote_user_token;
my $request = _request('/thruk/cgi-bin/user.cgi');
ok( $request->is_success, 'get_current_user_token() request succeeded' ) or diag(Dumper($request));
my $page = $request->content;
my $token;
if($page =~ m/name="CSRFtoken"\s+value="([^"]+)"/mxo) {
$token = $1;
}
isnt($token, undef, "got a token from user.cgi") or bail_out_req('got no token, cannot test.', $request);
$remote_user_token = $token;
return($token);
}
#########################
sub get_test_service {
my $backend = shift;
my $request = _request('/thruk/r/services?columns=host_name,description&limit=1'.(defined $backend ? '&backend='.$backend : ''));
ok( $request->is_success, 'get_test_service() request succeeded' ) or diag(Dumper($request));
my $data = decode_json($request->decoded_content || $request->content);
my $host = $data->[0]->{'host_name'};
my $service = $data->[0]->{'description'};
isnt($host, undef, "got a host from the rest api") or bail_out_req('got no test host, cannot test.', $request);
isnt($service, undef, "got a service from the rest api") or bail_out_req('got no test service, cannot test.', $request);
return($host, $service);
}
#########################
sub get_test_timeperiod {
my $request = _request('/thruk/r/timeperiods?columns=name&limit=1');
ok( $request->is_success, 'get_test_timeperiod() request succeeded' ) or diag(Dumper($request));
my $data = decode_json($request->decoded_content || $request->content);
my $name = $data->[0]->{'name'};
isnt($name, undef, "got a timeperiod from the rest api") or bail_out_req('got no test object, cannot test.', $request);
return($name);
}
#########################
sub get_test_host_cli {
my($binary) = @_;
my $auth = '';
if(!$ENV{'PLACK_TEST_EXTERNALSERVER_URI'}) {
my $user = Thruk->config->{'default_user_name'};
$auth = ' -A "'.$user.'"' if($user and $user ne 'thrukadmin');
}
my $test = { cmd => $binary.' -a listhosts'.$auth };
test_command($test);
my $host = (split(/\n/mx, $test->{'stdout'}))[0];
isnt($host, undef, 'got test hosts') or BAIL_OUT($0.": need test host:\n".Dumper($test));
return $host;
}
#########################
sub get_test_hostgroup_cli {
my($binary) = @_;
my $auth = '';
if(!$ENV{'PLACK_TEST_EXTERNALSERVER_URI'}) {
my $user = Thruk->config->{'default_user_name'};
$auth = ' -A "'.$user.'"' if($user and $user ne 'thrukadmin');
}
my $test = { cmd => $binary.' -a listhostgroups'.$auth };
test_command($test);
my @groups = split(/\n/mx, $test->{'stdout'});
my $hostgroup;
for my $group (@groups) {
my($name, $members) = split/\s+/, $group, 2;
next unless $members;
$hostgroup = $name;
}
isnt($hostgroup, undef, 'got test hostgroup') or BAIL_OUT($0.": need test hostgroup");
return $hostgroup;
}
#########################
=head2 test_page
check a page
needs test hash
{
url => url to test
post => do post request with this data
method => http method, default is GET
follow => follow redirects
fail => request should fail
code => expect this response code
redirect => request should redirect
location => redirect location
fail_message_ok => page can contain error message without failing
like => (list of) regular expressions which have to match page content
unlike => (list of) regular expressions which must not match page content
content_type => match this content type
skip_html_lint => skip html lint check
skip_doctype => skip doctype check, even if its an html page
skip_js_check => skip js comma check
sleep => sleep this amount of seconds after the request
waitfor => wait till regex occurs (max 300sec or waitmax)
waitmax => wait this amount of seconds
agent => user agent for requests
callback => content callback
}
=cut
sub test_page {
my(%opts) = @_;
my $return = {};
my $waitmax = $opts{'waitmax'} // 300;
my $start = time();
my $opts = _set_test_page_defaults(\%opts);
if($opts->{'post'}) {
if(ref $opts->{'post'} eq 'REF') {
$opts->{'post'} = ${$opts->{'post'}};
}
$opts->{'method'} = 'POST' unless $opts->{'method'};
$opts->{'method'} = uc($opts->{'method'});
local $Data::Dumper::Indent = 0;
local $Data::Dumper::Varname = $opts->{'method'};
ok($opts->{'url'}, $opts->{'method'}.' '.Thruk::Utils::Encode::encode_utf8($opts->{'url'}).' '.Dumper($opts->{'post'}));
} else {
$opts->{'method'} = 'GET' unless $opts->{'method'};
$opts->{'method'} = uc($opts->{'method'});
ok($opts->{'url'}, $opts->{'method'}.' '.Thruk::Utils::Encode::encode_utf8($opts->{'url'}));
}
my $request = _request($opts->{'url'}, $opts->{'startup_to_url'}, $opts->{'post'}, $opts->{'agent'}, $opts->{'method'});
if(defined $opts->{'follow'}) {
my $redirects = 0;
while(my $location = $request->{'_headers'}->{'location'}) {
if($location !~ m/^(http|\/)/gmxo) { $location = _relative_url($location, $request->base()->as_string()); }
$request = _request($location, undef, undef, $opts->{'agent'});
$redirects++;
last if $redirects > 10;
}
ok( $redirects < 10, 'Redirect succeed after '.$redirects.' hops' ) or bail_out_req('too many redirects', $request, 1);
}
my $cleaned_content = $request->content;
$cleaned_content =~ s/<script.*?<\/script>//sgmx;
if($cleaned_content =~ m/<span\ class="fail_message">(.*?)<\/span>/msxo) {
my $msg = $1;
fail('Request '.$opts->{'url'}.' had error message: '.$msg) unless $opts->{'fail_message_ok'};
fail('Request '.$opts->{'url'}.' error message contains escaped html: '.$msg) if $msg =~ m/<.*>/mx;
}
# wait for something?
$return->{'content'} = $request->decoded_content || $request->content;
if(defined $opts->{'waitfor'}) {
my $now = time();
my $waitfor = $opts->{'waitfor'};
my $found = 0;
my $end = $start + $waitmax;
ok(1, "waiting for $waitfor to appear till ".(scalar localtime $end));
while($now < $end) {
# text that shouldn't appear
if(defined $opts->{'unlike'}) {
for my $unlike (@{_list($opts->{'unlike'})}) {
if($return->{'content'} =~ m/$unlike/mx) {
fail("Content should not contain: ".(defined $1 ? $1 : $unlike)) or diag($opts->{'url'});
return $return;
}
}
}
if($return->{'content'} =~ $waitfor) {
ok(1, "content ".$waitfor." found after ".($now - $start)."seconds");
$found = 1;
last;
}
if($request->is_redirect && $request->{'_headers'}->{'location'} =~ m/cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
# is it a background job page?
my $location = $request->{'_headers'}->{'location'};
wait_for_job($location);
$request = _request($location, undef, undef, $opts->{'agent'});
$return->{'content'} = $request->content;
if($request->is_error) {
fail('Request '.$location.' should succeed. Original url: '.$opts->{'url'});
bail_out_req('request failed', $request, 1);
}
if($request->is_redirect && $request->{'_headers'}->{'location'} =~ m/cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
fail('Request '.$location.' should not redirect to job page again. Original url: '.$opts->{'url'});
bail_out_req('request failed', $request, 1);
}
} else {
sleep(0.3);
$now = time();
$request = _request($opts->{'url'}, $opts->{'startup_to_url'}, $opts->{'post'}, $opts->{'agent'}, $opts->{'method'});
$return->{'content'} = $request->content;
}
}
if(!$found) {
fail("content did not match $waitfor within $waitmax seconds") or diag($opts->{'url'});
} else {
# text that should appear
if(defined $opts->{'like'}) {
for my $like (@{_list($opts->{'like'})}) {
my $regex = ref $like ? $like : qr/$like/;
like($return->{'content'}, $regex, "Content should contain: ".Thruk::Utils::Encode::encode_utf8($like)) or diag($opts->{'url'});
}
}
}
return $return;
}
my($job_location, $job_id);
# job redirect
if($request->is_redirect && $request->{'_headers'}->{'location'} =~ m/cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
$job_id = $1;
$job_location = $request->{'_headers'}->{'location'};
}
# job page?
elsif(defined $return->{'content'} && $return->{'content'} =~ m/cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
$job_id = $1;
$job_location = "/thruk/cgi-bin/job.cgi?job=".$job_id;
}
# follow job
if($job_id) {
wait_for_job($job_location);
$request = _request($job_location, undef, undef, $opts->{'agent'});
$return->{'content'} = $request->content;
if($request->is_error) {
fail('Request '.$job_location.' should succeed. Original url: '.$opts->{'url'});
bail_out_req('request failed', $request, 1);
}
}
if(defined $opts->{'code'}) {
is($request->code, $opts->{'code'}, 'Request '.$opts->{'url'}.' returns code: '.$opts->{'code'} );
}
elsif(defined $opts->{'fail'}) {
ok( $request->is_error, 'Request '.$opts->{'url'}.' should fail' );
}
elsif(defined $opts->{'redirect'}) {
ok( $request->is_redirect, 'Request '.$opts->{'url'}.' should redirect' ) or diag(Dumper($opts, $request));
if(defined $opts->{'location'}) {
if(defined $request->{'_headers'}->{'location'}) {
like($request->{'_headers'}->{'location'}, qr/$opts->{'location'}/, "Content should redirect: ".$opts->{'location'});
} else {
fail('no redirect header found');
}
}
}
else {
ok( $request->is_success, 'Request '.Thruk::Utils::Encode::encode_utf8($opts->{'url'}).' should succeed' ) or bail_out_req('request failed', $request, 1);
}
# text that should appear
if(defined $opts->{'like'}) {
for my $like (@{_list($opts->{'like'})}) {
use Carp;
my $regex = ref $like ? $like : qr/$like/;
like($return->{'content'}, $regex, "Content should contain: ".Thruk::Utils::Encode::encode_utf8($regex)) || die("failed in ".Carp::longmess($opts->{'url'})."\nRequest:\n".$request->request->as_string()); # diag($opts->{'url'});
}
}
# text that shouldn't appear
if(defined $opts->{'unlike'}) {
for my $unlike (@{_list($opts->{'unlike'})}) {
unlike($return->{'content'}, qr/$unlike/, "Content should not contain: ".$unlike) or diag($opts->{'url'});
}
}
# test the content type
$return->{'content_type'} = $request->header('content-type');
my $content_type = $request->header('content-type') || '';
if(defined $opts->{'content_type'}) {
is($return->{'content_type'}, $opts->{'content_type'}, 'Content-Type should be: '.$opts->{'content_type'}) or diag($opts->{'url'});
}
# memory usage
SKIP: {
skip "skipped memory check", 1 if $ENV{'TEST_SKIP_MEMORY'};
require Thruk::Backend::Pool;
my $rsize = Thruk::Utils::IO::get_memory_usage($$);
ok($rsize < 1024, 'resident size ('.$rsize.'MB) higher than 1024MB on '.Thruk::Utils::Encode::encode_utf8($opts->{'url'}));
}
# html valitidy
if(!defined $opts->{'skip_doctype'} or $opts->{'skip_doctype'} == 0) {
if($content_type =~ 'text\/html' and !$request->is_redirect) {
like($return->{'content'}, '/<html[^>]*>/i', 'html page has html section');
like($return->{'content'}, '/<!doctype/i', 'html page has doctype');
}
}
if($content_type =~ m|text/html| && !defined $return->{'content_type'}) {
# test without having to change the test number in all tests
fail("Content-Type should contain charset=utf-8") unless $content_type =~ m/\;\s*charset=utf\-8/mx;
}
if($content_type =~ m|application/json|) {
# test without having to change the test number in all tests
fail("Content-Type should contain charset=utf-8") unless $content_type =~ m/\;\s*charset=utf\-8/mx;
}
my $is_length = length($request->content);
my $got_length = $request->header('content-length');
if($got_length && $is_length != $got_length) {
fail("Content-Length did not match, $is_length != $got_length");
}
if(!$got_length && ($content_type =~ m|text/html| || $content_type =~ m|application/json|)) {
fail("no Content-Length set");
}
SKIP: {
if($content_type =~ m|text/html| and (!defined $opts->{'skip_html_lint'} or $opts->{'skip_html_lint'} == 0)) {
if(!defined $use_html_lint) {
# load lint on first use
$use_html_lint = 0;
eval {
require HTML::Lint;
$use_html_lint = 1;
$lint = HTML::Lint->new();
};
}
if($use_html_lint == 0) {
skip "no HTML::Lint installed", 1;
}
$lint->newfile($opts->{'url'});
# will result in "Parsing of undecoded UTF-8 will give garbage when decoding entities..." otherwise
my $content = $return->{'content'};
utf8::decode($content);
$lint->parse($content);
$lint->eof();
my @errors = $lint->errors;
@errors = diag_lint_errors_and_remove_some_exceptions($lint, $content);
is(scalar @errors, 0, "No errors found in HTML");
$lint->clear_errors();
my $html_only_content = $return->{'content'};
$html_only_content =~ s/<script[^>]*>.+?<\/script>//gsmxio;
my $matches = get_matches_with_meta($html_only_content, qr/^(.*\&amp.*)$/mx);
for my $m (@{$matches}) {
next if $m->{'match'} =~ m/abbr=/mx;
fail(sprintf("page contains double html escaped amps in line %d: %s", $m->{'line'}, $m->{'match'}));
}
}
}
# check for missing images / css or js
if($content_type =~ 'text\/html') {
my $content = $return->{'content'};
# check for failed javascript lists
verify_html_js($content) unless $opts->{'skip_js_check'};
# remove script tags without a src
$content =~ s/<script(?!([^>]*src=[^>]*))[^>]*>.+?<\/script>//gsmxio;
my @matches1 = $content =~ m/<(?:[^>]+)\s+(src|href)='(.+?)'/gio;
my @matches2 = $content =~ m/<(?:[^>]+)\s+(src|href)="(.+?)"/gio;
my $links_to_check;
my $x=0;
for my $match (@matches1, @matches2) {
$x++;
next if $x%2==1;
next if $match =~ m/^http/mxo;
next if $match =~ m/^ssh/mxo;
next if $match =~ m/^mailto:/mxo;
next if $match =~ m/^(\#|'|")/mxo;
next if $match =~ m/\/thruk\/cgi\-bin/mxo;
next if $match =~ m/^\w+\.cgi/mxo;
next if $match =~ m/^javascript:/mxo;
next if $match =~ m/^'\+\w+\+'$/mxo and defined $ENV{'PLACK_TEST_EXTERNALSERVER_URI'};
next if $match =~ m|^/thruk/frame\.html|mxo and defined $ENV{'PLACK_TEST_EXTERNALSERVER_URI'};
next if $match =~ m/"\s*\+\s*icon\s*\+\s*"/mxo;
next if $match =~ m/\/"\+/mxo;
next if $match =~ m/data:image\/png;base64/mxo;
$match =~ s/"\s*\+\s*url_prefix\s*\+\s*"/\//gmxo;
$match =~ s/"\s*\+\s*theme\s*\+\s*"/Thruk/gmxo;
$links_to_check->{$match} = 1;
}
my $errors = 0;
for my $test_url (sort keys %{$links_to_check}) {
if($test_url !~ m/^(http|\/)/gmxo) { $test_url = _relative_url($test_url, $request->base()->as_string()); }
next if $test_url =~ m/\/pnp4nagios\//mxo;
next if $test_url =~ m/\/pnp\//mxo;
next if $test_url =~ m/\/grafana\//mxo;
next if $test_url =~ m|/thruk/themes/.*?/images/logos/|mxo;
my $request = _request($test_url, undef, undef, $opts->{'agent'});
if($request->is_redirect) {
my $redirects = 0;
while(my $location = $request->{'_headers'}->{'location'}) {
if($location !~ m/^(http|\/)/gmxo) { $location = _relative_url($location, $request->base()->as_string()); }
$request = _request($location, undef, undef, $opts->{'agent'});
$redirects++;
last if $redirects > 10;
}
}
unless($request->is_success) {
$errors++;
diag("'$test_url' is missing, status: ".$request->code);
}
}
is( $errors, 0, 'All stylesheets, images and javascript exist' );
}
# sleep after the request?
if(defined $opts->{'sleep'}) {
ok(sleep($opts->{'sleep'}), "slept $opts->{'sleep'} seconds");
}
if($opts->{'callback'}) {
$opts->{'callback'}($return->{'content'});
}
$return->{'response'} = $request;
$return->{'code'} = $request->code();
return $return;
}
#########################
=head2 set_cookie
set_cookie($name, $value, $expire)
Sets cookie. Expire date is in seconds. A value <= 0 will remove the cookie.
=cut
sub set_cookie {
my($var, $val, $expire) = @_;
our($cookie_jar, $cookie_file);
if(!defined $cookie_jar) {
my $fh;
($fh, $cookie_file) = tempfile(TEMPLATE => 'tempXXXXX', UNLINK => 1);
unlink ($cookie_file);
$cookie_jar = HTTP::Cookies::Netscape->new(file => $cookie_file);
}
my $config = Thruk::Config::get_config();
my $cookie_path = $config->{'cookie_path'};
$cookie_jar->set_cookie( 0, $var, $val, $cookie_path, 'localhost.local', undef, 1, 0, $expire, 1, {});
$cookie_jar->save();
return;
}
#########################
sub diag_lint_errors_and_remove_some_exceptions {
my($lint, $content) = @_;
my @return;
for my $error ( $lint->errors ) {
my $err_str = $error->as_string;
next if $err_str =~ m/<IMG\ SRC="[^"]+">\ tag\ has\ no\ HEIGHT\ and\ WIDTH\ attributes/imxo;
next if $err_str =~ m/Unknown\ attribute\ "data\-[\w\-]+"\ for\ tag/imxo;
next if $err_str =~ m/Invalid\ character.*should\ be\ written\ as/imxo;
next if $err_str =~ m/Unknown\ attribute\ "placeholder"\ for\ tag\ <input>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "placeholder"\ for\ tag\ <textarea>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "class"\ for\ tag\ <html>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "autocomplete"\ for\ tag\ <form>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "autocomplete"\ for\ tag\ <input>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "hidden"\ for\ tag\ <option>/imxo;
next if $err_str =~ m/Character\ ".*?"\ should\ be\ written\ as/imxo;
next if $err_str =~ m/Unknown\ attribute\ "manifest"\ for\ tag\ <html>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "sizes"\ for\ tag\ <link>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "charset"\ for\ tag\ <meta>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "required"\ for\ tag\ <(input|select|textarea)>/imxo;
next if $err_str =~ m/Unknown\ attribute\ "oncontextmenu"\ for\ tag/imxo;
next if $err_str =~ m/<html>\ tag\ is\ required/imxo;
next if $err_str =~ m/<head>\ tag\ is\ required/imxo;
next if $err_str =~ m/<title>\ tag\ is\ required/imxo;
next if $err_str =~ m/<body>\ tag\ is\ required/imxo;
next if $err_str =~ m/Entity\ .*\ is\ unknown/imxo;
next if $err_str =~ m/Unknown\ element\ <(main|header|footer|nav)>/imxo;
diag($error->as_string."\n");
my @lines = $error->as_string() =~ m/\((\d+):\d+\)/gmx;
for my $line (sort @lines) {
_diag_context($content, $line);
}
push @return, $error;
}
return @return;
}
#########################
sub _diag_context {
my($content, $nr) = @_;
my $linenr = 0;
for my $line (split(/\n/, $content)) {
$linenr++;
if($linenr >= $nr-2 && $linenr <= $nr+2) {
diag($linenr.": ".substr($line, 0, 250));
}
}
return;
}
#########################
sub get_themes {
my @themes = @{Thruk->config->{'themes'}};
return @themes;
}
#########################
sub get_c {
our($c);
return $c if defined $c;
my $res;
($res, $c) = ctx_request('/thruk/main.html');
return $c;
}
#########################
sub get_user {
my $c = get_c();
require Thruk::Utils;
my ($uid, $groups) = Thruk::Utils::get_user($c);
my $user = getpwuid($uid);
return $user;
}
#########################
sub wait_for_job {
my($url) = @_;
my($job, $joburl);
my $maxwait = 300;
my $maxend = time() + $maxwait;
if($url =~ m/^\w+$/mx) {
$job = $url;
}
elsif($url =~ m/proxy\.cgi\/([^\/]+)\/.*cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
$job = $1;
$joburl = $url.'&json=1';
}
elsif($url =~ m/cgi\-bin\/job\.cgi\?job=(\w+)/mxo) {
$job = $1;
}
my $start = time();
my $config = Thruk::Config::get_config();
if($ENV{'PLACK_TEST_EXTERNALSERVER_URI'} || $joburl) {
$joburl = '/thruk/r/thruk/jobs/'.$job unless $joburl;
local $SIG{ALRM} = sub { die("timeout while waiting for external job: ".$job) };
alarm($maxwait);
my $data;
eval {
while(time() < $maxend) {
my $r = _request($joburl);
eval {
$data = decode_json($r->decoded_content);
};
last if($data && defined $data->{'is_running'} && $data->{'is_running'} == 0 && $data->{'end'} && $data->{'end'} > 0);
sleep(0.1);
}
};
my $end = time();
is($data->{'is_running'}, 0, 'job '.$job.' is finished in '.($end-$start).' seconds');
alarm(0);
return;
}
my $jobdir = $config->{'var_path'} ? $config->{'var_path'}.'/jobs/'.$job : './var/jobs/'.$job;
if(!-e $jobdir) {
fail("job folder ".$jobdir.": ".$!);
return;
}
local $SIG{ALRM} = sub { die("timeout while waiting for job: ".$jobdir) };
require Thruk::Utils::External;
alarm($maxwait);
eval {
while(Thruk::Utils::External::_is_running(undef, $jobdir) && time() < $maxend) {
sleep(0.1);
}
};
alarm(0);
my $end = time();
is(Thruk::Utils::External::_is_running(undef, $jobdir), 0, 'job is finished in '.($end-$start).' seconds')
or diag(sprintf("uptime: %s\n\nps:\n%s\n\njobs:\n%s\n",
scalar `uptime`,
scalar `ps -efl`,
scalar `find $jobdir/ -ls -exec cat {} \\;`,
));
return;
}
#########################
=head2 test_command
execute a test command
needs test hash
{
cmd => command line to execute
exit => expected exit code (set to undef to ignore exit code verification)
like => (list of) regular expressions which have to match stdout
errlike => (list of) regular expressions which have to match stderr, default: empty
unlike => (list of) regular expressions which must not match stdout
sleep => time to wait after executing the command
env => hash with extra environment variables
waitfor => wait till regex occurs (max 120sec)
}
=cut
sub test_command {
my $test = shift;
my($rc, $stdout, $stderr) = ( -1, '', '') ;
my $return = 1;
require Test::Cmd;
Test::Cmd->import();
# run the command
isnt($test->{'cmd'}, undef, "running cmd: ".Thruk::Utils::Encode::encode_utf8($test->{'cmd'})) or $return = 0;
if($test->{'env'}) {
for my $key (%{$test->{'env'}}) {
$ENV{$key} = $test->{'env'}->{$key};
}
}
my($prg,$arg) = split(/\s+/, $test->{'cmd'}, 2);
my $t = Test::Cmd->new(prog => $prg, workdir => '') or die($!);
# wait for something?
if(defined $test->{'waitfor'}) {
my $start = time();
my $now = time();
my $waitfor = $test->{'waitfor'};
my $found = 0;
local $test->{'exit'} = undef;
local $test->{'like'} = '/.*/';
local $test->{'errlike'} = '/.*/';
my $expr = '';
my $end = $start + 30;
ok(1, "waiting for $waitfor to appear till ".(scalar localtime $end));
while($now <= $end) {
alarm(15);
$expr = $waitfor;
eval {
local $SIG{ALRM} = sub { die "timeout on cmd: ".$test->{'cmd'}."\n" };
$t->run(args => $arg, stdin => $test->{'stdin'});
};
alarm(0);
$stdout = Thruk::Utils::Encode::decode_any(scalar $t->stdout);
if($waitfor =~ m/^\!/) {
$expr =~ s/^\!//mx;
if($stdout !~ m/$expr/mx) {
ok(1, "content ".$expr." disappeared after ".($now - $start)."seconds");
$found = 1;
last;
}
}
elsif($stdout =~ m/$waitfor/mx) {
ok(1, "content ".$expr." found after ".($now - $start)."seconds");
$found = 1;
last;
}
sleep(1);
$now = time();
}
if(!$found) {
fail("content ".$expr." did not occur within 120 seconds");
diag("command waitfor failed:\n".$stdout."\n"._caller_info());
}
}
alarm(300);
eval {
local $SIG{ALRM} = sub { die "timeout on cmd: ".$test->{'cmd'}."\n" };
$t->run(args => $arg, stdin => $test->{'stdin'});
$rc = $?>>8;
};
if($@) {
$stderr = $@;
} else {
$stderr = Thruk::Utils::Encode::decode_any(scalar $t->stderr);
}
$stdout = Thruk::Utils::Encode::decode_any(scalar $t->stdout);
alarm(0);
# exit code?
$test->{'exit'} = 0 unless exists $test->{'exit'};
if(defined $test->{'exit'} and $test->{'exit'} != -1) {
ok($rc == $test->{'exit'}, "exit code: ".$rc." == ".$test->{'exit'}) or do { diag("command failed with rc: ".$rc." - ".$stdout."\n"._caller_info()); $return = 0 };
}
# matches on stdout?
if(defined $test->{'like'}) {
for my $expr (ref $test->{'like'} eq 'ARRAY' ? @{$test->{'like'}} : $test->{'like'} ) {
like($stdout, $expr, "stdout like ".Thruk::Utils::Encode::encode_utf8($expr)) or do { diag("\ncmd: '".$test->{'cmd'}."' failed\n"._caller_info()); $return = 0 };
}
}
# unlike matches on stdout?
if(defined $test->{'unlike'}) {
for my $expr (ref $test->{'unlike'} eq 'ARRAY' ? @{$test->{'unlike'}} : $test->{'unlike'} ) {
unlike($stdout, $expr, "stdout unlike ".$expr) or do { diag("\ncmd: '".$test->{'cmd'}."' failed\n"._caller_info()); $return = 0 };
}
}
# matches on stderr?
$test->{'errlike'} = '/^\s*$/' unless exists $test->{'errlike'};
if(defined $test->{'errlike'}) {
for my $expr (@{_list($test->{'errlike'})}) {
like($stderr, $expr, "stderr like ".$expr) or do { diag("\ncmd: '".$test->{'cmd'}."' failed\n"._caller_info()); $return = 0 };
}
}
# sleep after the command?
if(defined $test->{'sleep'}) {
ok(sleep($test->{'sleep'}), "slept $test->{'sleep'} seconds") or do { $return = 0 };
}
# set some values
$test->{'stdout'} = $stdout;
$test->{'stderr'} = $stderr;
$test->{'exit'} = $rc;
return $return;
}
#########################
=head2 override_config
override_config('key', 'value')
override config setting
=cut
sub override_config {
my($key, $value) = @_;
my $c = get_c();
$c->config->{$key} = $value;
ok(1, "config: set '$key' to '$value'");
return;
}
#########################
sub make_test_hash {
my $data = shift;
my $test = shift || {};
if(ref $data eq '') {
$test->{'url'} = $data;
} else {
for my $key (%{$data}) {
$test->{$key} = $data->{$key};
}
}
return $test;
}
#########################
sub _relative_url {
my($location, $url) = @_;
my $newloc = $url;
$newloc =~ s/^(.*\/).*$/$1/gmxo;
$newloc .= $location;
while($newloc =~ s|/[^\/]+/\.\./|/|gmxo) {}
return $newloc;
}
#########################
sub _request {
my($url, $start_to, $post, $agent, $method) = @_;
our($cookie_jar, $cookie_file);
if(!defined $cookie_jar) {
my $fh;
($fh, $cookie_file) = tempfile(TEMPLATE => 'tempXXXXX', UNLINK => 1);
unlink ($cookie_file);
$cookie_jar = HTTP::Cookies::Netscape->new(file => $cookie_file);
}
$url =~ s|^\Qhttp://localhost.local/\E|/|gmx;
if(defined $ENV{'PLACK_TEST_EXTERNALSERVER_URI'} || $url =~ m/^https?:\/\//mx) {
return(_external_request(@_));
}
# add pseudo domain, otherwise cookies from set_cookie() won't work
$url = 'http://localhost.local'.$url unless $url =~ m|^https?:|mx;
my $request;
if($post) {
$method = 'POST' unless $method;
$method = uc($method);
$post->{'CSRFtoken'} = $test_token if $test_token;
$request = POST($url, {});
$request->method(uc($method));
$request->content_type('application/json; charset=utf-8');
$request->content(Cpanel::JSON::XS->new->encode($post)); # using ->utf8 here would end in double encoding
$request->header('Content-Length' => undef);
} else {
$method = 'GET' unless $method;
$method = uc($method);
$request = HTTP::Request->new($method => $url);
}
$request->header("User-Agent" => $agent) if $agent;
$cookie_jar->add_cookie_header($request);
my $response = request($request);
$cookie_jar->extract_cookies($response);
return $response;
}
#########################
sub _external_request {
my($url, $start_to, $post, $agent, $method, $retry) = @_;
confess("no url") unless $url;
$retry = 1 unless defined $retry;
if($url !~ m/^http/) {
$url =~ s#//#/#gmx;
$url =~ s#^/demo##gmx;
if($ENV{'PLACK_TEST_EXTERNALSERVER_URI'}) {
$url = $ENV{'PLACK_TEST_EXTERNALSERVER_URI'}.$url;
}
}
our($cookie_jar, $cookie_file);
my $ua = Thruk::UserAgent->new({
keep_alive => 1,
max_redirect => 0,
timeout => 60,
requests_redirectable => [],
}, {
use_curl => $has_curl,
});
$ua->env_proxy;
$ua->cookie_jar($cookie_jar);
$ua->agent( $agent ) if $agent;
if($post && ref $post ne 'HASH') {
confess("unknown post data: ".Dumper($post));
}
my $req;
if($post || ($method && $method ne 'GET')) {
$post = {} unless defined $post;
$post->{'CSRFtoken'} = $test_token if $test_token;
$method = 'POST' unless $method;
my $request = POST($url, {});
$request->method(uc($method));
$request->content_type('application/json; charset=utf-8');
$request->content(Cpanel::JSON::XS->new->encode($post)); # using ->utf8 here would end in double encoding
$request->header('Content-Length' => undef);
$request->header('X-Thruk-Auth-Key' => $ENV{'THRUK_TEST_AUTH_KEY'}) if $ENV{'THRUK_TEST_AUTH_KEY'};
$request->header('X-Thruk-Auth-User' => $ENV{'THRUK_TEST_AUTH_USER'}) if $ENV{'THRUK_TEST_AUTH_USER'};
$cookie_jar->add_cookie_header($request) if $cookie_jar;
$req = $ua->request($request);
} else {
my $request = GET($url);
$cookie_jar->add_cookie_header($request) if $cookie_jar;
$request->header('X-Thruk-Auth-Key' => $ENV{'THRUK_TEST_AUTH_KEY'}) if $ENV{'THRUK_TEST_AUTH_KEY'};
$request->header('X-Thruk-Auth-User' => $ENV{'THRUK_TEST_AUTH_USER'}) if $ENV{'THRUK_TEST_AUTH_USER'};
$req = $ua->request($request);
}
if($req->is_redirect and $req->{'_headers'}->{'location'} =~ m/\/thruk\/cgi\-bin\/login\.cgi\?(.*)$/mxo and defined $ENV{'THRUK_TEST_AUTH'}) {
die("login failed: ".Dumper($req)) unless $retry;
my $referer = uri_unescape($1);
$referer =~ s/^nocookie&//gmx;
$referer = '/'.$referer;
my($user, $pass) = split(/:/mx, $ENV{'THRUK_TEST_AUTH'}, 2);
my $login_page = $req->{'_headers'}->{'location'};
my $r = _external_request($login_page, undef, undef, $agent);
$login_page =~ s/nocookie&//gmx;
$r = _external_request($login_page, undef, { password => $pass, login => $user, submit => 'login', referer => $referer }, $agent, undef, 0);
$req = _external_request($r->{'_headers'}->{'location'}, $start_to, $post, $agent, undef, 0);
}
return $req;
}
#########################
sub _set_test_page_defaults {
my($opts) = @_;
if(!exists $opts->{'unlike'}) {
$opts->{'unlike'} = [ 'internal server error', 'HASH', 'ARRAY' ];
}
return $opts;
}
#########################
sub bail_out_req {
my($msg, $res, $die) = @_;
my $page = $res->content;
my $error = "";