launchable 1.0__3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
launchable/__init__.py ADDED
File without changes
launchable/__main__.py ADDED
@@ -0,0 +1,28 @@
1
+ from .version import __version__
2
+ import click
3
+ import importlib
4
+ from os.path import dirname, basename, join
5
+ from glob import glob
6
+ from .commands.record import record
7
+ from .commands.subset import subset
8
+ from .commands.verify import verify
9
+
10
+
11
+ @click.group()
12
+ @click.version_option(version=__version__, prog_name='launchable-cli')
13
+ def main():
14
+ # load all test runners
15
+ for f in glob(join(dirname(__file__), 'test_runners', "*.py")):
16
+ f = basename(f)[:-3]
17
+ if f == '__init__':
18
+ continue
19
+ importlib.import_module('launchable.test_runners.%s' % f)
20
+
21
+
22
+ main.add_command(record)
23
+ main.add_command(subset)
24
+ main.add_command(verify)
25
+
26
+
27
+ if __name__ == '__main__':
28
+ main()
File without changes
@@ -0,0 +1,18 @@
1
+ from .build import build
2
+ from .commit import commit
3
+ from .tests import tests
4
+ from .session import session
5
+ import click
6
+ from launchable.utils.click import GroupWithAlias
7
+
8
+
9
+ @click.group(cls=GroupWithAlias)
10
+ def record():
11
+ pass
12
+
13
+
14
+ record.add_command(build)
15
+ record.add_command(commit)
16
+ record.add_command(tests)
17
+ record.add_alias('test', tests) # for backward compatibility
18
+ record.add_command(session)
@@ -0,0 +1,103 @@
1
+ import re
2
+ import click
3
+ import subprocess
4
+ import json
5
+ import os
6
+ from ...utils.token import parse_token
7
+ from .commit import commit
8
+ from ...utils.env_keys import REPORT_ERROR_KEY
9
+ from ...utils.http_client import LaunchableClient
10
+
11
+
12
+ @click.command()
13
+ @click.option(
14
+ '--name',
15
+ 'build_name',
16
+ help='build name',
17
+ required=True,
18
+ type=str,
19
+ metavar='BUILD_NAME'
20
+ )
21
+ @click.option(
22
+ '--source',
23
+ help='path to local Git workspace, optionally prefixed by a label. '
24
+ ' like --source path/to/ws or --source main=path/to/ws',
25
+ default=["."],
26
+ metavar="REPO_NAME",
27
+ multiple=True
28
+ )
29
+ @click.pass_context
30
+ def build(ctx, build_name, source):
31
+ token, org, workspace = parse_token()
32
+
33
+ # This command accepts REPO_NAME=REPO_DIST and REPO_DIST
34
+ repos = [s.split('=') if re.match(r'[^=]+=[^=]+', s) else (s, s)
35
+ for s in source]
36
+ # TODO: if repo_dist is absolute path, warn the user that that's probably not what they want to do
37
+
38
+ for (name, repo_dist) in repos:
39
+ ctx.invoke(commit, source=repo_dist)
40
+
41
+ sources = [(
42
+ name,
43
+ subprocess.check_output(
44
+ "git rev-parse HEAD".split(), cwd=repo_dist
45
+ ).decode().replace("\n", "")
46
+ ) for name, repo_dist in repos]
47
+ submodules = []
48
+ for repo_name, repo_dist in repos:
49
+ # invoke git directly because dulwich's submodule feature was broken
50
+ submodule_stdouts = subprocess.check_output(
51
+ "git submodule status --recursive".split(), cwd=repo_dist
52
+ ).decode().splitlines()
53
+ for submodule_stdout in submodule_stdouts:
54
+ # the output is e.g.
55
+ # "+bbf213437a65e82dd6dda4391ecc5d598200a6ce sub1 (heads/master)"
56
+ matched = re.search(
57
+ r"^[\+\-U ](?P<hash>[a-f0-9]{40}) (?P<name>\w+)",
58
+ submodule_stdout
59
+ )
60
+ if matched:
61
+ hash = matched.group('hash')
62
+ name = matched.group('name')
63
+ if hash and name:
64
+ submodules.append((repo_name+"/"+name, hash))
65
+
66
+ # Note: currently becomes unique command args and submodules by the hash.
67
+ # But they can be conflict between repositories.
68
+ uniq_submodules = {hash: (name, hash)
69
+ for name, hash in sources + submodules}.values()
70
+
71
+ try:
72
+ commitHashes = [{
73
+ 'repositoryName': name,
74
+ 'commitHash': hash
75
+ } for name, hash in uniq_submodules]
76
+
77
+ if not (commitHashes[0]['repositoryName']
78
+ and commitHashes[0]['commitHash']):
79
+ exit('Please specify --source as --source .')
80
+
81
+ payload = {
82
+ "buildNumber": build_name,
83
+ "commitHashes": commitHashes
84
+ }
85
+
86
+ headers = {
87
+ "Content-Type": "application/json",
88
+ }
89
+
90
+ path = "/intake/organizations/{}/workspaces/{}/builds".format(
91
+ org, workspace)
92
+
93
+ client = LaunchableClient(token)
94
+ res = client.request("post", path, data=json.dumps(
95
+ payload).encode(), headers=headers)
96
+ print(res.status_code)
97
+ res.raise_for_status()
98
+
99
+ except Exception as e:
100
+ if os.getenv(REPORT_ERROR_KEY):
101
+ raise e
102
+ else:
103
+ print(e)
@@ -0,0 +1,59 @@
1
+ import datetime
2
+ import os
3
+ from typing import Callable, Dict
4
+ from junitparser import JUnitXml, Failure, Error, Skipped, TestCase, TestSuite
5
+ from ...testpath import TestPath
6
+
7
+
8
+ class CaseEvent:
9
+ EVENT_TYPE = "case"
10
+ TEST_SKIPPED = 2
11
+ TEST_PASSED = 1
12
+ TEST_FAILED = 0
13
+
14
+ # function that computes TestPath from a test case
15
+ # The 3rd argument is the report file path
16
+ TestPathBuilder = Callable[[TestCase, TestSuite, str], TestPath]
17
+
18
+ @staticmethod
19
+ def default_path_builder(base_path) -> TestPathBuilder:
20
+ """
21
+ Obtains a default TestPathBuilder that uses a base directory to relativize the file name
22
+ """
23
+
24
+ def f(case: TestCase, suite: TestSuite, report_file: str) -> TestPath:
25
+ classname = case.classname or suite._elem.attrib.get("classname")
26
+ filepath = case._elem.attrib.get(
27
+ "file") or suite._elem.attrib.get("filepath")
28
+ if filepath:
29
+ filepath = os.path.relpath(filepath, start=base_path)
30
+
31
+ test_path = []
32
+ if classname:
33
+ test_path.append({"type": "class", "name": classname})
34
+ if filepath:
35
+ test_path.append({"type": "file", "name": filepath})
36
+ if case.name:
37
+ test_path.append(
38
+ {"type": "testcase", "name": case.name, "_lineno": case._elem.attrib.get("lineno")})
39
+ return test_path
40
+
41
+ return f
42
+
43
+ @classmethod
44
+ def from_case_and_suite(cls, path_builder: TestPathBuilder, case: TestCase, suite: TestSuite, report_file: str, data: Dict = None) -> Dict:
45
+ "Builds a JSON representation of CaseEvent"
46
+
47
+ status = CaseEvent.TEST_FAILED if case.result and any(isinstance(case.result, s) for s in (
48
+ Failure, Error)) else CaseEvent.TEST_SKIPPED if isinstance(case.result, Skipped) else CaseEvent.TEST_PASSED
49
+
50
+ return {
51
+ "type": cls.EVENT_TYPE,
52
+ "testPath": path_builder(case, suite, report_file),
53
+ "duration": case.time,
54
+ "status": status,
55
+ "stdout": case.system_out or "",
56
+ "stderr": case.system_err or "",
57
+ "created_at": suite.timestamp or datetime.datetime.now(datetime.timezone.utc).isoformat(),
58
+ "data": data
59
+ }
@@ -0,0 +1,58 @@
1
+ import os
2
+
3
+ import click
4
+
5
+ from ...utils.env_keys import REPORT_ERROR_KEY
6
+ from ...utils.http_client import get_base_url
7
+ from ...utils.ingester_image import ingester_image
8
+ from ...utils.java import get_java_command
9
+
10
+ jar_file_path = os.path.normpath(os.path.join(
11
+ os.path.dirname(__file__), "../../jar/exe_deploy.jar"))
12
+
13
+
14
+ @click.command()
15
+ @click.option('--source',
16
+ help="repository path",
17
+ default=os.getcwd(),
18
+ type=click.Path(exists=True, file_okay=False),
19
+ )
20
+ @click.option('--executable',
21
+ help="collect commits with Jar or Docker",
22
+ type=click.Choice(['jar', 'docker']),
23
+ default='jar'
24
+ )
25
+ def commit(source, executable):
26
+ source = os.path.abspath(source)
27
+
28
+ if executable == 'jar':
29
+ try:
30
+ exec_jar(source)
31
+ except Exception as e:
32
+ if os.getenv(REPORT_ERROR_KEY):
33
+ raise e
34
+ else:
35
+ print(e)
36
+ elif executable == 'docker':
37
+ exec_docker(source)
38
+
39
+
40
+ def exec_jar(source):
41
+ java = get_java_command()
42
+
43
+ if not java:
44
+ exit("You need to install Java or try --executable docker")
45
+
46
+ base_url = get_base_url()
47
+ os.system(
48
+ "{} -jar {} ingest:commit -endpoint {} {}"
49
+ .format(java, jar_file_path, "{}/intake/".format(base_url), source))
50
+
51
+
52
+ def exec_docker(source):
53
+ base_url = get_base_url()
54
+ os.system(
55
+ "docker run -u $(id -u) -i --rm "
56
+ "-v {}:{} --env LAUNCHABLE_TOKEN {} ingest:commit -endpoint {} {}"
57
+ .format(source, source, ingester_image, "{}/intake/".format(base_url), source)
58
+ )
@@ -0,0 +1,42 @@
1
+ import click
2
+ import os
3
+
4
+ from ...utils.http_client import LaunchableClient
5
+ from ...utils.token import parse_token
6
+ from ...utils.env_keys import REPORT_ERROR_KEY
7
+
8
+
9
+ @click.command()
10
+ @click.option(
11
+ '--build',
12
+ 'build_name',
13
+ help='build name',
14
+ required=True,
15
+ type=str,
16
+ metavar='BUILD_NAME'
17
+ )
18
+ def session(build_name):
19
+ token, org, workspace = parse_token()
20
+
21
+ headers = {
22
+ "Content-Type": "application/json",
23
+ }
24
+
25
+ client = LaunchableClient(token)
26
+
27
+ try:
28
+ session_path = "/intake/organizations/{}/workspaces/{}/builds/{}/test_sessions".format(
29
+ org, workspace, build_name)
30
+ res = client.request("post", session_path, headers=headers)
31
+ res.raise_for_status()
32
+ session_id = res.json()['id']
33
+
34
+ # what we print here gets captured and passed to `--session` in later commands
35
+ click.echo("{}/{}".format(session_path, session_id))
36
+ return session_id
37
+
38
+ except Exception as e:
39
+ if os.getenv(REPORT_ERROR_KEY):
40
+ raise e
41
+ else:
42
+ click.echo(e, err=True)
@@ -0,0 +1,133 @@
1
+ import click
2
+ import json
3
+ import os
4
+ import glob
5
+ from junitparser import JUnitXml, TestSuite
6
+
7
+ from .case_event import CaseEvent
8
+ from ...utils.http_client import LaunchableClient
9
+ from ...utils.gzipgen import compress
10
+ from ...utils.token import parse_token
11
+ from ...utils.env_keys import REPORT_ERROR_KEY
12
+
13
+
14
+ @click.group()
15
+ @click.option(
16
+ '--base',
17
+ 'base_path',
18
+ help='(Advanced) base directory to make test names portable',
19
+ type=click.Path(exists=True, file_okay=False),
20
+ metavar="DIR",
21
+ )
22
+ @click.option(
23
+ '--session',
24
+ 'session_id',
25
+ help='Test session ID',
26
+ # validate session_id under debug mode,
27
+ required=os.getenv(REPORT_ERROR_KEY),
28
+ type=str,
29
+ )
30
+ @click.pass_context
31
+ def tests(context, base_path, session_id: str):
32
+ if not session_id:
33
+ click.echo(
34
+ "Session ID in --session is missing. It might be caused by Launchable API errors.", err=True)
35
+ # intentionally exiting with zero
36
+ return
37
+
38
+ # TODO: placed here to minimize invasion in this PR to reduce the likelihood of
39
+ # PR merge hell. This should be moved to a top-level class
40
+ class RecordTests:
41
+ @property
42
+ def path_builder(self) -> CaseEvent.TestPathBuilder:
43
+ """
44
+ This function, if supplied, is used to build a test path
45
+ that uniquely identifies a test case
46
+ """
47
+ return self._path_builder
48
+
49
+ @path_builder.setter
50
+ def path_builder(self, v: CaseEvent.TestPathBuilder):
51
+ self._path_builder = v
52
+
53
+ def __init__(self):
54
+ self.reports = []
55
+ self.path_builder = CaseEvent.default_path_builder(base_path)
56
+
57
+ def report(self, junit_report_file: str):
58
+ """Add one report file by its path name"""
59
+ self.reports.append(junit_report_file)
60
+
61
+ def scan(self, base, pattern):
62
+ """
63
+ Starting at the 'base' path, recursively add everything that matches the given GLOB pattern
64
+
65
+ scan('build/test-reports', '**/*.xml')
66
+ """
67
+ for t in glob.iglob(os.path.join(base, pattern), recursive=True):
68
+ self.report(t)
69
+
70
+ def run(self):
71
+ token, org, workspace = parse_token()
72
+
73
+ # generator that creates the payload incrementally
74
+ def payload():
75
+ yield '{"events":['
76
+ first = True # used to control ',' in printing
77
+
78
+ for p in self.reports:
79
+ # To understand JUnit XML format, https://llg.cubic.org/docs/junit/ is helpful
80
+ # TODO: robustness: what's the best way to deal with broken XML file, if any?
81
+ xml = JUnitXml.fromfile(p)
82
+
83
+ if isinstance(xml, JUnitXml):
84
+ testsuites = [suite for suite in xml]
85
+ elif isinstance(xml, TestSuite):
86
+ testsuites = [xml]
87
+ else:
88
+ # TODO: what is a Pythonesque way to do this?
89
+ assert False
90
+
91
+ for suite in testsuites:
92
+ for case in suite:
93
+ if not first:
94
+ yield ','
95
+ first = False
96
+
97
+ yield json.dumps(CaseEvent.from_case_and_suite(self.path_builder, case, suite, p))
98
+ yield ']}'
99
+
100
+ # TODO: this probably should be a flag
101
+ if True:
102
+ # generator adapter that prints the content
103
+ def printer(f):
104
+ for d in f:
105
+ print(d)
106
+ yield d
107
+ payload = printer(payload())
108
+
109
+ # str -> bytes then gzip compress
110
+ payload = (s.encode() for s in payload)
111
+ payload = compress(payload)
112
+
113
+ headers = {
114
+ "Content-Type": "application/json",
115
+ "Content-Encoding": "gzip",
116
+ }
117
+
118
+ client = LaunchableClient(token)
119
+
120
+ try:
121
+ res = client.request(
122
+ "post", "{}/events".format(session_id), data=payload, headers=headers)
123
+ res.raise_for_status()
124
+
125
+ print(res.status_code)
126
+
127
+ except Exception as e:
128
+ if os.getenv(REPORT_ERROR_KEY):
129
+ raise e
130
+ else:
131
+ print(e)
132
+
133
+ context.obj = RecordTests()
@@ -0,0 +1,166 @@
1
+ import click
2
+ import json
3
+ import os
4
+ from os.path import *
5
+ import glob
6
+ from typing import Callable, Union
7
+ from ..utils.click import PERCENTAGE
8
+ from ..utils.env_keys import REPORT_ERROR_KEY
9
+ from ..utils.http_client import LaunchableClient
10
+ from ..utils.token import parse_token
11
+ from ..testpath import TestPath
12
+
13
+ # TODO: rename files and function accordingly once the PR landscape
14
+
15
+
16
+ @click.group(help="Subsetting tests")
17
+ @click.option(
18
+ '--target',
19
+ 'target',
20
+ help='subsetting target from 0% to 100%',
21
+ required=True,
22
+ type=PERCENTAGE,
23
+ )
24
+ @click.option(
25
+ '--session',
26
+ 'session_id',
27
+ help='Test session ID',
28
+ type=str,
29
+ # validate session_id under debug mode
30
+ required=os.getenv(REPORT_ERROR_KEY),
31
+ )
32
+ @click.option(
33
+ '--base',
34
+ 'base_path',
35
+ help='(Advanced) base directory to make test names portable',
36
+ type=click.Path(exists=True, file_okay=False),
37
+ metavar="DIR",
38
+ )
39
+ @click.pass_context
40
+ def subset(context, target, session_id, base_path):
41
+ token, org, workspace = parse_token()
42
+
43
+ # TODO: placed here to minimize invasion in this PR to reduce the likelihood of
44
+ # PR merge hell. This should be moved to a top-level class
45
+ class Optimize:
46
+ # test_paths: List[TestPath] # doesn't work with Python 3.5
47
+
48
+ # Where we take TestPath, we also accept a path name as a string.
49
+ TestPathLike = Union[str, TestPath]
50
+
51
+ def __init__(self):
52
+ self.test_paths = []
53
+ # TODO: robustness improvement.
54
+ self._formatter = Optimize.default_formatter
55
+
56
+ @staticmethod
57
+ def default_formatter(x: TestPath):
58
+ """default formatter that's in line with to_test_path(str)"""
59
+ file_name = x[0]['name']
60
+ if base_path:
61
+ # default behavior consistent with default_path_builder's relative path handling
62
+ file_name = join(base_path, file_name)
63
+ return file_name
64
+
65
+ @property
66
+ def formatter(self) -> Callable[[TestPath], str]:
67
+ """
68
+ This function, if supplied, is used to format test names
69
+ from the format Launchable uses to the format test runners expect.
70
+ """
71
+ return self._formatter
72
+
73
+ @formatter.setter
74
+ def formatter(self, v: Callable[[TestPath], str]):
75
+ self._formatter = v
76
+
77
+ def test_path(self, path: TestPathLike):
78
+ """register one test"""
79
+ self.test_paths.append(self.to_test_path(path))
80
+
81
+ @staticmethod
82
+ def to_test_path(x: TestPathLike) -> TestPath:
83
+ """Convert input to a TestPath"""
84
+ if isinstance(x, str):
85
+ # default representation for a file
86
+ return [{'type': 'file', 'name': x}]
87
+ else:
88
+ return x
89
+
90
+ def scan(self, base: str, pattern: str, path_builder: Callable[[str], Union[TestPath, str, None]] = None):
91
+ """
92
+ Starting at the 'base' path, recursively add everything that matches the given GLOB pattern
93
+
94
+ scan('src/test/java', '**/*.java')
95
+
96
+ 'path_builder' is a function used to map file name into a custom test path.
97
+ It takes a single string argument that represents the portion matched to the glob pattern,
98
+ and its return value controls what happens to that file:
99
+ - skip a file by returning a False-like object
100
+ - if a str is returned, that's interpreted as a path name and
101
+ converted to the default test path representation. Typically, `os.path.join(base,file_name)
102
+ - if a TestPath is returned, that's added as is
103
+ """
104
+
105
+ if path_builder == None:
106
+ # default implementation of path_builder creates a file name relative to `source` so as not
107
+ # to be affected by the path
108
+ def default_path_builder(file_name):
109
+ file_name = join(base, file_name)
110
+ if base_path:
111
+ # relativize against `base_path` to make the path name portable
112
+ file_name = normpath(
113
+ relpath(file_name, start=base_path))
114
+ return file_name
115
+ path_builder = default_path_builder
116
+
117
+ for t in glob.iglob(join(base, pattern), recursive=True):
118
+ t = path_builder(t[len(base)+1:])
119
+ if t:
120
+ self.test_paths.append(self.to_test_path(t))
121
+
122
+ def run(self):
123
+ """called after tests are scanned to compute the optimized order"""
124
+
125
+ # When Error occurs, return the test name as it is passed.
126
+ output = self.test_paths
127
+
128
+ if not session_id:
129
+ # Session ID in --session is missing. It might be caused by Launchable API errors.
130
+ pass
131
+ else:
132
+ try:
133
+ headers = {
134
+ "Content-Type": "application/json",
135
+ }
136
+
137
+ payload = {
138
+ "testPaths": self.test_paths,
139
+ "target": target,
140
+ "session": {
141
+ # expecting just the last component, not the whole path
142
+ "id": os.path.basename(session_id)
143
+ }
144
+ }
145
+
146
+ path = "/intake/organizations/{}/workspaces/{}/subset".format(
147
+ org, workspace)
148
+
149
+ client = LaunchableClient(token)
150
+ res = client.request("post", path, data=json.dumps(
151
+ payload).encode(), headers=headers)
152
+ res.raise_for_status()
153
+
154
+ output = res.json()["testPaths"]
155
+ except Exception as e:
156
+ if os.getenv(REPORT_ERROR_KEY):
157
+ raise e
158
+ else:
159
+ click.echo(e, err=True)
160
+
161
+ # regardless of whether we managed to talk to the service
162
+ # we produce test names
163
+ for t in output:
164
+ click.echo(self.formatter(t))
165
+
166
+ context.obj = Optimize()
@@ -0,0 +1,59 @@
1
+ import os
2
+
3
+ import click
4
+ import platform
5
+
6
+ from ..utils.env_keys import REPORT_ERROR_KEY
7
+ from ..utils.http_client import LaunchableClient
8
+ from ..utils.token import parse_token
9
+ from ..utils.java import get_java_command
10
+ from ..version import __version__ as version
11
+
12
+
13
+ @click.command(name="verify")
14
+ def verify():
15
+ try:
16
+ if os.getenv("LAUNCHABLE_TOKEN") is None:
17
+ raise click.UsageError(click.style("Could not find the LAUNCHABLE_TOKEN environment variable. Please check if you "
18
+ "set it properly.", fg="red"))
19
+
20
+ token, org, workspace = parse_token()
21
+
22
+ headers = {
23
+ "Content-Type": "application/json",
24
+ }
25
+
26
+ path = "/intake/organizations/{}/workspaces/{}/verification".format(
27
+ org, workspace)
28
+
29
+ client = LaunchableClient(token)
30
+ res = client.request("get", path, headers=headers)
31
+
32
+ if res.status_code == 401:
33
+ raise click.UsageError(click.style("Authentication failed. Most likely the value for the LAUNCHABLE_TOKEN "
34
+ "environment variable is invalid.", fg="red"))
35
+
36
+ res.raise_for_status()
37
+
38
+ click.echo("Platform: " + platform.platform())
39
+ click.echo("Python version: " + platform.python_version())
40
+
41
+ java = get_java_command()
42
+
43
+ if java is None:
44
+ raise click.UsageError(click.style(
45
+ "Java is not installed. You need Java to use the Launchable CLI.", fg="red"))
46
+
47
+ click.echo("Java command: " + java)
48
+ click.echo("launchable version: " + version)
49
+
50
+ click.echo(click.style(
51
+ "Your CLI configuration is successfully verified \U0001f389", fg="green"))
52
+
53
+ except Exception as e:
54
+ if os.getenv(REPORT_ERROR_KEY):
55
+ raise e
56
+ else:
57
+ print(e)
58
+ import sys
59
+ sys.exit(1)
Binary file
File without changes
@@ -0,0 +1,61 @@
1
+ import os
2
+ import sys
3
+ from os.path import join
4
+
5
+ import click
6
+ from junitparser import TestCase, TestSuite
7
+
8
+ from . import launchable
9
+ from ..testpath import TestPath
10
+
11
+
12
+ def make_test_path(pkg, target) -> TestPath:
13
+ return [{'type': 'package', 'name': pkg}, {'type': 'target', 'name': target}]
14
+
15
+
16
+ @launchable.subset
17
+ def subset(client):
18
+ # Read targets from stdin, which generally looks like //foo/bar:zot
19
+ for label in sys.stdin:
20
+ # //foo/bar:zot -> //foo/bar & zot
21
+ if label.startswith('//'):
22
+ pkg, target = label.rstrip('\n').split(':')
23
+ # TODO: error checks and more robustness
24
+ client.test_path(make_test_path(pkg, target))
25
+
26
+ client.formatter = lambda x: x[0]['name'] + ":" + x[1]['name']
27
+ client.run()
28
+
29
+
30
+ @click.argument('workspace', required=True)
31
+ @launchable.record.tests
32
+ def record_tests(client, workspace):
33
+ """
34
+ Takes Bazel workspace, then report all its test results
35
+ """
36
+ base = join(workspace, 'bazel-testlogs')
37
+ if not os.path.exists(base):
38
+ exit("No such directory: %s" % base)
39
+
40
+ default_path_builder = client.path_builder
41
+
42
+ def f(case: TestCase, suite: TestSuite, report_file: str) -> TestPath:
43
+ # In Bazel, report path name contains package & target.
44
+ # for example, for //foo/bar:zot, the report file is at bazel-testlogs/foo/bar/zot/test.xml
45
+ # TODO: robustness
46
+ pkgNtarget = report_file[len(base)+1:-len("/test.xml")]
47
+
48
+ # last path component is the target, the rest is package
49
+ # TODO: does this work correctly when on Windows?
50
+ path = make_test_path(os.path.dirname(pkgNtarget),
51
+ os.path.basename(pkgNtarget))
52
+
53
+ # let the normal path building kicks in
54
+ path.extend(default_path_builder(case, suite, report_file))
55
+ return path
56
+
57
+ client.path_builder = f
58
+
59
+ client.scan(base, '**/test.xml')
60
+
61
+ client.run()
@@ -0,0 +1,25 @@
1
+ #
2
+ # The most bare-bone versions of the test runner support
3
+ #
4
+ import click
5
+ import sys
6
+ from . import launchable
7
+
8
+
9
+ @launchable.subset
10
+ def subset(client):
11
+ # read lines as test file names
12
+ for t in sys.stdin:
13
+ client.test_path(t)
14
+ client.run()
15
+
16
+
17
+ @click.argument('reports', required=True, nargs=-1)
18
+ @launchable.record.tests
19
+ def record_tests(client, reports):
20
+ # here we are implicitly assuming that test reports we read, combined with the default path builder,
21
+ # produces test names that aligned with what `optimize_tests` function does above.
22
+ # TODO: use a custom path builder to ensure this is always the case. This is too fragile.
23
+ for r in reports:
24
+ client.report(r)
25
+ client.run()
@@ -0,0 +1,46 @@
1
+ import sys
2
+ import re
3
+ import click
4
+
5
+ from . import launchable
6
+ from ..testpath import TestPath
7
+
8
+
9
+ def make_test_path(cls, case) -> TestPath:
10
+ return [{'type': 'class', 'name': cls}, {'type': 'case', 'name': case}]
11
+
12
+
13
+ @launchable.subset
14
+ def subset(client):
15
+ # Read targets from stdin, which generally looks like //foo/bar:zot
16
+ cls = ''
17
+ for label in map(str.rstrip, sys.stdin):
18
+ # handle Google Test's --gtest_list_tests output
19
+ # FooTest.
20
+ # Bar
21
+ # Baz
22
+ gtest_class = re.match(r'^([^\.]+)\.', label)
23
+ if gtest_class:
24
+ cls = gtest_class.group(1)
25
+ gtest_case = re.match(r'^ ([^ ]+)', label)
26
+ if gtest_case and cls:
27
+ case = gtest_case.group(1)
28
+ client.test_path(make_test_path(cls, case))
29
+
30
+ # handle ctest -N output
31
+ # Test #1: FooTest.Bar -> (FooTest, Bar)
32
+ ctest_result = re.match(r'^ Test #\d+: ([^ ]+)$', label)
33
+ if ctest_result:
34
+ (cls, case) = ctest_result.group(1).split('.')
35
+ client.test_path(make_test_path(cls, case))
36
+
37
+ client.formatter = lambda x: x[0]['name'] + "." + x[1]['name']
38
+ client.run()
39
+
40
+
41
+ @click.argument('report_dirs', required=True, nargs=-1)
42
+ @launchable.record.tests
43
+ def record_tests(client, report_dirs):
44
+ for root in report_dirs:
45
+ client.scan(root, "*.xml")
46
+ client.run()
@@ -0,0 +1,29 @@
1
+ import click
2
+ import os
3
+ from . import launchable
4
+
5
+
6
+ @click.argument('source_roots', required=True, nargs=-1)
7
+ @launchable.subset
8
+ def subset(client, source_roots):
9
+ def file2test(f: str):
10
+ if f.endswith('.java') or f.endswith('.scala') or f.endswith('.kt'):
11
+ f = f[:f.rindex('.')] # remove extension
12
+ # directory -> package name conversion
13
+ cls_name = f.replace(os.path.sep, '.')
14
+ return [{"type": "class", "name": cls_name}]
15
+ else:
16
+ return None
17
+
18
+ for root in source_roots:
19
+ client.scan(root, '**/*', file2test)
20
+
21
+ client.run()
22
+
23
+
24
+ @click.argument('source_roots', required=True, nargs=-1)
25
+ @launchable.record.tests
26
+ def record_tests(client, source_roots):
27
+ for root in source_roots:
28
+ client.scan(root, "*.xml")
29
+ client.run()
@@ -0,0 +1,31 @@
1
+ import click
2
+ import types
3
+ from launchable.commands.subset import subset as subset_cmd
4
+ from launchable.commands.record.tests import tests as record_tests_cmd
5
+
6
+
7
+ def cmdname(f):
8
+ """figure out the sub-command name from a test runner function"""
9
+
10
+ # a.b.cde -> cde
11
+ m = f.__module__
12
+ return m[m.rindex('.')+1:]
13
+
14
+
15
+ def wrap(f, group):
16
+ """
17
+ Wraps a 'plugin' function into a click command and registers it to the given group.
18
+
19
+ a plugin function receives the scanner object in its first argument
20
+ """
21
+ d = click.command(name=cmdname(f))
22
+ cmd = d(click.pass_obj(f))
23
+ group.add_command(cmd)
24
+ return cmd
25
+
26
+
27
+ def subset(f): return wrap(f, subset_cmd)
28
+
29
+
30
+ record = types.SimpleNamespace()
31
+ record.tests = lambda f: wrap(f, record_tests_cmd)
@@ -0,0 +1,44 @@
1
+ import click
2
+ import os
3
+ import sys
4
+ from . import launchable
5
+
6
+
7
+ @click.argument('files', required=True, nargs=-1)
8
+ @launchable.subset
9
+ def subset(client, files):
10
+ def parse(fname: str):
11
+ '''
12
+ Scan a file, directory full of *.rb, or @FILE
13
+ '''
14
+ if os.path.isdir(fname):
15
+ client.scan(fname, '**/*_test.rb')
16
+ elif fname == '@-':
17
+ # read stdin
18
+ for l in sys.stdin:
19
+ parse(l)
20
+ elif fname.startswith('@'):
21
+ # read response file
22
+ with open(fname[1:]) as f:
23
+ for l in f:
24
+ parse(l)
25
+ else:
26
+ # assume it's a file
27
+ client.test(fname)
28
+
29
+ for f in files:
30
+ parse(f)
31
+
32
+ client.run()
33
+
34
+
35
+ @click.argument('report_dirs', required=True, nargs=-1)
36
+ @launchable.record.tests
37
+ def record_tests(client, report_dirs):
38
+ for root in report_dirs:
39
+ if os.path.isdir(root):
40
+ client.scan(root, "*.xml")
41
+ else:
42
+ client.report(root)
43
+
44
+ client.run()
launchable/testpath.py ADDED
@@ -0,0 +1,10 @@
1
+ from typing import Dict, List
2
+
3
+ # Path component is a node in a tree.
4
+ # It's the equivalent of a short file/directory name in a file system.
5
+ # In our abstraction, it's represented as arbitrary bag of attributes
6
+ TestPathComponent = Dict[str, str]
7
+
8
+ # TestPath is a full path to a node in a tree from the root
9
+ # It's the equivalent of an absolute file name in a file system
10
+ TestPath = List[TestPathComponent]
File without changes
@@ -0,0 +1,35 @@
1
+ import click
2
+
3
+ # click.Group has the notion of hidden commands but it doesn't allow us to easily add
4
+ # the same command under multiple names and hide all but one.
5
+
6
+
7
+ class GroupWithAlias(click.Group):
8
+ def __init__(self, name=None, commands=None, **attrs):
9
+ super().__init__(name, commands, **attrs)
10
+ self.aliases = {}
11
+
12
+ def get_command(self, ctx, cmd_name):
13
+ return super().get_command(ctx, cmd_name) or self.aliases.get(cmd_name)
14
+
15
+ def add_alias(self, name, cmd):
16
+ self.aliases[name] = cmd
17
+
18
+
19
+ class PercentageType(click.ParamType):
20
+ name = "percentage"
21
+
22
+ def convert(self, value: str, param, ctx):
23
+ try:
24
+ if value.endswith('%'):
25
+ x = float(value[:-1])/100
26
+ if 0 <= x <= 100:
27
+ return x
28
+ except ValueError:
29
+ pass
30
+
31
+ self.fail("Expected percentage like 50% but got '{}'".format(
32
+ value), param, ctx)
33
+
34
+
35
+ PERCENTAGE = PercentageType()
@@ -0,0 +1 @@
1
+ REPORT_ERROR_KEY = "LAUNCHABLE_REPORT_ERROR"
@@ -0,0 +1,42 @@
1
+ # MIT License, from https://github.com/leetreveil/gengzip
2
+ import time
3
+ import zlib
4
+ import struct
5
+ from builtins import int
6
+
7
+
8
+ def write32u(value):
9
+ return struct.pack('<L', value)
10
+
11
+
12
+ def write_gzip_header():
13
+ header = b''
14
+ header += b'\037\213' # magic header (0x1f, 0x8b)
15
+ header += b'\010' # compression method (deflate)
16
+ header += b'\000' # flags (not set)
17
+ header += write32u(int(time.time())) # file modification time
18
+ header += b'\002' # extra flags (maximum compression)
19
+ header += b'\377' # os type (unknown)
20
+ return header
21
+
22
+
23
+ def write_gzip_footer(crc, size):
24
+ footer = b''
25
+ footer += write32u(crc)
26
+ footer += write32u(size & 0xffffffff)
27
+ return footer
28
+
29
+
30
+ def compress(d, compresslevel=6):
31
+ crc = zlib.crc32(b'') & 0xffffffff
32
+ size = 0
33
+ yield write_gzip_header()
34
+ compress = zlib.compressobj(
35
+ compresslevel, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
36
+ for data in d:
37
+ crc = zlib.crc32(data, crc) & 0xffffffff
38
+ size += len(data)
39
+ compressed = compress.compress(data)
40
+ if len(compressed) > 0:
41
+ yield compressed
42
+ yield compress.flush() + write_gzip_footer(crc, size)
@@ -0,0 +1,29 @@
1
+ import requests
2
+ import os
3
+ import platform
4
+ from launchable.version import __version__
5
+
6
+
7
+ BASE_URL_KEY = "LAUNCHABLE_BASE_URL"
8
+ DEFAULT_BASE_URL = "https://api.mercury.launchableinc.com"
9
+
10
+
11
+ def get_base_url():
12
+ return os.getenv(BASE_URL_KEY) or DEFAULT_BASE_URL
13
+
14
+
15
+ class LaunchableClient:
16
+ def __init__(self, token, base_url="", http=requests):
17
+ self.base_url = base_url or get_base_url()
18
+ self.http = http
19
+ self.token = token
20
+
21
+ def request(self, method, path, **kwargs):
22
+ headers = kwargs.pop("headers")
23
+ return self.http.request(method, self.base_url + path, headers={**headers, **self._headers()}, **kwargs)
24
+
25
+ def _headers(self):
26
+ return {
27
+ "User-Agent": "Launchable/{} (Python {}, {})".format(__version__, platform.python_version(), platform.platform()),
28
+ 'Authorization': 'Bearer {}'.format(self.token)
29
+ }
@@ -0,0 +1,8 @@
1
+ # Launchable's ingester Docker image with tag
2
+ # If you need up-to-date image, please replace the image tag
3
+ # You can see the docker image tags at
4
+ # https://hub.docker.com/repository/registry-1.docker.io/launchableinc/ingester/tags
5
+ ingester_image = (
6
+ 'launchableinc/ingester:'
7
+ '976171f4005f8a1c6d0e706d20760890b44c5373'
8
+ )
@@ -0,0 +1,13 @@
1
+ import os
2
+ import subprocess
3
+
4
+
5
+ def get_java_command():
6
+ res = subprocess.run(["which", "java"], stdout=subprocess.DEVNULL)
7
+ if res.returncode == 0:
8
+ return "java"
9
+
10
+ if os.access(os.path.expandvars("$JAVA_HOME/bin/java"), os.X_OK):
11
+ return "$JAVA_HOME/bin/java"
12
+
13
+ return None
@@ -0,0 +1,12 @@
1
+ import os
2
+
3
+
4
+ def parse_token():
5
+ try:
6
+ token = os.environ["LAUNCHABLE_TOKEN"]
7
+ _, user, _ = token.split(":", 2)
8
+ org, workspace = user.split("/", 1)
9
+ except ValueError:
10
+ exit("Please set LAUNCHABLE_TOKEN environment variable \
11
+ to the Launchable API token")
12
+ return token, org, workspace
launchable/version.py ADDED
@@ -0,0 +1,7 @@
1
+ from pkg_resources import get_distribution, DistributionNotFound
2
+
3
+ try:
4
+ __version__ = get_distribution("launchable").version
5
+ except DistributionNotFound:
6
+ # package is not installed
7
+ pass
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.1
2
+ Name: launchable
3
+ Version: 1.0
4
+ Summary: Launchable CLI
5
+ Home-page: https://launchableinc.com/
6
+ Author: Launchable, Inc.
7
+ Author-email: info@launchableinc.com
8
+ License: Apache Software License v2
9
+ Platform: UNKNOWN
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.4
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: click (==7.1.2)
16
+ Requires-Dist: requests (==2.24.0)
17
+ Requires-Dist: junitparser (==1.6.3)
18
+ Requires-Dist: setuptools
19
+
20
+ # Installation
21
+
22
+ ```shell
23
+ pip3 install --user launchable
24
+ ```
25
+
26
+ This creates executable `~/.local/bin/launchable` that should be on your `PATH`. See [PEP-370](https://www.python.org/dev/peps/pep-0370/) for further details.
27
+
28
+ ## Set your API token
29
+
30
+ ```shell
31
+ export LAUNCHABLE_TOKEN=set_your_token
32
+ ```
33
+
34
+ # How to use
35
+ ## Basic usage
36
+ ### Record build and commit
37
+
38
+ Basic usage,
39
+
40
+ ```shell
41
+ launchable record build --name BUILD_ID --source .
42
+ ```
43
+
44
+ Or if you want to specify the repo name,
45
+
46
+ ```shell
47
+ launchable record build --name BUILD_ID --source REPO_NAME=REPO_DIST
48
+ ```
49
+
50
+ #### Example
51
+ ```shell
52
+ launchable record build --name 12345678 --source main=.
53
+ ```
54
+
55
+ ## Optional
56
+ ### Separate commit recording
57
+
58
+ Basically, `launchable record build` record commit data simultaneously. If you want to record commit individually, you could separate recording commit and build.
59
+
60
+ Using `launchable record build --without-commit` , the command surpress commit recoding.
61
+
62
+ ```shell
63
+ launchable record build --name 12345678 --source main=. --without-commit
64
+ ```
65
+
66
+ To record commit individually, use `record commit`.
67
+
68
+ ```shell
69
+ launchable record commit --source .
70
+ ```
71
+
72
+ ## Docker
73
+
74
+ You can get DockerImage from docker hub.
75
+ https://hub.docker.com/repository/docker/launchableinc/cli
76
+
77
+ ```sh
78
+ $ docker pull launchableinc/ingester:latest
79
+ $ docker run -it -e LAUNCHABLE_TOKEN=v1:launchableinc/reponame:xxxxx launchableinc/cli:latest launchable verify
80
+ Platform: Linux-5.4.39-linuxkit-x86_64-with-debian-10.5
81
+ Python version: 3.7.3
82
+ Java command: java
83
+ Your CLI configuration is successfully verified 🎉
84
+ ```
85
+
86
+ You can easily integrate it into your CircleCI jobs.
87
+
88
+ ```
89
+ launchable_verify:
90
+ docker:
91
+ - image: launchableinc/cli:latest
92
+ environment:
93
+ LAUNCHABLE_TOKEN: $LAUNCHABLE_TOKEN
94
+ steps:
95
+ - run:
96
+ name: launchable verify?
97
+ command: launchable verify || true
98
+ ```
99
+
100
+ # How to release
101
+ Create new release on Github, then Github Actions automatically uploads the module to PyPI.
102
+
103
+
104
+
@@ -0,0 +1,34 @@
1
+ launchable/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ launchable/__main__.py,sha256=fDNpN82v2-xnPaEd0AjpyNNmdu5UYaKpJ7YpYtlvFkQ,694
3
+ launchable/testpath.py,sha256=bU9F-lgfIOJHtjrD_rIa6Zai___bMMCW-1ecs7jiPGc,405
4
+ launchable/version.py,sha256=U5bX7Vtok-AC5Jy-SofS7Fo54MnRvxpbZQZdqcPup9A,197
5
+ launchable/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ launchable/commands/subset.py,sha256=jb68vd0zcNxLjhet8B8hUT9VFUSuo9spq2PEV-UYkkc,6191
7
+ launchable/commands/verify.py,sha256=s5YsEuZaU9D5Cve9C4m7ARr4DJmUB4bQ8ZBiH0fAC_c,1901
8
+ launchable/commands/record/__init__.py,sha256=VcoyNvceBtOwhTMVSasDAFHXrFqvmLOkHY4VxOKKcJI,400
9
+ launchable/commands/record/build.py,sha256=BUilujByvGaIuMmcLGiLJ1TET7iYI8iAnwf-ttTsjBU,3236
10
+ launchable/commands/record/case_event.py,sha256=NfyMggZSj47DOVS8MehMkm5xQLaR1XYuM4tI-qD93OE,2286
11
+ launchable/commands/record/commit.py,sha256=X6DtekrtYVQm-IKYOeJYySjWUSqqa_xzp5OH2BtHImM,1637
12
+ launchable/commands/record/session.py,sha256=i-eQ6nApoD4J-ClkOvvYcGlhjsyUEoBI_LyY304T1zw,1078
13
+ launchable/commands/record/tests.py,sha256=tYNBx9hmphflX2Nc7xIuG09gJToUKE5xSFHyGoax5mk,4447
14
+ launchable/jar/exe_deploy.jar,sha256=7xdsqzy9TbJM0guXGDNRmAJHUJMlEaudBFfBPM-HHqk,19929061
15
+ launchable/test_runners/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ launchable/test_runners/bazel.py,sha256=Pb_gTHSFYiDmjIm9MYT4HH4O871CeVApdB_dv_bK4Sw,1913
17
+ launchable/test_runners/generic.py,sha256=QCvPVJPlKCWbF9Vyz-eRx9wTtoIOru00W3yiI7Wwj9k,720
18
+ launchable/test_runners/googletest.py,sha256=5ZhyW3ut6Ea-bJongsMbtThjOQWlJnb_MVftF8D9Q7o,1370
19
+ launchable/test_runners/gradle.py,sha256=K21K1TKYEpagx_QgFHTguOUstxPf0BE3yB6-H8Qw22U,816
20
+ launchable/test_runners/launchable.py,sha256=3wHGMY_rUzL4AwViMmUzy8FZ4tnnuzIw9X79x7jS57c,760
21
+ launchable/test_runners/minitest.py,sha256=aehGdOfbhr4d_TJYGuVDy41UV2vUqD0wcvW_Zry5wro,1037
22
+ launchable/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ launchable/utils/click.py,sha256=85WIGrreiLA6FmZzUriRDoR1EHfWmATyjZhCf_JOnFU,973
24
+ launchable/utils/env_keys.py,sha256=GjN6YE_rNusCYHRxBlWq9q6DuISG61nZ3LQ1UpIxlu0,45
25
+ launchable/utils/gzipgen.py,sha256=GBbySBTi_0sBzuZCRnljsXv4XmMwBG5QuU_jGljNT4Q,1189
26
+ launchable/utils/http_client.py,sha256=dnmD2XWwzrrwTGJDI2gNQMWpKeF2lzT0_aH3fNVAzxo,888
27
+ launchable/utils/ingester_image.py,sha256=w6-Dpkp28hiQYEPa1uIBNTdQT16l_ivqOiav9dqwENM,329
28
+ launchable/utils/java.py,sha256=NM1YCfCe9CCtA9j78zlRp4dC73DUJXGcf7fkLKXFkys,300
29
+ launchable/utils/token.py,sha256=Iusuv7uDzdnUA5gaScEKnRnnGbRXlYCnl46QGAiViIA,333
30
+ launchable-1.0.dist-info/METADATA,sha256=oId-_JYyx8fvLYdkR7yi3myZMPbXmIV88-T5znaQyBE,2538
31
+ launchable-1.0.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
32
+ launchable-1.0.dist-info/entry_points.txt,sha256=ZS3XnDqeGasG5cNKGo0ALdOwjEaQdeBwFyExHYODKYE,57
33
+ launchable-1.0.dist-info/top_level.txt,sha256=-gCm7MM4z5ASDA24B4vAA2m4vY1MoxJggXIm12hAgNs,11
34
+ launchable-1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.36.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ launchable = launchable.__main__:main
3
+
@@ -0,0 +1 @@
1
+ launchable