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
|
import os
import re
import yaml
from .conda import conda, conda_env_load, conda_cmd_channels
from .utils import comment_find, git, pushd, sh
from configparser import ConfigParser
from glob import glob
DMFILE_RE = re.compile(r'^(?P<name>[A-z\-_l]+)(?:[=<>\!]+)?(?P<version>[A-z0-9. ]+)?') # noqa
DMFILE_INVALID_VERSION_RE = re.compile(r'[\ \!\@\#\$\%\^\&\*\(\)\-_]+')
DELIVERY_NAME_RE = re.compile(r'(?P<name>.*)[-_](?P<version>.*)[-_]py(?P<python_version>\d+)[-_.](?P<iteration>\d+)[-_.](?P<ext>.*)') # noqa
class EmptyPackageSpec(Exception):
pass
class InvalidPackageSpec(Exception):
pass
def dmfile(filename):
""" Return the contents of a file without comments
:param filename: string: path to file
:returns: list: of dicts, one per package
"""
result = []
with open(filename, 'r') as fp:
for line in fp:
line = line.strip()
comment_pos = comment_find(line)
if comment_pos >= 0:
line = line[:comment_pos].strip()
if not line:
continue
match = DMFILE_RE.match(line)
if match is None:
raise InvalidPackageSpec(f"'{line}'")
pkg = match.groupdict()
if pkg['version']:
invalid = DMFILE_INVALID_VERSION_RE.match(pkg['version'])
if invalid:
raise InvalidPackageSpec(f"'{line}'")
pkg['fullspec'] = line
result.append(pkg)
if not result:
raise EmptyPackageSpec("Nothing to do")
return result
def env_combine(filename, conda_env, conda_channels=[]):
""" Install packages listed in `filename` inside `conda_env`.
Packages are quote-escaped to prevent spurious file redirection.
:param filename: str: path to file
:param conda_env: str: conda environment name
:param conda_channels: list: channel URLs
:returns: None
:raises subprocess.CalledProcessError: via check_returncode method
"""
packages = []
for record in dmfile(filename):
packages.append(f"'{record['fullspec']}'")
packages_result = ' '.join([x for x in packages])
proc = conda('install', '-q', '-y',
'-n', conda_env,
conda_cmd_channels(conda_channels),
packages_result)
if proc.stderr:
print(proc.stderr.decode())
proc.check_returncode()
def testable_packages(filename, prefix):
""" Scan a mini/anaconda prefix for unpacked packages matching versions
requested by dmfile.
:param filename: str: path to file
:param prefix: str: path to conda root directory (aka prefix)
:returns: dict: git commit hash and repository URL information
"""
pkgdir = os.path.join(prefix, 'pkgs')
paths = []
for record in dmfile(filename):
# Reconstruct ${package}-${version} format (when possible)
pattern = f"{record['name']}-"
if record['version']:
pattern += record['version']
pattern += '*'
# Record path to extracted package
path = ''.join([x for x in glob(os.path.join(pkgdir, pattern))
if os.path.isdir(x)])
paths.append(path)
for root in paths:
info_d = os.path.join(root, 'info')
recipe_d = os.path.join(info_d, 'recipe')
git_log = os.path.join(info_d, 'git')
if not os.path.exists(git_log):
continue
with open(os.path.join(recipe_d, 'meta.yaml')) as yaml_data:
source = yaml.load(yaml_data.read(),
Loader=yaml.SafeLoader)['source']
if not isinstance(source, dict):
continue
repository = source['git_url']
head = open(git_log).readlines()[1].split()[1]
yield dict(repo=repository, commit=head)
def integration_test(pkg_data, conda_env, results_root='.'):
"""
:param pkg_data: dict: data returned by `testable_packages` method
:param conda_env: str: conda environment name
:param results_root: str: path to store XML reports
:returns: str: path to XML report
:raises subprocess.CalledProcessError: via check_returncode method
"""
results = ''
results_root = os.path.abspath(os.path.join(results_root, 'results'))
src_root = os.path.abspath('src')
if not os.path.exists(src_root):
os.mkdir(src_root, 0o755)
with pushd(src_root) as _:
repo_root = os.path.basename(pkg_data['repo']).replace('.git', '')
if not os.path.exists(repo_root):
git(f"clone --recursive {pkg_data['repo']} {repo_root}")
with pushd(repo_root) as _:
git(f"checkout {pkg_data['commit']}")
force_xunit2()
with conda_env_load(conda_env):
results = os.path.abspath(os.path.join(results_root,
repo_root,
'result.xml'))
proc_pip = sh("pip", "install -e .[test] pytest ci_watson")
proc_pip_stderr = proc_pip.stderr.decode()
if proc_pip.returncode:
print(proc_pip.stderr.decode())
# Setuptools is busted in conda. Ignore errors related to
# easy_install.pth
if 'easy-install.pth' not in proc_pip_stderr:
proc_pip.check_returncode()
proc_pytest = sh("pytest", f"-v --junitxml={results}")
if proc_pytest.returncode:
print(proc_pytest.stderr.decode())
return results
def force_xunit2(project='.'):
configs = [os.path.abspath(os.path.join(project, x))
for x in ['pytest.ini', 'setup.cfg']]
create_config = not all([os.path.exists(x) for x in configs])
if create_config:
data = """[pytest]\njunit_family = xunit2\n"""
with open('pytest.ini', 'w+') as cfg:
cfg.write(data)
return
for filename in configs:
if not os.path.exists(filename):
continue
cfg = ConfigParser()
cfg.read(filename)
cfg['tool:pytest']['junit_family'] = 'xunit2'
cfg.write(filename)
break
|