How to use isattrs method in Pytest

Best Python code snippet using pytest

util.py

Source:util.py Github

copy

Full Screen

...79def isset(x):80 return isinstance(x, (set, frozenset))81def isdatacls(obj):82 return getattr(obj, "__dataclass_fields__", None) is not None83def isattrs(obj):84 return getattr(obj, "__attrs_attrs__", None) is not None85def isiterable(obj):86 try:87 iter(obj)88 return not istext(obj)89 except TypeError:90 return False91def assertrepr_compare(config, op, left, right):92 """Return specialised explanations for some operators/operands"""93 width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op94 left_repr = saferepr(left, maxsize=int(width // 2))95 right_repr = saferepr(right, maxsize=width - len(left_repr))96 summary = "{} {} {}".format(left_repr, op, right_repr)97 verbose = config.getoption("verbose")98 explanation = None99 try:100 if op == "==":101 if istext(left) and istext(right):102 explanation = _diff_text(left, right, verbose)103 else:104 if issequence(left) and issequence(right):105 explanation = _compare_eq_sequence(left, right, verbose)106 elif isset(left) and isset(right):107 explanation = _compare_eq_set(left, right, verbose)108 elif isdict(left) and isdict(right):109 explanation = _compare_eq_dict(left, right, verbose)110 elif type(left) == type(right) and (isdatacls(left) or isattrs(left)):111 type_fn = (isdatacls, isattrs)112 explanation = _compare_eq_cls(left, right, verbose, type_fn)113 elif verbose > 0:114 explanation = _compare_eq_verbose(left, right)115 if isiterable(left) and isiterable(right):116 expl = _compare_eq_iterable(left, right, verbose)117 if explanation is not None:118 explanation.extend(expl)119 else:120 explanation = expl121 elif op == "not in":122 if istext(left) and istext(right):123 explanation = _notin_text(left, right, verbose)124 except outcomes.Exit:125 raise126 except Exception:127 explanation = [128 "(pytest_assertion plugin: representation of details failed. "129 "Probably an object has a faulty __repr__.)",130 str(_pytest._code.ExceptionInfo.from_current()),131 ]132 if not explanation:133 return None134 return [summary] + explanation135def _diff_text(left, right, verbose=0):136 """Return the explanation for the diff between text or bytes.137 Unless --verbose is used this will skip leading and trailing138 characters which are identical to keep the diff minimal.139 If the input are bytes they will be safely converted to text.140 """141 from difflib import ndiff142 explanation = []143 def escape_for_readable_diff(binary_text):144 """145 Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.146 This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape147 newlines and carriage returns (#429).148 """149 r = str(repr(binary_text)[1:-1])150 r = r.replace(r"\n", "\n")151 r = r.replace(r"\r", "\r")152 return r153 if isinstance(left, bytes):154 left = escape_for_readable_diff(left)155 if isinstance(right, bytes):156 right = escape_for_readable_diff(right)157 if verbose < 1:158 i = 0 # just in case left or right has zero length159 for i in range(min(len(left), len(right))):160 if left[i] != right[i]:161 break162 if i > 42:163 i -= 10 # Provide some context164 explanation = [165 "Skipping %s identical leading characters in diff, use -v to show" % i166 ]167 left = left[i:]168 right = right[i:]169 if len(left) == len(right):170 for i in range(len(left)):171 if left[-i] != right[-i]:172 break173 if i > 42:174 i -= 10 # Provide some context175 explanation += [176 "Skipping {} identical trailing "177 "characters in diff, use -v to show".format(i)178 ]179 left = left[:-i]180 right = right[:-i]181 keepends = True182 if left.isspace() or right.isspace():183 left = repr(str(left))184 right = repr(str(right))185 explanation += ["Strings contain only whitespace, escaping them using repr()"]186 explanation += [187 line.strip("\n")188 for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))189 ]190 return explanation191def _compare_eq_verbose(left, right):192 keepends = True193 left_lines = repr(left).splitlines(keepends)194 right_lines = repr(right).splitlines(keepends)195 explanation = []196 explanation += ["-" + line for line in left_lines]197 explanation += ["+" + line for line in right_lines]198 return explanation199def _compare_eq_iterable(left, right, verbose=0):200 if not verbose:201 return ["Use -v to get the full diff"]202 # dynamic import to speedup pytest203 import difflib204 left_formatting = pprint.pformat(left).splitlines()205 right_formatting = pprint.pformat(right).splitlines()206 explanation = ["Full diff:"]207 explanation.extend(208 line.strip() for line in difflib.ndiff(left_formatting, right_formatting)209 )210 return explanation211def _compare_eq_sequence(left, right, verbose=0):212 comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)213 explanation = []214 len_left = len(left)215 len_right = len(right)216 for i in range(min(len_left, len_right)):217 if left[i] != right[i]:218 if comparing_bytes:219 # when comparing bytes, we want to see their ascii representation220 # instead of their numeric values (#5260)221 # using a slice gives us the ascii representation:222 # >>> s = b'foo'223 # >>> s[0]224 # 102225 # >>> s[0:1]226 # b'f'227 left_value = left[i : i + 1]228 right_value = right[i : i + 1]229 else:230 left_value = left[i]231 right_value = right[i]232 explanation += [233 "At index {} diff: {!r} != {!r}".format(i, left_value, right_value)234 ]235 break236 if comparing_bytes:237 # when comparing bytes, it doesn't help to show the "sides contain one or more items"238 # longer explanation, so skip it239 return explanation240 len_diff = len_left - len_right241 if len_diff:242 if len_diff > 0:243 dir_with_more = "Left"244 extra = saferepr(left[len_right])245 else:246 len_diff = 0 - len_diff247 dir_with_more = "Right"248 extra = saferepr(right[len_left])249 if len_diff == 1:250 explanation += [251 "{} contains one more item: {}".format(dir_with_more, extra)252 ]253 else:254 explanation += [255 "%s contains %d more items, first extra item: %s"256 % (dir_with_more, len_diff, extra)257 ]258 return explanation259def _compare_eq_set(left, right, verbose=0):260 explanation = []261 diff_left = left - right262 diff_right = right - left263 if diff_left:264 explanation.append("Extra items in the left set:")265 for item in diff_left:266 explanation.append(saferepr(item))267 if diff_right:268 explanation.append("Extra items in the right set:")269 for item in diff_right:270 explanation.append(saferepr(item))271 return explanation272def _compare_eq_dict(left, right, verbose=0):273 explanation = []274 set_left = set(left)275 set_right = set(right)276 common = set_left.intersection(set_right)277 same = {k: left[k] for k in common if left[k] == right[k]}278 if same and verbose < 2:279 explanation += ["Omitting %s identical items, use -vv to show" % len(same)]280 elif same:281 explanation += ["Common items:"]282 explanation += pprint.pformat(same).splitlines()283 diff = {k for k in common if left[k] != right[k]}284 if diff:285 explanation += ["Differing items:"]286 for k in diff:287 explanation += [saferepr({k: left[k]}) + " != " + saferepr({k: right[k]})]288 extra_left = set_left - set_right289 len_extra_left = len(extra_left)290 if len_extra_left:291 explanation.append(292 "Left contains %d more item%s:"293 % (len_extra_left, "" if len_extra_left == 1 else "s")294 )295 explanation.extend(296 pprint.pformat({k: left[k] for k in extra_left}).splitlines()297 )298 extra_right = set_right - set_left299 len_extra_right = len(extra_right)300 if len_extra_right:301 explanation.append(302 "Right contains %d more item%s:"303 % (len_extra_right, "" if len_extra_right == 1 else "s")304 )305 explanation.extend(306 pprint.pformat({k: right[k] for k in extra_right}).splitlines()307 )308 return explanation309def _compare_eq_cls(left, right, verbose, type_fns):310 isdatacls, isattrs = type_fns311 if isdatacls(left):312 all_fields = left.__dataclass_fields__313 fields_to_check = [field for field, info in all_fields.items() if info.compare]314 elif isattrs(left):315 all_fields = left.__attrs_attrs__316 fields_to_check = [field.name for field in all_fields if field.cmp]317 same = []318 diff = []319 for field in fields_to_check:320 if getattr(left, field) == getattr(right, field):321 same.append(field)322 else:323 diff.append(field)324 explanation = []325 if same and verbose < 2:326 explanation.append("Omitting %s identical items, use -vv to show" % len(same))327 elif same:328 explanation += ["Matching attributes:"]...

Full Screen

Full Screen

niudu-nix-scope.py

Source:niudu-nix-scope.py Github

copy

Full Screen

1import os2import sys3from PySide2 import QtGui, QtWidgets4import subprocess5import json6app = QtWidgets.QApplication(sys.argv)7class ScopeView(QtWidgets.QTreeView):8 def __init__(self, *args, **kwargs):9 super().__init__(*args, **kwargs)10 self.model = QtGui.QStandardItemModel()11 self.setModel(self.model)12 self.setHeaderHidden(True)13 self.expanded.connect(self.expanded__handler)14 self.add_items('(import <nixpkgs> {})', self.model.invisibleRootItem())15 def expanded__handler(self, index):16 parent_item = self.model.itemFromIndex(index)17 parent_item.removeRows(0, parent_item.rowCount())18 attr_path = ''19 parent_item_tmp = parent_item20 while parent_item_tmp is not None and parent_item_tmp is not self.model.invisibleRootItem():21 attr_path = '.' + parent_item_tmp.text() + attr_path22 parent_item_tmp = parent_item_tmp.parent()23 self.add_items('(import <nixpkgs> {})'+attr_path, parent_item)24 def add_items(self, set_expr, parent_item):25 #command = "nix-instantiate --strict --eval -E 'with rec {set_is_pkg = set: builtins.isAttrs set && builtins.hasAttr "type" set && builtins.getAttr "type" set == "derivation"; filter_pkgs = attr_set: builtins.filter (attr_name: (builtins.tryEval (set_is_pkg (builtins.getAttr attr_name attr_set))).value) (builtins.attrNames attr_set); }; filter_pkgs " + set_expr + "' --json"26 process = subprocess.Popen(["nix-instantiate", "--strict", "--eval", "-E", "with rec {set_is_pkg = set: builtins.isAttrs set && builtins.hasAttr \"type\" set && builtins.getAttr \"type\" set == \"derivation\"; filter_pkgs = attr_set: builtins.filter (attr_name: (builtins.tryEval (set_is_pkg (builtins.getAttr attr_name attr_set))).value) (builtins.attrNames attr_set); }; filter_pkgs "+set_expr, "--json"], stdout=subprocess.PIPE)27 (output, _) = process.communicate()28 _ = process.wait()29 for attr in json.loads(output):30 child_item = QtGui.QStandardItem(attr)31 parent_item.appendRow(child_item)32 child_item.appendRow(QtGui.QStandardItem(''))33scope_view = ScopeView()34class MainWindow(QtWidgets.QMainWindow):35 def __init__(self, *args, **kwargs):36 QtWidgets.QMainWindow.__init__(self, *args, **kwargs)37 central_widget = scope_view38 self.setCentralWidget(central_widget)39window = MainWindow()40window.show()...

Full Screen

Full Screen

Pytest Tutorial

Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.

Chapters

  1. What is pytest
  2. Pytest installation: Want to start pytest from scratch? See how to install and configure pytest for Python automation testing.
  3. Run first test with pytest framework: Follow this step-by-step tutorial to write and run your first pytest script.
  4. Parallel testing with pytest: A hands-on guide to parallel testing with pytest to improve the scalability of your test automation.
  5. Generate pytest reports: Reports make it easier to understand the results of pytest-based test runs. Learn how to generate pytest reports.
  6. Pytest Parameterized tests: Create and run your pytest scripts while avoiding code duplication and increasing test coverage with parameterization.
  7. Pytest Fixtures: Check out how to implement pytest fixtures for your end-to-end testing needs.
  8. Execute Multiple Test Cases: Explore different scenarios for running multiple test cases in pytest from a single file.
  9. Stop Test Suite after N Test Failures: See how to stop your test suite after n test failures in pytest using the @pytest.mark.incremental decorator and maxfail command-line option.

YouTube

Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.

https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful