userver: en/testsuite/plugins/envinfo.py Source File
Loading...
Searching...
No Matches
envinfo.py
1import socket
2import subprocess
3import sys
4
5from testsuite.utils import subprocess_helper
6
7BASE_BRANCH = 'develop'
8UPSTREAM_REMOTES = ('upstream', 'origin')
9
10
11def pytest_addoption(parser):
12 parser.addoption(
13 '--envinfo-no-git',
14 action='store_true',
15 help='Do not print git-related information in test report header.',
16 )
17
18
19def pytest_report_header(config):
20 headers = [
21 'args: {}'.format(' '.join(sys.argv)),
22 f'hostname: {socket.gethostname()}',
23 ]
24 if not config.option.envinfo_no_git:
25 headers.extend(get_vcs_info())
26 return headers
27
28
29def get_vcs_info() -> list[str]:
30 try:
31 commit = subprocess_helper.sh('git', 'rev-parse', 'HEAD')
32 branch = subprocess_helper.sh(
33 'git',
34 'rev-parse',
35 '--abbrev-ref',
36 'HEAD',
37 )
38 except (subprocess.CalledProcessError, FileNotFoundError):
39 return []
40 merge_base = git_merge_base()
41 items = [f'branch {branch}']
42 if git_is_clean():
43 items.append(commit)
44 else:
45 items.append(f'{commit}*')
46 if merge_base:
47 items.append(f'base {merge_base}')
48 return ['git: ' + ', '.join(items)]
49
50
51def git_is_clean() -> bool:
52 try:
53 subprocess_helper.sh(
54 'git',
55 'diff',
56 '--ignore-submodules=dirty',
57 '--quiet',
58 )
59 except subprocess.CalledProcessError:
60 return False
61 return True
62
63
64def git_merge_base() -> str | None:
65 """Try to guess merge base for current commit."""
66 try:
67 remotes = set(subprocess_helper.sh('git', 'remote').splitlines())
68 for remote in UPSTREAM_REMOTES:
69 if remote in remotes:
70 return subprocess_helper.sh(
71 'git',
72 'merge-base',
73 f'{remote}/{BASE_BRANCH}',
74 'HEAD',
75 )
76 except subprocess.CalledProcessError:
77 pass
78 return None