Skip to content

Commit a112367

Browse files
committed
pyupgrade to 3.6+ syntax
1 parent eabe896 commit a112367

File tree

4 files changed

+75
-53
lines changed

4 files changed

+75
-53
lines changed

cwltest/__init__.py

Lines changed: 36 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,8 @@
3737
UNSUPPORTED_FEATURE = 33
3838
DEFAULT_TIMEOUT = 600 # 10 minutes
3939

40-
if sys.version_info < (3, 0):
41-
import subprocess32 as subprocess # nosec
42-
from pipes import quote
43-
else:
44-
import subprocess # nosec
45-
from shlex import quote
40+
import subprocess # nosec
41+
from shlex import quote
4642

4743
templock = threading.Lock()
4844

@@ -55,7 +51,7 @@ def prepare_test_command(
5551
cwd, # type: str
5652
verbose=False, # type: bool
5753
): # type: (...) -> List[str]
58-
""" Turn the test into a command line. """
54+
"""Turn the test into a command line."""
5955
test_command = [tool]
6056
test_command.extend(args)
6157

@@ -72,26 +68,26 @@ def prepare_test_command(
7268
outdir = tempfile.mkdtemp(prefix=os.path.abspath(os.path.curdir))
7369
test_command.extend(
7470
[
75-
"--tmp-outdir-prefix={}".format(outdir),
76-
"--tmpdir-prefix={}".format(outdir),
71+
f"--tmp-outdir-prefix={outdir}",
72+
f"--tmpdir-prefix={outdir}",
7773
]
7874
)
7975
else:
8076
outdir = tempfile.mkdtemp()
81-
test_command.extend(["--outdir={}".format(outdir)])
77+
test_command.extend([f"--outdir={outdir}"])
8278
if not verbose:
8379
test_command.extend(["--quiet"])
8480

8581
cwd = schema_salad.ref_resolver.file_uri(cwd)
8682
toolpath = test["tool"]
8783
if toolpath.startswith(cwd):
88-
toolpath = toolpath[len(cwd)+1:]
84+
toolpath = toolpath[len(cwd) + 1 :]
8985
test_command.extend([os.path.normcase(toolpath)])
9086

9187
jobpath = test.get("job")
9288
if jobpath:
9389
if jobpath.startswith(cwd):
94-
jobpath = jobpath[len(cwd)+1:]
90+
jobpath = jobpath[len(cwd) + 1 :]
9591
test_command.append(os.path.normcase(jobpath))
9692
return test_command
9793

@@ -108,7 +104,7 @@ def run_test(
108104
global templock
109105

110106
out = {} # type: Dict[str,Any]
111-
outdir = outstr = outerr = u""
107+
outdir = outstr = outerr = ""
112108
test_command = [] # type: List[str]
113109
duration = 0.0
114110
prefix = ""
@@ -145,7 +141,13 @@ def run_test(
145141

146142
start_time = time.time()
147143
stderr = subprocess.PIPE if not args.verbose else None
148-
process = subprocess.Popen(test_command, stdout=subprocess.PIPE, stderr=stderr, universal_newlines=True, cwd=cwd) # nosec
144+
process = subprocess.Popen( # nosec
145+
test_command,
146+
stdout=subprocess.PIPE,
147+
stderr=stderr,
148+
universal_newlines=True,
149+
cwd=cwd,
150+
)
149151
outstr, outerr = process.communicate(timeout=timeout)
150152
return_code = process.poll()
151153
duration = time.time() - start_time
@@ -167,25 +169,25 @@ def run_test(
167169
if test.get("should_fail", False):
168170
return TestResult(0, outstr, outerr, duration, args.classname)
169171
_logger.error(
170-
u"""Test %i failed: %s""",
172+
"""Test %i failed: %s""",
171173
test_number,
172174
" ".join([quote(tc) for tc in test_command]),
173175
)
174176
_logger.error(test.get("doc"))
175177
if err.returncode == UNSUPPORTED_FEATURE:
176-
_logger.error(u"Does not support required feature")
178+
_logger.error("Does not support required feature")
177179
else:
178-
_logger.error(u"Returned non-zero")
180+
_logger.error("Returned non-zero")
179181
_logger.error(outerr)
180182
return TestResult(1, outstr, outerr, duration, args.classname, str(err))
181183
except (yamlscanner.ScannerError, TypeError) as err:
182184
_logger.error(
183-
u"""Test %i failed: %s""",
185+
"""Test %i failed: %s""",
184186
test_number,
185-
u" ".join([quote(tc) for tc in test_command]),
187+
" ".join([quote(tc) for tc in test_command]),
186188
)
187189
_logger.error(outstr)
188-
_logger.error(u"Parse error %s", str(err))
190+
_logger.error("Parse error %s", str(err))
189191
_logger.error(outerr)
190192
except KeyboardInterrupt:
191193
_logger.error(
@@ -204,7 +206,7 @@ def run_test(
204206
return TestResult(2, outstr, outerr, timeout, args.classname, "Test timed out")
205207
finally:
206208
if process is not None and process.returncode is None:
207-
_logger.error(u"""Terminating lingering process""")
209+
_logger.error("""Terminating lingering process""")
208210
process.terminate()
209211
for _ in range(0, 3):
210212
time.sleep(1)
@@ -217,24 +219,24 @@ def run_test(
217219

218220
if test.get("should_fail", False):
219221
_logger.warning(
220-
u"""Test %i failed: %s""",
222+
"""Test %i failed: %s""",
221223
test_number,
222-
u" ".join([quote(tc) for tc in test_command]),
224+
" ".join([quote(tc) for tc in test_command]),
223225
)
224226
_logger.warning(test.get("doc"))
225-
_logger.warning(u"Returned zero but it should be non-zero")
227+
_logger.warning("Returned zero but it should be non-zero")
226228
return TestResult(1, outstr, outerr, duration, args.classname)
227229

228230
try:
229231
compare(test.get("output"), out)
230232
except CompareFail as ex:
231233
_logger.warning(
232-
u"""Test %i failed: %s""",
234+
"""Test %i failed: %s""",
233235
test_number,
234-
u" ".join([quote(tc) for tc in test_command]),
236+
" ".join([quote(tc) for tc in test_command]),
235237
)
236238
_logger.warning(test.get("doc"))
237-
_logger.warning(u"Compare failure %s", ex)
239+
_logger.warning("Compare failure %s", ex)
238240
fail_message = str(ex)
239241

240242
if outdir:
@@ -345,13 +347,14 @@ def arg_parser(): # type: () -> argparse.ArgumentParser
345347

346348
pkg = pkg_resources.require("cwltest")
347349
if pkg:
348-
ver = u"%s %s" % (sys.argv[0], pkg[0].version)
350+
ver = f"{sys.argv[0]} {pkg[0].version}"
349351
else:
350-
ver = u"%s %s" % (sys.argv[0], "unknown version")
352+
ver = "{} {}".format(sys.argv[0], "unknown version")
351353
parser.add_argument("--version", action="version", version=ver)
352354

353355
return parser
354356

357+
355358
def expand_number_range(nr: str) -> List[int]:
356359
ans: List[int] = []
357360
for s in nr.split(","):
@@ -362,6 +365,7 @@ def expand_number_range(nr: str) -> List[int]:
362365
ans.append(int(s) - 1)
363366
return ans
364367

368+
365369
def main(): # type: () -> int
366370

367371
args = arg_parser().parse_args(sys.argv[1:])
@@ -558,12 +562,12 @@ def main(): # type: () -> int
558562
else:
559563
color = "yellow"
560564

561-
with open("{}/{}.json".format(args.badgedir, t), "w") as out:
565+
with open(f"{args.badgedir}/{t}.json", "w") as out:
562566
out.write(
563567
json.dumps(
564568
{
565-
"subject": "{}".format(t),
566-
"status": "{}%".format(percent),
569+
"subject": f"{t}",
570+
"status": f"{percent}%",
567571
"color": color,
568572
}
569573
)

cwltest/tests/test_categories.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,17 @@
88
import defusedxml.ElementTree as ET
99
import schema_salad.ref_resolver
1010

11+
1112
class TestCategories(unittest.TestCase):
1213
maxDiff = None
1314

1415
def test_unsupported_with_required_tests(self):
15-
args = ["--test", schema_salad.ref_resolver.file_uri(get_data("tests/test-data/required-unsupported.yml"))]
16+
args = [
17+
"--test",
18+
schema_salad.ref_resolver.file_uri(
19+
get_data("tests/test-data/required-unsupported.yml")
20+
),
21+
]
1622
try:
1723
cwd = os.getcwd()
1824
os.chdir(get_data("tests/test-data/"))
@@ -47,7 +53,12 @@ def test_unsupported_with_required_tests(self):
4753
)
4854

4955
def test_unsupported_with_optional_tests(self):
50-
args = ["--test", schema_salad.ref_resolver.file_uri(get_data("tests/test-data/optional-unsupported.yml"))]
56+
args = [
57+
"--test",
58+
schema_salad.ref_resolver.file_uri(
59+
get_data("tests/test-data/optional-unsupported.yml")
60+
),
61+
]
5162
error_code, stdout, stderr = run_with_mock_cwl_runner(args)
5263
self.assertEqual(error_code, 0)
5364
self.assertEqual(
@@ -58,7 +69,12 @@ def test_unsupported_with_optional_tests(self):
5869
)
5970

6071
def test_error_with_optional_tests(self):
61-
args = ["--test", schema_salad.ref_resolver.file_uri(get_data("tests/test-data/optional-error.yml"))]
72+
args = [
73+
"--test",
74+
schema_salad.ref_resolver.file_uri(
75+
get_data("tests/test-data/optional-error.yml")
76+
),
77+
]
6278
error_code, stdout, stderr = run_with_mock_cwl_runner(args)
6379
self.assertEqual(error_code, 1)
6480
self.assertIn("1 failures", stderr)
@@ -67,7 +83,9 @@ def test_category_in_junit_xml(self):
6783
junit_xml_report = get_data("tests/test-data/junit-report.xml")
6884
args = [
6985
"--test",
70-
schema_salad.ref_resolver.file_uri(get_data("tests/test-data/optional-error.yml")),
86+
schema_salad.ref_resolver.file_uri(
87+
get_data("tests/test-data/optional-error.yml")
88+
),
7189
"--junit-xml",
7290
junit_xml_report,
7391
]

cwltest/tests/test_prepare.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55

66
class TestPrepareCommand(unittest.TestCase):
7-
""" Test prepare_test_command() """
7+
"""Test prepare_test_command()"""
88

99
def test_unix_relative_path(self):
10-
""" Confirm unix style to windows style path corrections. """
10+
"""Confirm unix style to windows style path corrections."""
1111
command = prepare_test_command(
1212
tool="cwl-runner",
1313
args=[],
@@ -19,7 +19,7 @@ def test_unix_relative_path(self):
1919
"job": "v1.0/bwa-mem-job.json",
2020
"tags": ["required"],
2121
},
22-
cwd=os.getcwd()
22+
cwd=os.getcwd(),
2323
)
2424
if os.name == "nt":
2525
self.assertEqual(command[3], "v1.0\\bwa-mem-tool.cwl")

cwltest/utils.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
REQUIRED = "required"
88

99

10-
class TestResult(object):
10+
class TestResult:
1111

1212
"""Encapsulate relevant test result data."""
1313

@@ -30,12 +30,12 @@ def __init__(
3030

3131
def create_test_case(self, test):
3232
# type: (Dict[Text, Any]) -> junit_xml.TestCase
33-
doc = test.get(u"doc", "N/A").strip()
33+
doc = test.get("doc", "N/A").strip()
3434
if test.get("tags"):
3535
category = ", ".join(test["tags"])
3636
else:
3737
category = REQUIRED
38-
short_name = test.get(u"short_name")
38+
short_name = test.get("short_name")
3939
case = junit_xml.TestCase(
4040
doc,
4141
elapsed_sec=self.duration,
@@ -53,12 +53,12 @@ class CompareFail(Exception):
5353
@classmethod
5454
def format(cls, expected, actual, cause=None):
5555
# type: (Any, Any, Any) -> CompareFail
56-
message = u"expected: %s\ngot: %s" % (
56+
message = "expected: {}\ngot: {}".format(
5757
json.dumps(expected, indent=4, sort_keys=True),
5858
json.dumps(actual, indent=4, sort_keys=True),
5959
)
6060
if cause:
61-
message += u"\ncaused by: %s" % cause
61+
message += "\ncaused by: %s" % cause
6262
return cls(message)
6363

6464

@@ -84,7 +84,7 @@ def compare_location(expected, actual):
8484
raise CompareFail.format(
8585
expected,
8686
actual,
87-
u"%s does not end with %s" % (actual[comp], expected[comp]),
87+
f"{actual[comp]} does not end with {expected[comp]}",
8888
)
8989

9090

@@ -98,7 +98,7 @@ def compare_contents(expected, actual):
9898
expected,
9999
actual,
100100
json.dumps(
101-
u"Output file contents do not match: actual '%s' is not equal to expected '%s'"
101+
"Output file contents do not match: actual '%s' is not equal to expected '%s'"
102102
% (actual_contents, expected_contents)
103103
),
104104
)
@@ -111,7 +111,7 @@ def check_keys(keys, expected, actual):
111111
compare(expected.get(k), actual.get(k))
112112
except CompareFail as e:
113113
raise CompareFail.format(
114-
expected, actual, u"field '%s' failed comparison: %s" % (k, str(e))
114+
expected, actual, f"field '{k}' failed comparison: {str(e)}"
115115
)
116116

117117

@@ -128,11 +128,11 @@ def compare_directory(expected, actual):
128128
# type: (Dict[str,Any], Dict[str,Any]) -> None
129129
if actual.get("class") != "Directory":
130130
raise CompareFail.format(
131-
expected, actual, u"expected object with a class 'Directory'"
131+
expected, actual, "expected object with a class 'Directory'"
132132
)
133133
if "listing" not in actual:
134134
raise CompareFail.format(
135-
expected, actual, u"'listing' is mandatory field in Directory object"
135+
expected, actual, "'listing' is mandatory field in Directory object"
136136
)
137137
for i in expected["listing"]:
138138
found = False
@@ -147,7 +147,7 @@ def compare_directory(expected, actual):
147147
raise CompareFail.format(
148148
expected,
149149
actual,
150-
u"%s not found" % json.dumps(i, indent=4, sort_keys=True),
150+
"%s not found" % json.dumps(i, indent=4, sort_keys=True),
151151
)
152152
compare_file(expected, actual)
153153

@@ -159,12 +159,12 @@ def compare_dict(expected, actual):
159159
compare(expected[c], actual.get(c))
160160
except CompareFail as e:
161161
raise CompareFail.format(
162-
expected, actual, u"failed comparison for key '%s': %s" % (c, e)
162+
expected, actual, f"failed comparison for key '{c}': {e}"
163163
)
164164
extra_keys = set(actual.keys()).difference(list(expected.keys()))
165165
for k in extra_keys:
166166
if actual[k] is not None:
167-
raise CompareFail.format(expected, actual, u"unexpected key '%s'" % k)
167+
raise CompareFail.format(expected, actual, "unexpected key '%s'" % k)
168168

169169

170170
def compare(expected, actual): # type: (Any, Any) -> None
@@ -190,7 +190,7 @@ def compare(expected, actual): # type: (Any, Any) -> None
190190
raise CompareFail.format(expected, actual)
191191

192192
if len(expected) != len(actual):
193-
raise CompareFail.format(expected, actual, u"lengths don't match")
193+
raise CompareFail.format(expected, actual, "lengths don't match")
194194
for c in range(0, len(expected)):
195195
try:
196196
compare(expected[c], actual[c])

0 commit comments

Comments
 (0)