forked from open-traffic-generator/snappi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
do.py
322 lines (256 loc) · 7.79 KB
/
do.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
import fnmatch
import os
import re
import sys
import shutil
import subprocess
import platform
os.environ["GOPATH"] = os.path.join(
os.path.dirname(os.path.abspath(__file__)), ".local"
)
os.environ["PATH"] = os.environ["PATH"] + ":{0}/go/bin:{0}/bin".format(os.environ["GOPATH"])
def arch():
return getattr(platform.uname(), "machine", platform.uname()[-1]).lower()
def on_arm():
return arch() in ["arm64", "aarch64"]
def on_x86():
return arch() == "x86_64"
def on_linux():
print("The platform is {}".format(sys.platform))
return "linux" in sys.platform
def get_go():
version = "1.17"
targz = None
if on_arm():
targz = "go" + version + ".linux-arm64.tar.gz"
elif on_x86():
targz = "go" + version + ".linux-amd64.tar.gz"
else:
print("host architecture not supported")
return
if not os.path.exists(os.environ["GOPATH"]):
os.mkdir(os.environ["GOPATH"])
print("Installing Go ...")
cmd = "go version 2> /dev/null || curl -kL https://dl.google.com/go/" + targz
cmd += " | tar -C " + os.environ["GOPATH"] + " -xzf -"
run([cmd])
def get_go_deps():
print("Getting Go libraries for grpc / protobuf ...")
cmd = "GO111MODULE=on go get -v"
run(
[
cmd + " google.golang.org/grpc/cmd/[email protected]",
cmd + " google.golang.org/protobuf/cmd/[email protected]",
cmd + " golang.org/x/tools/cmd/goimports"
]
)
def get_protoc():
version = "3.17.3"
zipfile = None
if on_arm():
zipfile = "protoc-" + version + "-linux-aarch_64.zip"
elif on_x86():
zipfile = "protoc-" + version + "-linux-x86_64.zip"
else:
print("host architecture not supported")
return
print("Installing protoc ...")
cmd = "protoc --version 2> /dev/null || ( curl -kL -o ./protoc.zip "
cmd += "https://github.com/protocolbuffers/protobuf/releases/download/v"
cmd += version + "/" + zipfile
cmd += ' && unzip ./protoc.zip -d ' + os.environ["GOPATH"]
cmd += ' && rm -rf ./protoc.zip )'
run([cmd])
def setup_ext():
if on_linux():
get_go()
get_protoc()
get_go_deps()
else:
print("Skipping go and protoc installation on non-linux platform ...")
def setup():
run(
[
py() + " -m pip install --upgrade pip",
py() + " -m pip install --upgrade virtualenv",
py() + " -m virtualenv .env",
]
)
def init():
run(
[
py() + " -m pip install -r requirements.txt",
]
)
def lint():
paths = [pkg()[0], "tests", "setup.py", "do.py"]
run(
[
py() + " -m black " + " ".join(paths),
py() + " -m flake8 " + " ".join(paths),
py() + " -m pytype " + " ".join(paths),
]
)
def test():
run(
[
py() + " -m pip install pytest-cov",
py() + " -m pytest -sv --cov=snappi --cov-report term --cov-report html:cov_report",
]
)
import re
coverage_threshold = 60
with open("./cov_report/index.html") as fp:
out = fp.read()
result = re.findall(r"data-ratio.*?[>](\d+)\b", out)[0]
if int(result) < coverage_threshold:
raise Exception("Coverage thresold[{0}] is NOT achieved[{1}]".format(coverage_threshold, result))
else:
print("Coverage thresold[{0}] is achieved[{1}]".format(coverage_threshold, result))
go_coverage_threshold = 0
# TODO: not able to run the test from main directory
os.chdir("gosnappi")
try:
run([
"go test ./... -v -coverprofile coverage.txt | tee coverage.out"
], raise_exception=True, msg="Exception occured while running the tests")
finally:
os.chdir("..")
with open("gosnappi/coverage.out") as fp:
out = fp.read()
result = re.findall(r"coverage:.*\s(\d+)", out)[0]
if int(result) < go_coverage_threshold:
raise Exception(
"Go tests achieved {1}% which is less than Coverage thresold {0}%,".format(
go_coverage_threshold, result))
else:
print(
"Go tests achieved {1}% ,Coverage thresold {0}%".format(
go_coverage_threshold, result))
def dist():
clean()
run(
[
py() + " setup.py sdist bdist_wheel --universal",
]
)
print(os.listdir("dist"))
def install():
wheel = "{}-{}-py2.py3-none-any.whl".format(*pkg())
run(
[
"{} -m pip install --upgrade --force-reinstall {}[testing]".format(
py(), os.path.join("dist", wheel)
),
]
)
def release():
run(
[
py() + " -m pip install --upgrade twine",
"{} -m twine upload -u {} -p {} dist/*".format(
py(),
os.environ["PYPI_USERNAME"],
os.environ["PYPI_PASSWORD"],
),
]
)
def clean():
"""
Removes filenames or dirnames matching provided patterns.
"""
pwd_patterns = [
".pytype",
"dist",
"build",
"*.egg-info",
]
recursive_patterns = [
".pytest_cache",
"__pycache__",
"*.pyc",
"*.log",
]
for pattern in pwd_patterns:
for path in pattern_find(".", pattern, recursive=False):
rm_path(path)
for pattern in recursive_patterns:
for path in pattern_find(".", pattern, recursive=True):
rm_path(path)
def version():
print(pkg()[-1])
def pkg():
"""
Returns name of python package in current directory and its version.
"""
try:
return pkg.pkg
except AttributeError:
with open("setup.py") as f:
out = f.read()
name = re.findall(r"pkg_name = \"(.+)\"", out)[0]
version = re.findall(r"version = \"(.+)\"", out)[0]
pkg.pkg = (name, version)
return pkg.pkg
def rm_path(path):
"""
Removes a path if it exists.
"""
if os.path.exists(path):
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
def pattern_find(src, pattern, recursive=True):
"""
Recursively searches for a dirname or filename matching given pattern and
returns all the matches.
"""
matches = []
if not recursive:
for name in os.listdir(src):
if fnmatch.fnmatch(name, pattern):
matches.append(os.path.join(src, name))
return matches
for dirpath, dirnames, filenames in os.walk(src):
for names in [dirnames, filenames]:
for name in names:
if fnmatch.fnmatch(name, pattern):
matches.append(os.path.join(dirpath, name))
return matches
def py():
"""
Returns path to python executable to be used.
"""
try:
return py.path
except AttributeError:
py.path = os.path.join(".env", "bin", "python")
if not os.path.exists(py.path):
py.path = sys.executable
# since some paths may contain spaces
py.path = '"' + py.path + '"'
return py.path
def run(commands, raise_exception=False, msg=None):
"""
Executes a list of commands in a native shell and raises exception upon
failure.
"""
try:
for cmd in commands:
print(cmd)
if sys.platform != "win32":
cmd = cmd.encode("utf-8", errors="ignore")
subprocess.check_call(cmd, shell=True)
except Exception as e:
if raise_exception:
raise Exception(msg)
print(e)
sys.exit(1)
def main():
if len(sys.argv) >= 2:
globals()[sys.argv[1]](*sys.argv[2:])
else:
print("usage: python do.py [args]")
if __name__ == "__main__":
main()