Skip to content

Commit 93fb849

Browse files
authored
fix(test): use yaml.SafeLoader only in test (#4466)
- the yaml.CSafeLoader doesn't work well with the python coverage test, limit to use yaml.SafeLoader for tests in this PR. - Jira: RHINENG-17357 Signed-off-by: Xiangce Liu <xiangceliu@redhat.com>
1 parent 8e7431f commit 93fb849

File tree

3 files changed

+38
-46
lines changed

3 files changed

+38
-46
lines changed

insights/ocp.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
The :py:func:`conf` component recognizes insights-operator and must-gather
55
archives.
66
"""
7+
78
import logging
89
import os
910
import yaml
1011
import warnings
1112

1213
from fnmatch import fnmatch
14+
from insights.core import SafeLoader as Loader
1315
from insights.core.plugins import component, datasource
1416
from insights.core.context import ExecutionContext, fs_root
1517

@@ -19,23 +21,18 @@
1921

2022
log = logging.getLogger(__name__)
2123

22-
try:
23-
# requires pyyaml installed after libyaml
24-
Loader = yaml.CSafeLoader
25-
except:
26-
log.info("Couldn't find libyaml loader. Falling back to python loader.")
27-
Loader = yaml.SafeLoader
28-
2924

3025
@fs_root
3126
class InsightsOperatorContext(ExecutionContext):
3227
"""Recognizes insights-operator archives"""
28+
3329
marker = "config/featuregate"
3430

3531

3632
@fs_root
3733
class MustGatherContext(ExecutionContext):
3834
"""Recognizes must-gather archives"""
35+
3936
marker = "cluster-scoped-resources"
4037

4138

insights/shell.py

Lines changed: 30 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from pygments.console import ansiformat
1818
from traitlets.config.loader import Config
1919

20+
from insights.core import SafeLoader as Loader
2021
from insights.core.context import SerializedArchiveContext
2122
from insights.core.serde import Hydration
2223
from insights.parsr.query import * # noqa
@@ -40,8 +41,6 @@
4041
from insights.formats import render
4142
from insights.formats.text import render_links
4243

43-
Loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader)
44-
4544
RULE_COLORS = {"fail": "brightred", "pass": "blue", "info": "magenta", "skip": "yellow"}
4645

4746

@@ -116,12 +115,8 @@ def _get_available_models(broker, group=dr.GROUPS.single):
116115
if dr.DELEGATES[comp].get_missing_dependencies(state):
117116
continue
118117

119-
if plugins.is_type(
120-
comp, (plugins.rule, plugins.condition, plugins.incident)
121-
):
122-
name = "_".join(
123-
[dr.get_base_module_name(comp), dr.get_simple_name(comp)]
124-
)
118+
if plugins.is_type(comp, (plugins.rule, plugins.condition, plugins.incident)):
119+
name = "_".join([dr.get_base_module_name(comp), dr.get_simple_name(comp)])
125120
else:
126121
name = dr.get_simple_name(comp)
127122

@@ -190,11 +185,11 @@ def __init__(self, broker, models, cwd, tmp, cov):
190185
super(Models, self).__init__(models)
191186

192187
def __dir__(self):
193-
""" Enabled ipython autocomplete. """
188+
"""Enabled ipython autocomplete."""
194189
return sorted(set(list(self.keys()) + dir(Models)))
195190

196191
def _ipython_key_completions_(self):
197-
""" For autocomplete of keys when accessing models as a dict. """
192+
"""For autocomplete of keys when accessing models as a dict."""
198193
return sorted(self.keys())
199194

200195
def __str__(self):
@@ -365,7 +360,7 @@ def make_rule(self, path=None, overwrite=False, pick=None):
365360
imports.append("")
366361

367362
for k in sorted(filterable):
368-
for (cls, n) in filterable[k]:
363+
for cls, n in filterable[k]:
369364
if (k, cls) not in seen:
370365
imports.append("from {} import {}".format(k, cls))
371366
seen.add((k, cls))
@@ -400,9 +395,7 @@ def make_rule(self, path=None, overwrite=False, pick=None):
400395
path = os.path.join(self._cwd, path)
401396

402397
if os.path.exists(path) and not overwrite:
403-
print(
404-
"{} already exists. Use overwrite=True to overwrite.".format(path)
405-
)
398+
print("{} already exists. Use overwrite=True to overwrite.".format(path))
406399
return
407400

408401
if not os.path.exists(path) or overwrite:
@@ -454,18 +447,16 @@ def _show_missing(self, comp):
454447
return results
455448

456449
def show_requested(self):
457-
""" Show the components you've worked with so far. """
450+
"""Show the components you've worked with so far."""
458451
results = []
459452
for name, comp in sorted(self._requested):
460453
results.append(
461-
ansiformat(
462-
self._get_color(comp), "{} {}".format(name, dr.get_name(comp))
463-
)
454+
ansiformat(self._get_color(comp), "{} {}".format(name, dr.get_name(comp)))
464455
)
465456
IPython.core.page.page(six.u(os.linesep.join(results)))
466457

467458
def reset_requested(self):
468-
""" Reset requested state so you can work on a new rule. """
459+
"""Reset requested state so you can work on a new rule."""
469460
IPython.get_ipython().history_manager.reset()
470461
self._requested.clear()
471462

@@ -487,11 +478,11 @@ def show_source(self, comp):
487478
width = len(str(len(src)))
488479
template = "{0:>%s}" % width
489480
results = []
490-
file_line = "{} {}".format(
491-
ansiformat("red", "File:"), os.path.realpath(path)
492-
)
493-
explain_line = "{} numbered lines have executed. python standard libs are excluded.".format(
494-
ansiformat("*brightgreen*", "Green")
481+
file_line = "{} {}".format(ansiformat("red", "File:"), os.path.realpath(path))
482+
explain_line = (
483+
"{} numbered lines have executed. python standard libs are excluded.".format(
484+
ansiformat("*brightgreen*", "Green")
485+
)
495486
)
496487
results.append(file_line)
497488
results.append(explain_line)
@@ -578,9 +569,7 @@ def _show_tree(self, node, indent="", depth=None, dep_getter=dr.get_dependencies
578569
results = []
579570
color = self._get_color(node)
580571
if plugins.is_datasource(node):
581-
results.extend(
582-
self._show_datasource(node, self._broker.get(node), indent=indent)
583-
)
572+
results.extend(self._show_datasource(node, self._broker.get(node), indent=indent))
584573
else:
585574
_type = self._get_type_name(node)
586575
name = dr.get_name(node)
@@ -598,7 +587,10 @@ def _show_tree(self, node, indent="", depth=None, dep_getter=dr.get_dependencies
598587
for d in deps:
599588
results.extend(
600589
self._show_tree(
601-
d, next_indent, depth=depth if depth is None else depth - 1, dep_getter=dep_getter
590+
d,
591+
next_indent,
592+
depth=depth if depth is None else depth - 1,
593+
dep_getter=dep_getter,
602594
)
603595
)
604596
return results
@@ -785,6 +777,7 @@ class Holder(dict):
785777
This is a dictionary that holds models for multiple archives. Access each model
786778
set using the path to the archive as the key. See models.keys().
787779
"""
780+
788781
def _ipython_key_completions_(self):
789782
return self.keys()
790783

@@ -818,6 +811,7 @@ def callback(brokers):
818811

819812
if kernel:
820813
from ipykernel import kernelapp
814+
821815
kernelapp.launch_new_instance([], user_ns=__ns, config=__cfg)
822816
else:
823817
IPython.start_ipython([], user_ns=__ns, config=__cfg)
@@ -844,9 +838,7 @@ def _parse_args():
844838
""".strip()
845839
p = argparse.ArgumentParser(description=desc, epilog=epilog)
846840

847-
p.add_argument(
848-
"-p", "--plugins", default="", help="Comma separated list of packages to load."
849-
)
841+
p.add_argument("-p", "--plugins", default="", help="Comma separated list of packages to load.")
850842
p.add_argument("-c", "--config", help="The insights configuration to apply.")
851843
p.add_argument(
852844
"--no-coverage",
@@ -858,16 +850,15 @@ def _parse_args():
858850
action="store_true",
859851
help="Change into the expanded directory for analysis.",
860852
)
853+
p.add_argument("--no-defaults", action="store_true", help="Don't load default components.")
854+
p.add_argument("-v", "--verbose", action="store_true", help="Global debug level logging.")
861855
p.add_argument(
862-
"--no-defaults", action="store_true", help="Don't load default components."
863-
)
864-
p.add_argument(
865-
"-v", "--verbose", action="store_true", help="Global debug level logging."
866-
)
867-
p.add_argument(
868-
"-k", "--kernel", action="store_true", default=False,
856+
"-k",
857+
"--kernel",
858+
action="store_true",
859+
default=False,
869860
help="Start an IPython kernel instead of an interactive session."
870-
" Requires ipykernel module"
861+
" Requires ipykernel module",
871862
)
872863

873864
path_desc = "Archives or paths to analyze. Leave off to target the current system."

insights/tests/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from collections import defaultdict
1313
from functools import wraps
1414
from operator import eq
15+
from yaml import SafeLoader
1516

1617
try:
1718
from StringIO import StringIO
@@ -27,6 +28,9 @@
2728
from insights.specs import Specs
2829

2930

31+
# Use yaml.SafeLoader only when pytesting, as the yaml.CSafeLoader does not
32+
# work well with coverage test.
33+
insights.core.SafeLoader = SafeLoader
3034
# we intercept the add_filter call during integration testing so we can ensure
3135
# that rules add filters to datasources that *should* be filterable
3236
ADDED_FILTERS = defaultdict(set)

0 commit comments

Comments
 (0)