-
Notifications
You must be signed in to change notification settings - Fork 4
/
stbt_rig.py
executable file
·2159 lines (1820 loc) · 76 KB
/
stbt_rig.py
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
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Command-line tool for interacting with the Stb-tester Portal's REST API.
For more details, and to get the latest version of this script, see
<https://stb-tester.com/manual/stbt-rig>.
Copyright 2017-2022 Stb-tester.com Ltd. <[email protected]>
Released under the MIT license.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import argparse
import errno
import fnmatch
import hashlib
import itertools
import logging
import os
import platform
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from collections import namedtuple
from contextlib import contextmanager
from textwrap import dedent
try:
import configparser
ConfigParser = configparser.ConfigParser
except ImportError:
# Python 2
import ConfigParser as configparser
ConfigParser = configparser.SafeConfigParser
try:
# Bash tab-completion, if python-argcomplete is installed
from argcomplete import autocomplete
except ImportError:
def autocomplete(*_args):
pass
try:
from requests.adapters import HTTPAdapter
from requests.exceptions import HTTPError
except ImportError:
# Hack: Work around requests not being installed so stbt_rig.py setup still
# works
class HTTPAdapter(object):
pass
class HTTPError(Exception):
pass
logger = logging.getLogger("stbt_rig")
def main(argv=None):
parser = argparser()
autocomplete(parser)
args = parser.parse_args((argv or sys.argv)[1:])
signal.signal(signal.SIGINT, _exit)
signal.signal(signal.SIGTERM, _exit)
if hasattr(signal, "SIGHUP"):
signal.signal(signal.SIGHUP, _exit) # pylint:disable=no-member
if args.command == "setup" and args.verbosity == 0:
args.verbosity = 1
logging.basicConfig(
format="%(filename)s: %(levelname)s: %(message)s",
level=logging.WARNING - args.verbosity * 10)
if args.C:
os.chdir(args.C)
resolve_args(args)
return main_with_args(args)
def resolve_args(args):
if args.mode == "auto":
if "JENKINS_HOME" in os.environ:
args.mode = "jenkins"
elif "bamboo_agentWorkingDirectory" in os.environ:
args.mode = "bamboo"
elif "GITLAB_CI" in os.environ:
args.mode = "gitlab"
else:
args.mode = "interactive"
if not args.portal_url:
try:
_, config_parser = read_stbt_conf(find_test_pack_root())
args.portal_url = config_parser.get('test_pack', 'portal_url')
except configparser.Error as e:
die("--portal-url isn't specified on the command line and "
"test_pack.portal_url isn't specified in .stbt.conf: %s", e)
if args.command in ("run", "screenshot") and not args.node_id:
die("argument --node-id is required")
def main_with_args(args):
# Do this before importing requests, we will be installing requests in here:
if args.command == "setup":
return cmd_setup(args, args.node_id)
elif args.command == "auth":
# auth logout doesn't require a portal - and we don't want to prompt
# for an auth token just before deleting it!
return cmd_auth(args)
portal = Portal.from_args(args)
node = Node(portal, args.node_id)
try:
if args.command == "run":
return cmd_run(args, node)
elif args.command == "download":
return cmd_download(args, portal)
elif args.command == "encrypt-secret":
return cmd_encrypt_secret(args, portal)
elif args.command == "screenshot":
return cmd_screenshot(args, node)
elif args.command == "snapshot":
return cmd_snapshot(args, node)
assert False, "Unreachable: Unknown command %r" % args.command
except HTTPError as e:
message = "HTTP %i Error: %s" % (
e.response.status_code, e.response.text)
if hasattr(e, "request"):
message += " during %s %s" % (
e.request.method, e.request.url) # pylint:disable=no-member
die(message)
except NodeBusyException as e:
die(str(e))
# Unreachable, but it makes pylint happy:
return 1
class Arg(namedtuple(
'Arg', 'name action nargs default choices help metavar dest '
'completer cmdline_only')):
def add(self, parser):
d = {k: v for k, v in self._asdict().items()
if (k not in ['name', 'completer', 'cmdline_only'] and
v is not None)}
a = parser.add_argument(
*(self[0] if isinstance(self[0], tuple) else (self[0],)),
**d)
if self.completer:
a.completer = self.completer
@property
def longname(self):
if isinstance(self.name, tuple):
return self.name[1]
else:
return self.name
Arg.__new__.__defaults__ = (
None, None, None, None, None, None, None, None, False)
def _list_node_ids(**_kwargs):
"""Used for command-line tab-completion.
For lack of a better place too look, looks for configuration files in
config/test-farm -- see https://stb-tester.com/manual/configuration#node-specific-configuration-files
"""
return [f[17:-5]
for f in to_unicode(subprocess.check_output(
["git", "ls-files", "config/test-farm/stb-tester-*.conf"]))
.strip().split("\n")]
def _list_test_cases(prefix, **_kwargs):
"""Used for command-line tab-completion."""
if "::" in prefix:
# List testcases in the file.
filename = prefix.split("::")[0]
tests = []
for line in open(filename):
m = re.match(r"^def\s+(test_[a-zA-Z0-9_]+)", line)
if m:
tests.append(filename + "::" + m.group(1))
return tests
else:
# List files:
return [f + "::"
for f in to_unicode(subprocess.check_output(
["git", "ls-files", "tests/**.py"])).strip().split("\n")]
ARGS = [
Arg("-C", metavar="PATH", help="Change to directory PATH before doing "
"anything else.", cmdline_only=True),
Arg("--portal-url", metavar="https://COMPANYNAME.stb-tester.com",
help="""Base URL of your Stb-tester Portal. You can specify it on the
command line or as "portal_url" in the [test_pack] section of
.stbt.conf. We look for .stbt.conf in the current working
directory."""),
# Can't pass auth token on command line because it would be visible in
# /proc. Pass it in a file instead.
Arg("--portal-auth-file", metavar="FILENAME",
help="""File containing the HTTP REST API access token. See
<https://stb-tester.com/manual/stbt-rig#authentication>."""),
Arg("--node-id", metavar="stb-tester-abcdef123456",
help="""Which Stb-tester node to execute the COMMAND on. The node ID is
labelled on the physical Stb-tester node, and it is also shown in the
Stb-tester Portal. Defaults to $STBT_NODE_ID.""",
default=os.environ.get("STBT_NODE_ID"),
completer=_list_node_ids),
Arg("--git-remote", metavar="NAME", default="origin",
help="""Which git remote to push to. Defaults to "origin" (this is the
default name that git creates when you did the original "git clone" of
the test-pack repository). This is only used by the commands that need
to push temporary snapshots to git: that is, "run" and "press" when
"--mode=interactive"."""),
Arg("--mode",
choices=["auto", "bamboo", "gitlab", "interactive", "jenkins"],
default="auto",
help="""See <https://stb-tester.com/manual/stbt-rig#interactive-mode>.
This defaults to "auto", which detects whether or not it is being run
inside Bamboo/GitLab/Jenkins.""", cmdline_only=True),
Arg("--csv", metavar="FILENAME",
help="Also write test-results in CSV format to the specified file."),
Arg(("-v", "--verbose"), action="count", dest="verbosity", default=0,
help="""Specify once to enable INFO logging, twice for DEBUG.""",
cmdline_only=True),
]
RUN_ARGS = [
Arg("--force", action="store_true",
help="""Stop an existing job first (otherwise this script will fail if
the Stb-tester node is busy)."""),
Arg("--test-pack-revision", metavar="GIT_SHA", help="""Git commit SHA in
the test-pack repository identifying the version of the tests to run.
Can also be the name of a git branch or tag. In interactive mode this
defaults to a snapshot of your current working directory. In
bamboo/gitlab/jenkins mode this defaults to the test-pack repository's
default branch (typically "main")."""),
Arg("--remote-control", metavar="NAME", help="""The remote control infrared
configuration to use when running the tests. This should match the name
of a remote control configuration file in your test-pack git
repository. For example if your test-pack has
"config/remote-control/roku.lircd.conf" then you should specify "roku".
If not specified here, you must specify
"test_pack.default_remote_control" in the test-pack's .stbt.conf"""),
Arg("--category", metavar="NAME", help="""Category to save the test-results
in. When you are viewing test results you can filter by this string. In
interactive mode this defaults to the branch name. In
bamboo/gitlab/jenkins mode this defaults to the CI job name."""),
Arg("--soak", action="store_true", help="""Run the testcases forever until
you interrupt them by pressing Control-C.""", cmdline_only=True),
Arg("--shuffle", action="store_true", help="""Randomise the order in which
the tests are run. If "--soak" is also specified, this will prefer
to run the faster testcases more often.""", cmdline_only=True),
Arg(("-t", "--tag"), action="append", dest="tags", default=[],
metavar="NAME=VALUE", help="""Tags are passed to the test scripts in
sys.argv and are recorded alongside the test-results. "--tag" can be
specified more than once."""),
Arg(("--artifacts"), action="append", dest="artifacts", default=[],
metavar="GLOB", help="""Download the specified artifacts. This is a
filename glob. Set to "*" for all artifacts. This argument can be
specified multiple times."""),
Arg(("--artifacts-dest"), metavar="PATH",
default=os.path.join("{result_id}", "artifacts", "{filename}"),
help="""Download the artifacts (specified by --artifacts) to PATH. You
can use the placeholders {result_id}, {filename} and {basename}.
Defaults to "%(default)s". Directories will be created as
required."""),
Arg("--junit-xml", action="append", dest="junit_xml", default=[],
help="""Save test-results in JUnit XML format to this filename. In
bamboo/gitlab/jenkins mode this is enabled by default, with the
filename 'stbt-results.xml'.""",
cmdline_only=True),
Arg("test_cases", nargs='+', metavar="TESTCASE",
help="""One or more tests to run. Test names have the form
FILENAME::FUNCTION_NAME where FILENAME is given relative to the root of
the test-pack repository and FUNCTION_NAME identifies a Python function
within that file; for example
"tests/my_test.py::test_that_blah_dee_blah".""", cmdline_only=True,
completer=_list_test_cases)
]
def argparser():
parser = argparse.ArgumentParser(
description="Command-line tool for interacting with the Stb-tester "
"Portal's REST API. See <https://stb-tester.com/manual/stbt-rig>.")
for arg in ARGS:
arg.add(parser)
subcommands = parser.add_subparsers(
dest="command", title="COMMANDS", metavar="COMMAND",
description=dedent("""\
Note: Run "./stbt_rig.py COMMAND -h" to see the additional
parameters for each COMMAND."""))
run_parser = subcommands.add_parser(
"run", help="Run testcases",
description="""Run the specified testcases on the specified Stb-tester
node. In interactive mode (the default mode if not running inside a
Bamboo/GitLab/Jenkins job) it also pushes a snapshot of your current
test-pack and pushes it to the branch "@YOUR_USERNAME's snapshot" on
the Stb-tester Portal, so that you don't have to make lots of temporary
git commits to debug your test scripts.""")
for arg in RUN_ARGS:
arg.add(run_parser)
download_parser = subcommands.add_parser(
"download", help="Download test-result artifacts",
description="""Download artifacts (log files, screenshots, etc) from
previous test-runs.""")
download_parser.add_argument(
"--artifacts", action="append", dest="artifacts", default=[],
metavar="GLOB", help="""Download the specified artifacts. This is a
filename glob. Defaults to "*" (all artifacts). This argument can be
specified multiple times.""")
download_parser.add_argument(
"--artifacts-dest", metavar="PATH",
default=os.path.join("{result_id}", "artifacts", "{filename}"),
help="""Download the artifacts (specified by --artifacts) to PATH. You
can use the placeholders {result_id}, {filename} and {basename}.
Defaults to "%(default)s". Directories will be created as required.""")
download_parser.add_argument(
"filter", help='''Search filter to identify the desired test-runs,
as given to the REST API (/api/v2/results) or the interactive
test-results view in the Stb-tester Portal -- see
<https://stb-tester.com/manual/user-interface-reference#filter>.''')
encrypt_secret_parser = subcommands.add_parser(
"encrypt-secret", help="Write encrypted value to config file")
encrypt_secret_parser.add_argument(
"name", help="Name that can be used to retrieve the secret")
encrypt_secret_parser.add_argument("value", help="Value to be encrypted")
auth_parser = subcommands.add_parser(
"auth", help="Authenticate with the Stb-tester Portal")
auth_subparser = auth_parser.add_subparsers(dest="auth_command")
auth_subparser.add_parser(
"get-username",
help="Prints the GitHub username of the authenticated user")
auth_subparser.add_parser(
"logout", help="Delete the auth token from your keyring on this PC")
screenshot_parser = subcommands.add_parser(
"screenshot", help="Save a screenshot to disk",
description="""Take a screenshot from the specified Stb-tester node
and save it to disk.""")
screenshot_parser.add_argument(
"filename", default="screenshot.png", nargs='?',
help="""Output filename. Defaults to "%(default)s".""")
subcommands.add_parser(
"snapshot", help="Push a snapshot of your current test-pack",
description="""Take a snapshot of your current test-pack and push it
to the branch "@YOUR_USERNAME's snapshot" on the Stb-tester Portal.
Note that the "run" command automatically does this when in interactive
mode.""")
setup_parser = subcommands.add_parser(
"setup", help="Setup your venv for development",
description="""Creates a Python venv in ".venv" and installs
dependencies needed for IDE autocompletion & linting.""")
setup_parser.add_argument(
"--vscode", action="store_true",
help="Update VSCode settings.json with recommended settings")
return parser
def _exit(signo, _):
name = next(k for k, v in signal.__dict__.items()
if v == signo and "_" not in k)
logger.warning("Received %s. Stopping job.", name)
# Teardown is handled by TestJob.__exit__
sys.exit(0)
def cmd_auth(args):
# type: (argparse.Namespace) -> int
if args.auth_command == "logout":
try:
import keyring
if keyring.get_password(args.portal_url, "stb-tester") is None:
sys.stderr.write("No auth token stored in keyring\n")
else:
keyring.delete_password(args.portal_url, "stb-tester")
sys.stderr.write("Deleted auth token from keyring\n")
except ImportError:
sys.stderr.write(
"Install the python \"keyring\" package to use "
"\"stbt_rig auth\"\n")
return 1
elif args.auth_command == "get-username" or args.auth_command is None:
# This will prompt the user for a token if none is stored:
portal = Portal.from_args(args)
print(portal.get_user()['login'])
else:
assert False, "Unreachable: Unknown auth_command %r" % args.auth_command
return 0
def cmd_run(args, node):
j = cmd_run_prep(args, node.portal)
return cmd_run_body(args, node, j)
JobPrepResult = namedtuple("JobPrepResult", "commit_sha category tags")
def cmd_run_prep(args, portal):
if args.mode in ["interactive", "pytest"]:
branch_name = _get_snapshot_branch_name(portal)
if args.test_pack_revision:
commit_sha = args.test_pack_revision
else:
if args.mode == "interactive":
commit_sha = TestPack(remote=args.git_remote) \
.push_git_snapshot(branch_name)
elif args.mode == "pytest":
commit_sha = TestPack(remote=args.git_remote) \
.push_git_snapshot(branch_name, interactive=False)
elif args.mode in ["bamboo", "gitlab", "jenkins"]:
# We assume that when in CI we're not in the git repo of the
# test-pack, so run tests from main.
commit_sha = "HEAD"
else:
assert False, "Unreachable: Unknown mode %r" % args.mode
if args.category:
category = args.category
else:
if args.mode in ["interactive", "pytest"]:
category = branch_name
elif args.mode == "jenkins":
category = os.environ["JOB_NAME"]
elif args.mode == "bamboo":
category = os.environ["bamboo_shortJobName"]
elif args.mode == "gitlab":
category = os.environ["CI_JOB_NAME"]
else:
assert False, "Unreachable: Unknown mode %r" % args.mode
tags = {}
if args.mode == "jenkins":
# Record Jenkins environment variables as Stb-tester tags.
# GIT_COMMIT or SVN_REVISION will refer to the repo of the STB software
# being tested in CI, rather than the test-pack repo.
for v in ["BUILD_ID", "BUILD_URL", "GIT_COMMIT", "JOB_NAME",
"SVN_REVISION"]:
if os.environ.get(v):
tags["jenkins/%s" % v] = os.environ[v]
elif args.mode == "bamboo":
# Record Bamboo variables as Stb-tester tags. Bamboo exports its
# variables as environment variables with dots replaced by underscores.
# "bamboo.planRepository.revision" will refer to the repo of the STB
# software being tested in CI, rather than the test-pack repo.
# See the complete list of bamboo variables here:
# https://confluence.atlassian.com/bamboo/bamboo-variables-289277087.html
for v in ["bamboo.buildPlanName",
"bamboo.buildResultKey",
"bamboo.buildResultsUrl",
"bamboo.planRepository.branchName",
"bamboo.planRepository.revision"]:
value = os.environ.get(v.replace(".", "_"))
if value:
tags[v] = value
elif args.mode == "gitlab":
# Record gitlab CI variables as Stb-tester tags.
# https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
for v in ["CI_COMMIT_REF_NAME",
"CI_COMMIT_SHA",
"CI_ENVIRONMENT_NAME",
"CI_JOB_ID",
"CI_JOB_NAME",
"CI_JOB_STAGE",
"CI_JOB_URL",
"CI_PROJECT_URL",
"CI_REPOSITORY_URL"]:
if os.environ.get(v):
tags["gitlab/%s" % v] = os.environ[v]
for tag in args.tags:
try:
name, value = tag.split("=", 1)
except ValueError:
die("Invalid --tag argument: %s (should be NAME=VALUE)" % tag)
if name in tags:
die("Duplicate --tag name: %s" % name)
tags[name] = value
return JobPrepResult(commit_sha, category, tags)
def cmd_run_body(args, node, j):
# type: (argparse.Namespace, Node, JobPrepResult) -> int
logger.info("Running tests...")
try:
root = find_test_pack_root()
test_cases = [os.path.relpath(x, root).replace('\\', '/')
for x in args.test_cases]
except NotInTestPack:
test_cases = args.test_cases
job = node.run_tests(
j.commit_sha, test_cases, args.remote_control, j.category,
args.soak, args.shuffle, j.tags, args.force)
try:
job.await_completion()
except SystemExit: # raised by our signal handler
job.stop()
results = job.list_results()
if args.mode in ["interactive", 'pytest']:
for result in results:
print("")
print(result.json["triage_url"])
result.print_logs()
elif args.mode in ["bamboo", "gitlab", "jenkins"]:
# Record results in XML format for the Jenkins JUnit plugin
if not args.junit_xml:
args.junit_xml = ["stbt-results.xml"]
if args.junit_xml:
results_xml = job.list_results_xml()
for filename in args.junit_xml:
with open(filename, "w") as f:
f.write(results_xml)
if args.csv:
results_csv = job.list_results_csv()
with open(args.csv, "w") as f:
f.write(results_csv)
if args.artifacts:
logger.info("Downloading artifacts...")
for result in results:
result.download_artifacts(args.artifacts, args.artifacts_dest)
print("View these test results at: %s/app/#/results?filter=job:%s" % (
node.portal.url(), job.job_uid))
if args.mode == "pytest":
for result in results:
result.raise_for_result()
return 0
else:
if all(result.is_ok() for result in results):
return 0
else:
return 1
def cmd_download(args, portal):
results = portal.get_results(args.filter)
for result in results:
result.download_artifacts(args.artifacts or ["*"], args.artifacts_dest)
def cmd_encrypt_secret(args, portal):
import base64
pubkey = portal.get_secrets_pubkey()
try:
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(pubkey.encode())
cmd = ["openssl", "pkeyutl", "-inkey", f.name, "-pubin", "-encrypt"]
proc = subprocess.Popen(
cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
encrypted, _ = proc.communicate(args.value.encode("utf-8"))
if proc.wait() != 0:
raise subprocess.CalledProcessError(proc.returncode, cmd, encrypted)
finally:
# Windows can't open a file that's already open - so we close it above,
# but only delete it here.
os.unlink(f.name)
encoded = base64.b64encode(encrypted).decode("utf-8")
with open("%s/.stbt.conf" % find_test_pack_root()) as f:
cfg = list(f)
_modify_config(cfg, "encrypted_secrets", args.name, encoded)
with open("%s/.stbt.conf" % find_test_pack_root(), "w") as f:
f.write("".join(cfg))
sys.stderr.write(
"Encrypted and added the secret to your stbt.conf. The unencrypted "
"secret can be read during a test run with:\n"
"\n"
" stbt.get_config('secrets', %r)\n" % args.name)
return 0
def _modify_config(cfg, section, key, value):
section_start = None
cfg_line = "%s = %s\n" % (key, value)
for n, line in enumerate(cfg):
if re.match(r"\s*\[\s*%s\s*\]" % re.escape(section), line):
section_start = n
if not line.endswith("\n"):
cfg[n] = line + "\n"
break
if section_start is None:
cfg.extend(["\n", "[%s]\n" % section, cfg_line])
return
for n, line in enumerate(cfg[section_start + 1:], section_start + 1):
if re.match(re.escape(key) + r"\s*=", line):
cfg[n] = cfg_line
return
# Preserve alphabetical order:
keyname = line.strip().split("=")[0].strip()
if keyname > key or line.strip().startswith("["):
section_end = n
break
else:
section_end = len(cfg)
# Backtrack to find insertion point:
for section_end in range(section_end, section_start, -1):
prevline = cfg[section_end - 1].strip()
if prevline and not prevline.startswith('#'):
break
cfg.insert(section_end, cfg_line)
def cmd_screenshot(args, node):
node.save_screenshot(args.filename)
return 0
def cmd_snapshot(args, node):
branch_name = _get_snapshot_branch_name(node.portal)
TestPack(remote=args.git_remote).push_git_snapshot(branch_name)
node.portal.notify_push()
def cmd_setup(args, node_id):
this_stbt_rig = os.path.abspath(sys.argv[0])
root = find_test_pack_root()
if os.environ.get("STBT_RIG_SECOND_STAGE") != "1":
# First we create a venv
setup_stage1(this_stbt_rig, root)
else:
# Then we re-exec `stbt_rig.py setup` to complete setup inside the venv.
setup_stage2(this_stbt_rig, root, args, node_id)
def setup_stage1(this_stbt_rig, root):
_, config_parser = read_stbt_conf(root)
stbt_version = int(config_parser.get("test_pack", "stbt_version"))
if stbt_version >= 33:
python_version = "3"
else:
python_version = config_parser.get("test_pack", "python_version")
if python_version != "3":
sys.stderr.write(
"Python version %r is not supported by stbt_rig.py setup. "
"Please contact [email protected]\n" % (python_version,))
sys.exit(1)
if stbt_version >= 33:
v = "3.10"
else:
v = "3.6"
system_python_exe, system_python_version = _find_python_executable(
v, stbt_version)
venv_dir = os.path.join(root, ".venv")
if os.path.exists(venv_dir):
venv_python_version = _get_python_version([_venv_exe("python", root)])
if (system_python_version.startswith(v + ".") and
not venv_python_version.startswith(v + ".")):
logging.warning(
"Virtualenv in '%s' has Python version %s; "
"deleting .venv and recreating it with Python %s.",
venv_dir, venv_python_version, v)
while True:
ok = ask("Delete and recreate .venv? [y/n] ").lower().strip()
if ok == "y":
shutil.rmtree(venv_dir)
break
elif ok == "n":
break
if not os.path.exists(venv_dir):
logging.info("Creating virtualenv in '%s' with Python %s",
venv_dir, system_python_version)
subprocess.check_call(system_python_exe + ['-m', 'venv', '.venv'],
cwd=root)
if platform.system() == "Windows":
b = "Scripts"
else:
b = "bin"
os.environ["PATH"] = (os.path.join(venv_dir, b) + os.pathsep +
os.environ.get("PATH", ""))
os.environ["VIRTUAL_ENV"] = venv_dir
# Install dependencies
if stbt_version < 33:
pip_deps = [
"keyring",
"requests",
"tzlocal",
"pytest>=4.6,<4.7",
"pylint==1.8.3",
"astroid==1.6.0",
"isort==4.3.4",
]
else:
pip_deps = [
"keyring",
"requests",
"tzlocal",
"pytest~=6.2.5",
]
if stbt_version == 32:
# Contains pylint fixes on Windows and Intellisense fixes. This
# ensures that existing .venvs are upgraded:
pip_deps.append("stbt_core>=32.0.4,==32.*")
pip_deps.append("stb-tester~=32.2")
else:
pip_deps.append("stb-tester~=%s.0" % (stbt_version,))
pip_deps.append("stbt_core~=%s.0" % (stbt_version,))
python = _venv_exe("python", root=root)
subprocess.check_call(
[python, "-m", "pip", 'install', '--upgrade', 'pip'],
cwd=root)
subprocess.check_call(
[python, "-m", "pip", 'install', '--upgrade'] + pip_deps, cwd=root)
os.environ["STBT_RIG_SECOND_STAGE"] = "1"
# We re-exec ourselves into the venv now that we've installed all our
# dependencies
cmd = [python, this_stbt_rig] + sys.argv[1:]
if platform.system() == "Windows":
# Windows has execv, but the process ends up backgrounded which
# breaks interactive use, so subprocess instead.
os._exit(subprocess.call(cmd))
else:
os.execv(cmd[0], cmd)
def setup_stage2(this_stbt_rig, root, args, node_id):
# Install this stbt_rig as a python module in the venv:
venv_site_packages = sys.path[-1]
this_stbt_rig_rel = os.path.relpath(this_stbt_rig, venv_site_packages)
pkg = os.path.join(venv_site_packages, "stbt_rig.py")
if this_stbt_rig_rel != "stbt_rig.py":
if platform.system() == "Windows":
shutil.copyfile(this_stbt_rig, pkg)
else:
try:
os.unlink(pkg)
except OSError:
# File doesn't exist
pass
os.symlink(this_stbt_rig_rel, pkg) # pylint: disable=no-member
os.chdir(root)
# This will prompt for the auth token and validate connectivity:
portal = Portal.from_args(args)
portal.get_user()
for k in "name", "email":
try:
subprocess.check_output(["git", "config", "user.%s" % k])
except subprocess.CalledProcessError as e:
if e.returncode == 1:
v = ask("What is your %s (for git commits): " % k)
subprocess.check_output(["git", "config", "user.%s" % k, v])
else:
raise
# Setup .env to include our node-id so we don't need to specify it every
# time
while not node_id:
r = portal._get("/api/_private/workgroup")
r.raise_for_status()
nodes = [n['id'] for n in r.json()]
assert nodes
if len(nodes) == 1:
node_id = nodes[0]
else:
sys.stderr.write("These nodes are attached to the portal:\n")
for (n, node) in enumerate(nodes, 1):
sys.stderr.write(" %i) %s\n" % (n, node))
node_no = ask("Which node do you want to use by default? ")
try:
node_idx = int(node_no) - 1
if node_idx < 0:
raise ValueError()
node_id = nodes[node_idx]
except (ValueError, IndexError):
sys.stderr.write(
"%r is not a valid number, please enter a value "
"between 1 and %i\n" % (node_no, len(nodes)))
continue
sys.stderr.write(
"Node %s will be used by default. Edit '.env' to change.\n" % node_id)
updates = {}
updates[b"STBT_NODE_ID"] = node_id.encode("utf-8")
_update_env(updates)
if args.vscode:
VS_CODE_CONFIG = {
"git.autoStash": True,
"git.closeDiffOnOperation": True,
"git.fetchOnPull": True,
"git.pruneOnFetch": True,
"git.pullBeforeCheckout": True,
"pylint.args": ["--load-plugins=_stbt.pylint_plugin"],
"pylint.path": ["pylint"],
"python.envFile": "${workspaceFolder}/.env",
"python.testing.nosetestsEnabled": False,
"python.testing.pytestArgs": [
"-pstbt_rig",
"-pno:python",
"--override-ini=python_files=*.py",
"--override-ini=python_functions=test_*",
"--tb=no", "--capture=no",
"tests"
],
"python.testing.pytestEnabled": True,
"python.testing.unittestEnabled": False,
# This requires the "pucelle.run-on-save" VSCode extension:
"runOnSave.commands": [
{
"match": ".*\\.py$",
"command":
"${workspaceFolder}/%s -m stbt_rig -v snapshot" % _venv_exe(
"python"),
"runIn": "backend",
"runningStatusMessage": "Running stbt_rig snapshot...",
"finishStatusMessage": "Snapshot complete"
}
]
}
VS_CODE_CONFIG_DEPRECATED_KEYS = {
"python.linting.enabled",
"python.linting.mypyEnabled",
"python.linting.pylintArgs",
"python.linting.pylintEnabled",
}
VS_CODE_RECOMMENDED_EXTENSIONS = {"recommendations": [
"ms-python.python",
"ms-python.pylint",
"pucelle.run-on-save",
]}
_update_vscode_config("settings.json", VS_CODE_CONFIG,
VS_CODE_CONFIG_DEPRECATED_KEYS)
_update_vscode_config("extensions.json", VS_CODE_RECOMMENDED_EXTENSIONS)
def _find_python_executable(v, stbt_version):
python_executable_names = (["python%s" % v], ["py", "-%s" % v],
["python"], ["python3"], ["py", "-3"])
for python in python_executable_names:
try:
o = _get_python_version(python)
if o.startswith("3."):
if not o.startswith(v + "."):
logger.warning(
"Using Python version %s which may not be "
"fully compatible with stb-tester %s. "
"For best compatibility install Python %s.",
o, stbt_version, v)
return python, o
except (subprocess.CalledProcessError, OSError):
# Doesn't exist, or there's something wrong with it
pass
die("Can't find python %s in PATH" % v)
return None # for pylint
def _get_python_version(python_exe): # -> str
return to_unicode(subprocess.check_output(
python_exe + ["-c", "import sys; print(sys.version.split(' ')[0])"],
stdin=open(os.devnull))).strip()
def _venv_exe(exe, root=None):
if root is None:
root = ""
elif not root.endswith("/"):
root += "/"
for x in ['%s.venv/bin/%s', '%s.venv/Scripts/%s.exe']:
f = x % (root, exe)
if os.path.exists(f):
return f
raise EnvironmentError("No exe %s found in venv" % exe)
def _update_vscode_config(filename, new_settings, remove_settings=None):
import json
filename = os.path.join(".vscode", filename)
try:
with open(filename) as f:
cfg = json.load(f)
except OSError:
cfg = {}
modified = False
for k, v in new_settings.items():
if cfg.get(k) != v:
cfg[k] = v
modified = True
if remove_settings:
for k in list(cfg.keys()):
if k in remove_settings:
del cfg[k]
modified = True
if modified:
mkdir_p(".vscode")
with sponge(filename) as f:
f.write(json.dumps(cfg, indent=4, sort_keys=True).encode("utf-8"))
def _update_env(updates):
"""Used for updating vscode style .env files which have the format:
KEY=VALUE
KEY2=VALUE2
"""
if not updates:
return
try:
with open(".env", "rb") as f:
env = f.read()
except IOError:
env = b""
with sponge(".env") as f:
for l in env.split(b"\n"):
try:
k, v = l.split(b'=', 1)
f.write(b"%s=%s\n" % (k, updates[k]))
del updates[k]
except (ValueError, KeyError):
f.write(l + b"\n")
continue
for k, v in updates.items():
f.write(b"%s=%s\n" % (k, v))
def _get_snapshot_branch_name(portal):
username = portal.get_user()["login"]