Skip to content

Commit f587d29

Browse files
committed
Apply formatting and code style fixes from pre-commit
A follow-on patch will add pre-commit to CI. References: * casework/CASE-Utilities-Python#37 Signed-off-by: Alex Nelson <alexander.nelson@nist.gov>
1 parent df54fb0 commit f587d29

File tree

3 files changed

+90
-46
lines changed

3 files changed

+90
-46
lines changed

case_gnu_time/__init__.py

Lines changed: 68 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,25 @@
2323
import os
2424
import typing
2525

26+
import case_utils
2627
import dateutil
2728
import dateutil.parser
2829
import dateutil.relativedelta
2930
import rdflib.util
30-
31-
import case_utils
3231
from case_utils.namespace import NS_RDF, NS_UCO_CORE, NS_UCO_OBSERVABLE, NS_XSD
3332

3433
_logger = logging.getLogger(os.path.basename(__file__))
3534

3635

3736
class ProcessUCOObject(object):
38-
def __init__(self, graph: rdflib.Graph, ns_base: rdflib.Namespace, *args: typing.Any, prefix_slug:str = "process-", **kwargs: typing.Any) -> None:
37+
def __init__(
38+
self,
39+
graph: rdflib.Graph,
40+
ns_base: rdflib.Namespace,
41+
*args: typing.Any,
42+
prefix_slug: str = "process-",
43+
**kwargs: typing.Any
44+
) -> None:
3945
"""
4046
Initializing a ProcessUCOObject will create one triple in the graph. To add data to the new node, call populate_from_gnu_time_log().
4147
"""
@@ -64,7 +70,9 @@ def populate_from_gnu_time_log(self, gnu_time_log: str) -> None:
6470
# Reminders on fromtimestamp vs. utcfromtimestamp:
6571
# https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp
6672
# "To get an aware datetime object, call fromtimestamp()"
67-
exit_time_datetime = datetime.datetime.fromtimestamp(st_time_log.st_mtime, tz=datetime.timezone.utc)
73+
exit_time_datetime = datetime.datetime.fromtimestamp(
74+
st_time_log.st_mtime, tz=datetime.timezone.utc
75+
)
6876
exit_time_str = exit_time_datetime.isoformat()
6977
self.exit_time = exit_time_str
7078
else:
@@ -84,22 +92,22 @@ def populate_from_gnu_time_log(self, gnu_time_log: str) -> None:
8492
elapsed_str = kvdict["Elapsed (wall clock) time (h:mm:ss or m:ss)"]
8593
elapsed_str_parts = elapsed_str.split(":")
8694
elapsed_seconds_str = elapsed_str_parts[-1]
87-
elapsed_seconds = int(elapsed_str_parts[-1].split(".")[0])
88-
elapsed_microseconds = int(elapsed_str_parts[-1].split(".")[1]) * 10000
95+
elapsed_seconds = int(elapsed_seconds_str.split(".")[0])
96+
elapsed_microseconds = int(elapsed_seconds_str.split(".")[1]) * 10000
8997
elapsed_minutes = int(elapsed_str_parts[-2])
9098
if len(elapsed_str_parts) == 3:
91-
elapsed_minutes += (60 * int(elapsed_str_parts[-3]))
99+
elapsed_minutes += 60 * int(elapsed_str_parts[-3])
92100

93101
delta = dateutil.relativedelta.relativedelta(
94-
minutes=elapsed_minutes,
95-
seconds=elapsed_seconds,
96-
microseconds=elapsed_microseconds
102+
minutes=elapsed_minutes,
103+
seconds=elapsed_seconds,
104+
microseconds=elapsed_microseconds,
97105
)
98106

99-
#logging.debug("delta = %r." % delta)
107+
# logging.debug("delta = %r." % delta)
100108
created_time_datetime = exit_time_datetime - delta
101-
#logging.debug("created_time_datetime = %r." % created_time_datetime)
102-
#logging.debug("exit_time_datetime = %r." % exit_time_datetime)
109+
# logging.debug("created_time_datetime = %r." % created_time_datetime)
110+
# logging.debug("exit_time_datetime = %r." % exit_time_datetime)
103111

104112
self.created_time = created_time_datetime.isoformat()
105113

@@ -112,12 +120,18 @@ def created_time(self, value: str) -> None:
112120
"""
113121
Only set once.
114122
"""
115-
assert not value is None
123+
assert value is not None
116124
assert self._created_time is None
117-
str_value = str(value) # For e.g. datetime objects.
125+
str_value = str(value) # For e.g. datetime objects.
118126
# Confirm text is ISO-8601.
119-
check_value = dateutil.parser.isoparse(str_value)
120-
self.graph.add((self.n_process_facet, NS_UCO_OBSERVABLE.observableCreatedTime, rdflib.Literal(str_value, datatype=NS_XSD.dateTime)))
127+
_ = dateutil.parser.isoparse(str_value)
128+
self.graph.add(
129+
(
130+
self.n_process_facet,
131+
NS_UCO_OBSERVABLE.observableCreatedTime,
132+
rdflib.Literal(str_value, datatype=NS_XSD.dateTime),
133+
)
134+
)
121135
self._created_time = value
122136

123137
@property
@@ -127,7 +141,9 @@ def exit_status(self) -> typing.Optional[int]:
127141
@exit_status.setter
128142
def exit_status(self, value: int) -> None:
129143
assert isinstance(value, int)
130-
self.graph.add((self.n_process_facet, NS_UCO_OBSERVABLE.exitStatus, rdflib.Literal(value)))
144+
self.graph.add(
145+
(self.n_process_facet, NS_UCO_OBSERVABLE.exitStatus, rdflib.Literal(value))
146+
)
131147

132148
@property
133149
def exit_time(self) -> typing.Optional[str]:
@@ -138,11 +154,11 @@ def exit_time(self, value: str) -> None:
138154
"""
139155
Only set once.
140156
"""
141-
assert not value is None
157+
assert value is not None
142158
assert self._exit_time is None
143-
str_value = str(value) # For e.g. datetime objects.
159+
str_value = str(value) # For e.g. datetime objects.
144160
# Confirm text is ISO-8601.
145-
check_value = dateutil.parser.isoparse(str_value)
161+
_ = dateutil.parser.isoparse(str_value)
146162
literal_time = rdflib.Literal(str_value, datatype=NS_XSD.dateTime)
147163
self.graph.add((self.n_process_facet, NS_UCO_OBSERVABLE.exitTime, literal_time))
148164
self._exit_time = value
@@ -153,8 +169,12 @@ def n_process_facet(self) -> rdflib.URIRef:
153169
Created on first access.
154170
"""
155171
if self._n_process_facet is None:
156-
self._n_process_facet = self.ns_base["process-facet-" + case_utils.local_uuid.local_uuid()]
157-
self.graph.add((self._n_process_facet, NS_RDF.type, NS_UCO_OBSERVABLE.ProcessFacet))
172+
self._n_process_facet = self.ns_base[
173+
"process-facet-" + case_utils.local_uuid.local_uuid()
174+
]
175+
self.graph.add(
176+
(self._n_process_facet, NS_RDF.type, NS_UCO_OBSERVABLE.ProcessFacet)
177+
)
158178
self.graph.add((self.node, NS_UCO_CORE.hasFacet, self._n_process_facet))
159179
return self._n_process_facet
160180

@@ -178,7 +198,7 @@ def build_process_object(
178198
ns_base: rdflib.Namespace,
179199
gnu_time_log: str,
180200
mtime: typing.Optional[str] = None,
181-
prefix_slug: typing.Optional[str] = None
201+
prefix_slug: typing.Optional[str] = None,
182202
) -> ProcessUCOObject:
183203
"""
184204
This function builds a Process UCO Object from a file that contains the output of GNU Time's --verbose flag.
@@ -194,24 +214,37 @@ def build_process_object(
194214
case_utils.local_uuid.configure()
195215

196216
process_object_kwargs = dict()
197-
if not prefix_slug is None:
217+
if prefix_slug is not None:
198218
process_object_kwargs["prefix_slug"] = prefix_slug
199219
process_object = ProcessUCOObject(graph, ns_base, **process_object_kwargs)
200220

201-
if not mtime is None:
221+
if mtime is not None:
202222
process_object.exit_time = mtime
203223

204224
process_object.populate_from_gnu_time_log(gnu_time_log)
205225

206226
return process_object
207227

228+
208229
argument_parser = argparse.ArgumentParser(epilog=__doc__)
209230
argument_parser.add_argument("--base-prefix", default="http://example.org/kb/")
210231
argument_parser.add_argument("--debug", action="store_true")
211-
argument_parser.add_argument("--done-log", help="A file recording the completion time of the process that GNU Time was timing, as an ISO-8601 string. If this argument is not provided, the Stat mtime of gnu_time_log is used.")
212-
argument_parser.add_argument("--output-format", help="Override extension-based format guesser.")
213-
argument_parser.add_argument("gnu_time_log", help="A file recording the output of the process wrapper GNU time, with the --verbose flag (recorded with the --output flag). Used to retrieve exit status, conclusion time (if --done-log not provided), and run length.")
214-
argument_parser.add_argument("out_graph", help="A self-contained RDF graph file, in the format either requested by --output-format or guessed based on extension.")
232+
argument_parser.add_argument(
233+
"--done-log",
234+
help="A file recording the completion time of the process that GNU Time was timing, as an ISO-8601 string. If this argument is not provided, the Stat mtime of gnu_time_log is used.",
235+
)
236+
argument_parser.add_argument(
237+
"--output-format", help="Override extension-based format guesser."
238+
)
239+
argument_parser.add_argument(
240+
"gnu_time_log",
241+
help="A file recording the output of the process wrapper GNU time, with the --verbose flag (recorded with the --output flag). Used to retrieve exit status, conclusion time (if --done-log not provided), and run length.",
242+
)
243+
argument_parser.add_argument(
244+
"out_graph",
245+
help="A self-contained RDF graph file, in the format either requested by --output-format or guessed based on extension.",
246+
)
247+
215248

216249
def main() -> None:
217250
args = argument_parser.parse_args()
@@ -228,12 +261,14 @@ def main() -> None:
228261
if args.done_log:
229262
with open(args.done_log, "r") as mtime_fh:
230263
mtime_str = mtime_fh.read(64).strip()
231-
process_object = build_process_object(graph, NS_BASE, args.gnu_time_log, mtime_str)
264+
_ = build_process_object(graph, NS_BASE, args.gnu_time_log, mtime_str)
232265

233-
#_logger.debug("args.output_format = %r." % args.output_format)
266+
# _logger.debug("args.output_format = %r." % args.output_format)
234267
output_format = args.output_format or rdflib.util.guess_format(args.out_graph)
268+
assert isinstance(output_format, str)
269+
270+
graph.serialize(destination=args.out_graph, format=output_format)
235271

236-
graph.serialize(destination=args.out_graph)
237272

238273
if __name__ == "__main__":
239274
main()

tests/as_import/consumer.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,13 @@
1818
import logging
1919
import os
2020

21+
import case_gnu_time
2122
import rdflib.util
22-
import case_utils
2323
from case_utils.namespace import NS_UCO_CORE, NS_UCO_OBSERVABLE
2424

25-
import case_gnu_time
26-
2725
_logger = logging.getLogger(os.path.basename(__file__))
2826

27+
2928
def main() -> None:
3029
args = case_gnu_time.argument_parser.parse_args()
3130
logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)
@@ -40,12 +39,15 @@ def main() -> None:
4039
if args.done_log:
4140
with open(args.done_log, "r") as mtime_fh:
4241
mtime_str = mtime_fh.read(64).strip()
43-
process_object = case_gnu_time.build_process_object(graph, NS_BASE, args.gnu_time_log, mtime_str, "custom-")
42+
_ = case_gnu_time.build_process_object(
43+
graph, NS_BASE, args.gnu_time_log, mtime_str, "custom-"
44+
)
4445

4546
output_format = args.output_format or rdflib.util.guess_format(args.out_graph)
4647
assert isinstance(output_format, str)
4748

4849
graph.serialize(destination=args.out_graph, format=output_format)
4950

51+
5052
if __name__ == "__main__":
5153
main()

tests/as_import/test_as_import.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,35 @@
1414
import logging
1515
import os
1616

17-
import rdflib.plugins.sparql
18-
1917
import case_utils.ontology
18+
import rdflib.plugins.sparql
2019

2120
_logger = logging.getLogger(os.path.basename(__file__))
2221

2322
srcdir = os.path.dirname(__file__)
2423

24+
2525
def _parse_graph(filename: str) -> rdflib.Graph:
2626
graph_filename = os.path.join(srcdir, filename)
2727
graph = rdflib.Graph()
2828
graph.parse(graph_filename)
2929
case_utils.ontology.load_subclass_hierarchy(graph)
3030
return graph
3131

32+
3233
def _test_as_import_load(graph_filename: str) -> None:
3334
graph = _parse_graph(graph_filename)
3435
assert len(graph) > 0
3536

37+
3638
def _test_as_import_query(graph_filename: str) -> None:
3739
graph = _parse_graph(graph_filename)
3840

39-
nsdict = {k:v for (k,v) in graph.namespace_manager.namespaces()}
41+
nsdict = {k: v for (k, v) in graph.namespace_manager.namespaces()}
4042

4143
iris = set()
42-
query = rdflib.plugins.sparql.processor.prepareQuery("""\
44+
query = rdflib.plugins.sparql.processor.prepareQuery(
45+
"""\
4346
SELECT ?nProcessObject
4447
WHERE
4548
{
@@ -53,27 +56,31 @@ def _test_as_import_query(graph_filename: str) -> None:
5356
uco-observable:exitStatus 0 ;
5457
.
5558
}
56-
""", initNs=nsdict)
59+
""",
60+
initNs=nsdict,
61+
)
5762

5863
results = graph.query(query)
5964
_logger.debug("len(results) = %d." % len(results))
6065
for result in results:
6166
_logger.debug("result = %r." % result)
62-
(
63-
n_process_object,
64-
) = result
65-
assert not n_process_object is None
67+
(n_process_object,) = result
68+
assert n_process_object is not None
6669
iris.add(n_process_object.toPython())
6770
assert len(iris) == 1
6871

72+
6973
def test_as_import_load_json() -> None:
7074
_test_as_import_load("process.json")
7175

76+
7277
def test_as_import_load_turtle() -> None:
7378
_test_as_import_load("process.ttl")
7479

80+
7581
def test_as_import_query_json() -> None:
7682
_test_as_import_query("process.json")
7783

84+
7885
def test_as_import_query_turtle() -> None:
7986
_test_as_import_query("process.ttl")

0 commit comments

Comments
 (0)