How to use delegate method in hypothesis

Best Python code snippet using hypothesis

lldbtk.py

Source:lldbtk.py Github

copy

Full Screen

1#!/usr/bin/python2from __future__ import print_function3import lldb4import shlex5import sys6try:7 from tkinter import *8 import tkinter.ttk as ttk9except ImportError:10 from Tkinter import *11 import ttk12class ValueTreeItemDelegate(object):13 def __init__(self, value):14 self.value = value15 def get_item_dictionary(self):16 name = self.value.name17 if name is None:18 name = ''19 typename = self.value.type20 if typename is None:21 typename = ''22 value = self.value.value23 if value is None:24 value = ''25 summary = self.value.summary26 if summary is None:27 summary = ''28 has_children = self.value.MightHaveChildren()29 return {'#0': name,30 'typename': typename,31 'value': value,32 'summary': summary,33 'children': has_children,34 'tree-item-delegate': self}35 def get_child_item_dictionaries(self):36 item_dicts = list()37 for i in range(self.value.num_children):38 item_delegate = ValueTreeItemDelegate(39 self.value.GetChildAtIndex(i))40 item_dicts.append(item_delegate.get_item_dictionary())41 return item_dicts42class FrameTreeItemDelegate(object):43 def __init__(self, frame):44 self.frame = frame45 def get_item_dictionary(self):46 id = self.frame.GetFrameID()47 name = 'frame #%u' % (id)48 value = '0x%16.16x' % (self.frame.GetPC())49 stream = lldb.SBStream()50 self.frame.GetDescription(stream)51 summary = stream.GetData().split("`")[1]52 return {53 '#0': name,54 'value': value,55 'summary': summary,56 'children': self.frame.GetVariables(57 True,58 True,59 True,60 True).GetSize() > 0,61 'tree-item-delegate': self}62 def get_child_item_dictionaries(self):63 item_dicts = list()64 variables = self.frame.GetVariables(True, True, True, True)65 n = variables.GetSize()66 for i in range(n):67 item_delegate = ValueTreeItemDelegate(variables[i])68 item_dicts.append(item_delegate.get_item_dictionary())69 return item_dicts70class ThreadTreeItemDelegate(object):71 def __init__(self, thread):72 self.thread = thread73 def get_item_dictionary(self):74 num_frames = self.thread.GetNumFrames()75 name = 'thread #%u' % (self.thread.GetIndexID())76 value = '0x%x' % (self.thread.GetThreadID())77 summary = '%u frames' % (num_frames)78 return {'#0': name,79 'value': value,80 'summary': summary,81 'children': num_frames > 0,82 'tree-item-delegate': self}83 def get_child_item_dictionaries(self):84 item_dicts = list()85 for frame in self.thread:86 item_delegate = FrameTreeItemDelegate(frame)87 item_dicts.append(item_delegate.get_item_dictionary())88 return item_dicts89class ProcessTreeItemDelegate(object):90 def __init__(self, process):91 self.process = process92 def get_item_dictionary(self):93 id = self.process.GetProcessID()94 num_threads = self.process.GetNumThreads()95 value = str(self.process.GetProcessID())96 summary = self.process.target.executable.fullpath97 return {'#0': 'process',98 'value': value,99 'summary': summary,100 'children': num_threads > 0,101 'tree-item-delegate': self}102 def get_child_item_dictionaries(self):103 item_dicts = list()104 for thread in self.process:105 item_delegate = ThreadTreeItemDelegate(thread)106 item_dicts.append(item_delegate.get_item_dictionary())107 return item_dicts108class TargetTreeItemDelegate(object):109 def __init__(self, target):110 self.target = target111 def get_item_dictionary(self):112 value = str(self.target.triple)113 summary = self.target.executable.fullpath114 return {'#0': 'target',115 'value': value,116 'summary': summary,117 'children': True,118 'tree-item-delegate': self}119 def get_child_item_dictionaries(self):120 item_dicts = list()121 image_item_delegate = TargetImagesTreeItemDelegate(self.target)122 item_dicts.append(image_item_delegate.get_item_dictionary())123 return item_dicts124class TargetImagesTreeItemDelegate(object):125 def __init__(self, target):126 self.target = target127 def get_item_dictionary(self):128 value = str(self.target.triple)129 summary = self.target.executable.fullpath130 num_modules = self.target.GetNumModules()131 return {'#0': 'images',132 'value': '',133 'summary': '%u images' % num_modules,134 'children': num_modules > 0,135 'tree-item-delegate': self}136 def get_child_item_dictionaries(self):137 item_dicts = list()138 for i in range(self.target.GetNumModules()):139 module = self.target.GetModuleAtIndex(i)140 image_item_delegate = ModuleTreeItemDelegate(141 self.target, module, i)142 item_dicts.append(image_item_delegate.get_item_dictionary())143 return item_dicts144class ModuleTreeItemDelegate(object):145 def __init__(self, target, module, index):146 self.target = target147 self.module = module148 self.index = index149 def get_item_dictionary(self):150 name = 'module %u' % (self.index)151 value = self.module.file.basename152 summary = self.module.file.dirname153 return {'#0': name,154 'value': value,155 'summary': summary,156 'children': True,157 'tree-item-delegate': self}158 def get_child_item_dictionaries(self):159 item_dicts = list()160 sections_item_delegate = ModuleSectionsTreeItemDelegate(161 self.target, self.module)162 item_dicts.append(sections_item_delegate.get_item_dictionary())163 symbols_item_delegate = ModuleSymbolsTreeItemDelegate(164 self.target, self.module)165 item_dicts.append(symbols_item_delegate.get_item_dictionary())166 comp_units_item_delegate = ModuleCompileUnitsTreeItemDelegate(167 self.target, self.module)168 item_dicts.append(comp_units_item_delegate.get_item_dictionary())169 return item_dicts170class ModuleSectionsTreeItemDelegate(object):171 def __init__(self, target, module):172 self.target = target173 self.module = module174 def get_item_dictionary(self):175 name = 'sections'176 value = ''177 summary = '%u sections' % (self.module.GetNumSections())178 return {'#0': name,179 'value': value,180 'summary': summary,181 'children': True,182 'tree-item-delegate': self}183 def get_child_item_dictionaries(self):184 item_dicts = list()185 num_sections = self.module.GetNumSections()186 for i in range(num_sections):187 section = self.module.GetSectionAtIndex(i)188 image_item_delegate = SectionTreeItemDelegate(self.target, section)189 item_dicts.append(image_item_delegate.get_item_dictionary())190 return item_dicts191class SectionTreeItemDelegate(object):192 def __init__(self, target, section):193 self.target = target194 self.section = section195 def get_item_dictionary(self):196 name = self.section.name197 section_load_addr = self.section.GetLoadAddress(self.target)198 if section_load_addr != lldb.LLDB_INVALID_ADDRESS:199 value = '0x%16.16x' % (section_load_addr)200 else:201 value = '0x%16.16x *' % (self.section.file_addr)202 summary = ''203 return {'#0': name,204 'value': value,205 'summary': summary,206 'children': self.section.GetNumSubSections() > 0,207 'tree-item-delegate': self}208 def get_child_item_dictionaries(self):209 item_dicts = list()210 num_sections = self.section.GetNumSubSections()211 for i in range(num_sections):212 section = self.section.GetSubSectionAtIndex(i)213 image_item_delegate = SectionTreeItemDelegate(self.target, section)214 item_dicts.append(image_item_delegate.get_item_dictionary())215 return item_dicts216class ModuleCompileUnitsTreeItemDelegate(object):217 def __init__(self, target, module):218 self.target = target219 self.module = module220 def get_item_dictionary(self):221 name = 'compile units'222 value = ''223 summary = '%u compile units' % (self.module.GetNumSections())224 return {'#0': name,225 'value': value,226 'summary': summary,227 'children': self.module.GetNumCompileUnits() > 0,228 'tree-item-delegate': self}229 def get_child_item_dictionaries(self):230 item_dicts = list()231 num_cus = self.module.GetNumCompileUnits()232 for i in range(num_cus):233 cu = self.module.GetCompileUnitAtIndex(i)234 image_item_delegate = CompileUnitTreeItemDelegate(self.target, cu)235 item_dicts.append(image_item_delegate.get_item_dictionary())236 return item_dicts237class CompileUnitTreeItemDelegate(object):238 def __init__(self, target, cu):239 self.target = target240 self.cu = cu241 def get_item_dictionary(self):242 name = self.cu.GetFileSpec().basename243 value = ''244 num_lines = self.cu.GetNumLineEntries()245 summary = ''246 return {'#0': name,247 'value': value,248 'summary': summary,249 'children': num_lines > 0,250 'tree-item-delegate': self}251 def get_child_item_dictionaries(self):252 item_dicts = list()253 item_delegate = LineTableTreeItemDelegate(self.target, self.cu)254 item_dicts.append(item_delegate.get_item_dictionary())255 return item_dicts256class LineTableTreeItemDelegate(object):257 def __init__(self, target, cu):258 self.target = target259 self.cu = cu260 def get_item_dictionary(self):261 name = 'line table'262 value = ''263 num_lines = self.cu.GetNumLineEntries()264 summary = '%u line entries' % (num_lines)265 return {'#0': name,266 'value': value,267 'summary': summary,268 'children': num_lines > 0,269 'tree-item-delegate': self}270 def get_child_item_dictionaries(self):271 item_dicts = list()272 num_lines = self.cu.GetNumLineEntries()273 for i in range(num_lines):274 line_entry = self.cu.GetLineEntryAtIndex(i)275 item_delegate = LineEntryTreeItemDelegate(276 self.target, line_entry, i)277 item_dicts.append(item_delegate.get_item_dictionary())278 return item_dicts279class LineEntryTreeItemDelegate(object):280 def __init__(self, target, line_entry, index):281 self.target = target282 self.line_entry = line_entry283 self.index = index284 def get_item_dictionary(self):285 name = str(self.index)286 address = self.line_entry.GetStartAddress()287 load_addr = address.GetLoadAddress(self.target)288 if load_addr != lldb.LLDB_INVALID_ADDRESS:289 value = '0x%16.16x' % (load_addr)290 else:291 value = '0x%16.16x *' % (address.file_addr)292 summary = self.line_entry.GetFileSpec().fullpath + ':' + \293 str(self.line_entry.line)294 return {'#0': name,295 'value': value,296 'summary': summary,297 'children': False,298 'tree-item-delegate': self}299 def get_child_item_dictionaries(self):300 item_dicts = list()301 return item_dicts302class InstructionTreeItemDelegate(object):303 def __init__(self, target, instr):304 self.target = target305 self.instr = instr306 def get_item_dictionary(self):307 address = self.instr.GetAddress()308 load_addr = address.GetLoadAddress(self.target)309 if load_addr != lldb.LLDB_INVALID_ADDRESS:310 name = '0x%16.16x' % (load_addr)311 else:312 name = '0x%16.16x *' % (address.file_addr)313 value = self.instr.GetMnemonic(314 self.target) + ' ' + self.instr.GetOperands(self.target)315 summary = self.instr.GetComment(self.target)316 return {'#0': name,317 'value': value,318 'summary': summary,319 'children': False,320 'tree-item-delegate': self}321class ModuleSymbolsTreeItemDelegate(object):322 def __init__(self, target, module):323 self.target = target324 self.module = module325 def get_item_dictionary(self):326 name = 'symbols'327 value = ''328 summary = '%u symbols' % (self.module.GetNumSymbols())329 return {'#0': name,330 'value': value,331 'summary': summary,332 'children': True,333 'tree-item-delegate': self}334 def get_child_item_dictionaries(self):335 item_dicts = list()336 num_symbols = self.module.GetNumSymbols()337 for i in range(num_symbols):338 symbol = self.module.GetSymbolAtIndex(i)339 image_item_delegate = SymbolTreeItemDelegate(340 self.target, symbol, i)341 item_dicts.append(image_item_delegate.get_item_dictionary())342 return item_dicts343class SymbolTreeItemDelegate(object):344 def __init__(self, target, symbol, index):345 self.target = target346 self.symbol = symbol347 self.index = index348 def get_item_dictionary(self):349 address = self.symbol.GetStartAddress()350 name = '[%u]' % self.index351 symbol_load_addr = address.GetLoadAddress(self.target)352 if symbol_load_addr != lldb.LLDB_INVALID_ADDRESS:353 value = '0x%16.16x' % (symbol_load_addr)354 else:355 value = '0x%16.16x *' % (address.file_addr)356 summary = self.symbol.name357 return {'#0': name,358 'value': value,359 'summary': summary,360 'children': False,361 'tree-item-delegate': self}362 def get_child_item_dictionaries(self):363 item_dicts = list()364 return item_dicts365class DelegateTree(ttk.Frame):366 def __init__(self, column_dicts, delegate, title, name):367 ttk.Frame.__init__(self, name=name)368 self.pack(expand=Y, fill=BOTH)369 self.master.title(title)370 self.delegate = delegate371 self.columns_dicts = column_dicts372 self.item_id_to_item_dict = dict()373 frame = Frame(self)374 frame.pack(side=TOP, fill=BOTH, expand=Y)375 self._create_treeview(frame)376 self._populate_root()377 def _create_treeview(self, parent):378 frame = ttk.Frame(parent)379 frame.pack(side=TOP, fill=BOTH, expand=Y)380 column_ids = list()381 for i in range(1, len(self.columns_dicts)):382 column_ids.append(self.columns_dicts[i]['id'])383 # create the tree and scrollbars384 self.tree = ttk.Treeview(columns=column_ids)385 scroll_bar_v = ttk.Scrollbar(orient=VERTICAL, command=self.tree.yview)386 scroll_bar_h = ttk.Scrollbar(387 orient=HORIZONTAL, command=self.tree.xview)388 self.tree['yscroll'] = scroll_bar_v.set389 self.tree['xscroll'] = scroll_bar_h.set390 # setup column headings and columns properties391 for columns_dict in self.columns_dicts:392 self.tree.heading(393 columns_dict['id'],394 text=columns_dict['text'],395 anchor=columns_dict['anchor'])396 self.tree.column(397 columns_dict['id'],398 stretch=columns_dict['stretch'])399 # add tree and scrollbars to frame400 self.tree.grid(in_=frame, row=0, column=0, sticky=NSEW)401 scroll_bar_v.grid(in_=frame, row=0, column=1, sticky=NS)402 scroll_bar_h.grid(in_=frame, row=1, column=0, sticky=EW)403 # set frame resizing priorities404 frame.rowconfigure(0, weight=1)405 frame.columnconfigure(0, weight=1)406 # action to perform when a node is expanded407 self.tree.bind('<<TreeviewOpen>>', self._update_tree)408 def insert_items(self, parent_id, item_dicts):409 for item_dict in item_dicts:410 name = None411 values = list()412 first = True413 for columns_dict in self.columns_dicts:414 if first:415 name = item_dict[columns_dict['id']]416 first = False417 else:418 values.append(item_dict[columns_dict['id']])419 item_id = self.tree.insert(parent_id, # root item has an empty name420 END,421 text=name,422 values=values)423 self.item_id_to_item_dict[item_id] = item_dict424 if item_dict['children']:425 self.tree.insert(item_id, END, text='dummy')426 def _populate_root(self):427 # use current directory as root node428 self.insert_items('', self.delegate.get_child_item_dictionaries())429 def _update_tree(self, event):430 # user expanded a node - build the related directory431 item_id = self.tree.focus() # the id of the expanded node432 children = self.tree.get_children(item_id)433 if len(children):434 first_child = children[0]435 # if the node only has a 'dummy' child, remove it and436 # build new directory; skip if the node is already437 # populated438 if self.tree.item(first_child, option='text') == 'dummy':439 self.tree.delete(first_child)440 item_dict = self.item_id_to_item_dict[item_id]441 item_dicts = item_dict[442 'tree-item-delegate'].get_child_item_dictionaries()443 self.insert_items(item_id, item_dicts)444@lldb.command("tk-variables")445def tk_variable_display(debugger, command, result, dict):446 # needed for tree creation in TK library as it uses sys.argv...447 sys.argv = ['tk-variables']448 target = debugger.GetSelectedTarget()449 if not target:450 print("invalid target", file=result)451 return452 process = target.GetProcess()453 if not process:454 print("invalid process", file=result)455 return456 thread = process.GetSelectedThread()457 if not thread:458 print("invalid thread", file=result)459 return460 frame = thread.GetSelectedFrame()461 if not frame:462 print("invalid frame", file=result)463 return464 # Parse command line args465 command_args = shlex.split(command)466 column_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0},467 {'id': 'typename', 'text': 'Type', 'anchor': W, 'stretch': 0},468 {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0},469 {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}]470 tree = DelegateTree(471 column_dicts,472 FrameTreeItemDelegate(frame),473 'Variables',474 'lldb-tk-variables')475 tree.mainloop()476@lldb.command("tk-process")477def tk_process_display(debugger, command, result, dict):478 # needed for tree creation in TK library as it uses sys.argv...479 sys.argv = ['tk-process']480 target = debugger.GetSelectedTarget()481 if not target:482 print("invalid target", file=result)483 return484 process = target.GetProcess()485 if not process:486 print("invalid process", file=result)487 return488 # Parse command line args489 columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0},490 {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0},491 {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}]492 command_args = shlex.split(command)493 tree = DelegateTree(494 columnd_dicts,495 ProcessTreeItemDelegate(process),496 'Process',497 'lldb-tk-process')498 tree.mainloop()499@lldb.command("tk-target")500def tk_target_display(debugger, command, result, dict):501 # needed for tree creation in TK library as it uses sys.argv...502 sys.argv = ['tk-target']503 target = debugger.GetSelectedTarget()504 if not target:505 print("invalid target", file=result)506 return507 # Parse command line args508 columnd_dicts = [{'id': '#0', 'text': 'Name', 'anchor': W, 'stretch': 0},509 {'id': 'value', 'text': 'Value', 'anchor': W, 'stretch': 0},510 {'id': 'summary', 'text': 'Summary', 'anchor': W, 'stretch': 1}]511 command_args = shlex.split(command)512 tree = DelegateTree(513 columnd_dicts,514 TargetTreeItemDelegate(target),515 'Target',516 'lldb-tk-target')...

Full Screen

Full Screen

test_delegate_parameter.py

Source:test_delegate_parameter.py Github

copy

Full Screen

1"""2Test suite for DelegateParameter3"""4from typing import cast5import hypothesis.strategies as hst6import pytest7from hypothesis import given8from qcodes.instrument.parameter import DelegateParameter, Parameter, ParamRawDataType9from .conftest import BetterGettableParam10# Disable warning that is created by using fixtures11# pylint: disable=redefined-outer-name12@pytest.fixture()13def numeric_val():14 yield 115@pytest.fixture()16def simple_param(numeric_val):17 yield Parameter('testparam', set_cmd=None, get_cmd=None,18 scale=2, offset=17,19 label='Test Parameter', unit='V',20 initial_value=numeric_val)21@pytest.fixture(params=[True, False])22def make_observable_parameter(request):23 def make_parameter(*args, override_getset: bool = True, **kwargs):24 class ObservableParam(Parameter):25 def __init__(self, *args, **kwargs):26 self.instr_val = None27 super().__init__(*args, **kwargs)28 def set_raw( # pylint: disable=method-hidden29 self, value: ParamRawDataType) -> None:30 self.instr_val = value31 def get_raw( # pylint: disable=method-hidden32 self) -> ParamRawDataType:33 return self.instr_val34 def get_instr_val(self):35 return self.instr_val36 if request.param:37 if not override_getset:38 pytest.skip()39 param = ObservableParam(*args, **kwargs)40 else:41 val = None42 def set_cmd(value):43 nonlocal val44 val = value45 def get_cmd():46 nonlocal val47 return val48 p = Parameter(*args, **kwargs, # type: ignore[misc]49 set_cmd=set_cmd, get_cmd=get_cmd)50 param = cast(ObservableParam, p)51 param.get_instr_val = get_cmd # type: ignore[assignment]52 return param53 yield make_parameter54def test_observable_parameter(make_observable_parameter, numeric_val):55 p = make_observable_parameter('testparam')56 p(numeric_val)57 assert p.get_instr_val() == numeric_val58def test_observable_parameter_initial_value(make_observable_parameter,59 numeric_val):60 t = make_observable_parameter(61 'observable_parameter', initial_value=numeric_val)62 assert t.get_instr_val() == numeric_val63def test_same_value(simple_param):64 d = DelegateParameter('test_delegate_parameter', simple_param)65 assert d() == simple_param()66def test_same_label_and_unit_on_init(simple_param):67 """68 Test that the label and unit get used from source parameter if not69 specified otherwise.70 """71 d = DelegateParameter('test_delegate_parameter', simple_param)72 assert d.label == simple_param.label73 assert d.unit == simple_param.unit74def test_overwritten_unit_on_init(simple_param):75 d = DelegateParameter('test_delegate_parameter', simple_param, unit='Ohm')76 assert d.label == simple_param.label77 assert not d.unit == simple_param.unit78 assert d.unit == 'Ohm'79def test_overwritten_label_on_init(simple_param):80 d = DelegateParameter('test_delegate_parameter', simple_param,81 label='Physical parameter')82 assert d.unit == simple_param.unit83 assert not d.label == simple_param.label84 assert d.label == 'Physical parameter'85def test_get_set_raises(simple_param):86 """87 Test that providing a get/set_cmd kwarg raises an error.88 """89 for kwargs in ({'set_cmd': None}, {'get_cmd': None}):90 with pytest.raises(KeyError) as e:91 DelegateParameter('test_delegate_parameter', simple_param, **kwargs)92 assert str(e.value).startswith('\'It is not allowed to set')93def test_scaling(simple_param, numeric_val):94 scale = 595 offset = 396 d = DelegateParameter(97 'test_delegate_parameter', simple_param, offset=offset, scale=scale)98 simple_param(numeric_val)99 assert d() == (numeric_val - offset) / scale100 d(numeric_val)101 assert simple_param() == numeric_val * scale + offset102def test_scaling_delegate_initial_value(simple_param, numeric_val):103 scale = 5104 offset = 3105 DelegateParameter(106 'test_delegate_parameter', simple_param, offset=offset, scale=scale,107 initial_value=numeric_val)108 assert simple_param() == numeric_val * scale + offset109def test_scaling_initial_value(simple_param, numeric_val):110 scale = 5111 offset = 3112 d = DelegateParameter(113 'test_delegate_parameter', simple_param, offset=offset, scale=scale)114 assert d() == (simple_param() - offset) / scale115def test_snapshot():116 p = Parameter('testparam', set_cmd=None, get_cmd=None,117 offset=1, scale=2, initial_value=1)118 d = DelegateParameter('test_delegate_parameter', p, offset=3, scale=5,119 initial_value=2)120 delegate_snapshot = d.snapshot()121 source_snapshot = delegate_snapshot.pop('source_parameter')122 assert source_snapshot == p.snapshot()123 assert delegate_snapshot['value'] == 2124 assert source_snapshot['value'] == 13125def test_set_source_cache_changes_delegate_cache(simple_param):126 """ Setting the cached value of the source parameter changes the127 delegate parameter cache accordingly.128 """129 offset = 4130 scale = 5131 d = DelegateParameter('d', simple_param, offset=offset, scale=scale)132 new_source_value = 3133 simple_param.cache.set(new_source_value)134 assert d.cache.get() == (new_source_value - offset) / scale135def test_set_source_cache_changes_delegate_get(simple_param):136 """ When the delegate parameter's ``get`` is called, the new137 value of the source propagates.138 """139 offset = 4140 scale = 5141 d = DelegateParameter('d', simple_param, offset=offset, scale=scale)142 new_source_value = 3143 simple_param.cache.set(new_source_value)144 assert d.get() == (new_source_value - offset) / scale145def test_set_delegate_cache_changes_source_cache(simple_param):146 offset = 4147 scale = 5148 d = DelegateParameter('d', simple_param, offset=offset, scale=scale)149 new_delegate_value = 2150 d.cache.set(new_delegate_value)151 assert simple_param.cache.get() == (new_delegate_value * scale + offset)152def test_set_delegate_cache_with_raw_value(simple_param):153 offset = 4154 scale = 5155 d = DelegateParameter('d', simple_param, offset=offset, scale=scale)156 new_delegate_value = 2157 d.cache._set_from_raw_value(new_delegate_value*scale + offset)158 assert simple_param.cache.get() == (new_delegate_value * scale + offset)159 assert d.cache.get(get_if_invalid=False) == new_delegate_value160def test_instrument_val_invariant_under_delegate_cache_set(161 make_observable_parameter, numeric_val):162 """163 Setting the cached value of the source parameter changes the delegate164 parameter. But it has no impact on the instrument value.165 """166 initial_value = numeric_val167 t = make_observable_parameter(168 'observable_parameter', initial_value=initial_value)169 new_source_value = 3170 t.cache.set(new_source_value)171 assert t.get_instr_val() == initial_value172def test_delegate_cache_pristine_if_not_set():173 p = Parameter('test')174 d = DelegateParameter('delegate', p)175 gotten_delegate_cache = d.cache.get(get_if_invalid=False)176 assert gotten_delegate_cache is None177def test_delegate_get_updates_cache(make_observable_parameter, numeric_val):178 initial_value = numeric_val179 t = make_observable_parameter(180 'observable_parameter', initial_value=initial_value)181 d = DelegateParameter('delegate', t)182 assert d() == initial_value183 assert d.cache.get() == initial_value184 assert t.get_instr_val() == initial_value185def test_delegate_parameter_get_and_snapshot_with_none_source():186 """187 Test that a delegate parameter returns None on get and snapshot if188 the source has a value of None and an offset or scale is used.189 And returns a value if the source is remapped to a real parameter.190 """191 none_param = Parameter("None")192 source_param = Parameter('source', get_cmd=None, set_cmd=None, initial_value=2)193 delegate_param = DelegateParameter(name='delegate', source=none_param)194 delegate_param.offset = 4195 assert delegate_param.get() is None196 assert delegate_param.snapshot()['value'] is None197 delegate_param.offset = None198 delegate_param.scale = 2199 assert delegate_param.get() is None200 assert delegate_param.snapshot()['value'] is None201 assert delegate_param.cache._parameter.source.cache is none_param.cache202 delegate_param.source = source_param203 assert delegate_param.get() == 1204 assert delegate_param.snapshot()['value'] == 1205 assert delegate_param.cache._parameter.source.cache is source_param.cache206def test_raw_value_scaling(make_observable_parameter):207 """208 The :attr:`raw_value` will be deprecated soon,209 so other tests should not use it.210 """211 p = Parameter('testparam', set_cmd=None, get_cmd=None,212 offset=1, scale=2)213 d = DelegateParameter('test_delegate_parameter', p, offset=3, scale=5)214 val = 1215 p(val)216 assert d() == (val - 3) / 5217 d(val)218 assert d.raw_value == val * 5 + 3219 assert d.raw_value == p()220def test_setting_initial_value_delegate_parameter():221 value = 10222 p = Parameter('testparam', set_cmd=None, get_cmd=None)223 d = DelegateParameter('test_delegate_parameter', p,224 initial_value=value)225 assert p.cache.get(get_if_invalid=False) == value226 assert d.cache.get(get_if_invalid=False) == value227def test_setting_initial_cache_delegate_parameter():228 value = 10229 p = Parameter('testparam', set_cmd=None, get_cmd=None)230 d = DelegateParameter('test_delegate_parameter', p,231 initial_cache_value=value)232 assert p.cache.get(get_if_invalid=False) == value233 assert d.cache.get(get_if_invalid=False) == value234def test_delegate_parameter_with_none_source_works_as_expected():235 delegate_param = DelegateParameter(name='delegate', source=None,236 scale=2, offset=1)237 _assert_none_source_is_correct(delegate_param)238@given(hst.floats(allow_nan=False, allow_infinity=False),239 hst.floats(allow_nan=False, allow_infinity=False).filter(lambda x: x != 0),240 hst.floats(allow_nan=False, allow_infinity=False))241def test_delegate_parameter_with_changed_source_snapshot_matches_value(value,242 scale,243 offset):244 delegate_param = DelegateParameter(name="delegate",245 source=None,246 scale=scale,247 offset=offset)248 source_parameter = Parameter(name="source",249 get_cmd=None,250 set_cmd=None,251 initial_value=value)252 _assert_none_source_is_correct(delegate_param)253 delegate_param.source = source_parameter254 calc_value = (value - offset) / scale255 assert delegate_param.cache.get(get_if_invalid=False) == calc_value256 assert delegate_param.source.cache.get(get_if_invalid=False) == value257 snapshot = delegate_param.snapshot()258 # disregard timestamp that might be slightly different259 snapshot["source_parameter"].pop("ts")260 source_snapshot = source_parameter.snapshot()261 source_snapshot.pop("ts")262 assert snapshot["source_parameter"] == source_snapshot263 assert snapshot["value"] == calc_value264 assert delegate_param.get() == calc_value265 # now remove the source again266 delegate_param.source = None267 _assert_none_source_is_correct(delegate_param)268 _assert_delegate_cache_none_source(delegate_param)269def _assert_none_source_is_correct(delegate_param):270 with pytest.raises(TypeError):271 delegate_param.get()272 with pytest.raises(TypeError):273 delegate_param.set(1)274 snapshot = delegate_param.snapshot()275 assert snapshot["source_parameter"] is None276 assert "value" not in snapshot.keys()277 snapshot.pop("ts")278 updated_snapshot = delegate_param.snapshot(update=True)279 updated_snapshot.pop("ts")280 assert snapshot == updated_snapshot281def _assert_delegate_cache_none_source(delegate_param):282 with pytest.raises(TypeError):283 delegate_param.cache.set(1)284 with pytest.raises(TypeError):285 delegate_param.cache.get()286 with pytest.raises(TypeError):287 delegate_param.cache.raw_value288 assert delegate_param.cache.max_val_age is None289 assert delegate_param.cache.timestamp is None290@pytest.mark.parametrize("snapshot_value", [True, False])291@pytest.mark.parametrize("gettable,get_cmd", [(True, None), (False, False)])292@pytest.mark.parametrize("settable,set_cmd", [(True, None), (False, False)])293def test_gettable_settable_snapshotget_delegate_parameter(gettable, get_cmd,294 settable, set_cmd,295 snapshot_value):296 """297 Test that gettable, settable and snapshot_get are correctly reflected298 in the DelegateParameter299 """300 source_param = Parameter("source", get_cmd=get_cmd,301 set_cmd=set_cmd, snapshot_value=snapshot_value)302 delegate_param = DelegateParameter("delegate", source=source_param)303 assert delegate_param.gettable is gettable304 assert delegate_param.settable is settable305 assert delegate_param._snapshot_value is snapshot_value306@pytest.mark.parametrize("snapshot_value", [True, False])307@pytest.mark.parametrize("gettable,get_cmd", [(True, None), (False, False)])308@pytest.mark.parametrize("settable,set_cmd", [(True, None), (False, False)])309def test_gettable_settable_snapshotget_delegate_parameter_2(gettable, get_cmd,310 settable, set_cmd,311 snapshot_value):312 """313 Test that gettable/settable and snapshot_get are updated correctly314 when source changes315 """316 source_param = Parameter("source", get_cmd=get_cmd, set_cmd=set_cmd,317 snapshot_value=snapshot_value)318 delegate_param = DelegateParameter("delegate", source=None)319 delegate_param.source = source_param320 assert delegate_param.gettable is gettable321 assert delegate_param.settable is settable322 assert delegate_param._snapshot_value is snapshot_value323def test_initial_value_and_none_source_raises():324 with pytest.raises(KeyError, match="It is not allowed to supply"325 " 'initial_value' or"326 " 'initial_cache_value'"):327 DelegateParameter("delegate", source=None, initial_value=1)328 with pytest.raises(KeyError, match="It is not allowed to supply"329 " 'initial_value' or "330 "'initial_cache_value'"):331 DelegateParameter("delegate", source=None, initial_cache_value=1)332def test_delegate_parameter_change_source_reflected_in_label_and_unit():333 delegate_param = DelegateParameter("delegate", source=None)334 source_param_1 = Parameter("source1", label="source 1", unit="unit1")335 source_param_2 = Parameter("source2", label="source 2", unit="unit2")336 assert delegate_param.label == "delegate"337 assert delegate_param.unit == ""338 delegate_param.source = source_param_1339 assert delegate_param.label == "source 1"340 assert delegate_param.unit == "unit1"341 delegate_param.source = source_param_2342 assert delegate_param.label == "source 2"343 assert delegate_param.unit == "unit2"344 delegate_param.source = None345 assert delegate_param.label == "delegate"346 assert delegate_param.unit == ""347def test_delegate_parameter_fixed_label_unit_unchanged():348 delegate_param = DelegateParameter("delegate",349 label="delegatelabel",350 unit="delegateunit",351 source=None)352 source_param_1 = Parameter("source1", label="source 1", unit="unit1")353 source_param_2 = Parameter("source2", label="source 2", unit="unit2")354 assert delegate_param.label == "delegatelabel"355 assert delegate_param.unit == "delegateunit"356 delegate_param.source = source_param_1357 assert delegate_param.label == "delegatelabel"358 assert delegate_param.unit == "delegateunit"359 delegate_param.source = source_param_2360 assert delegate_param.label == "delegatelabel"361 assert delegate_param.unit == "delegateunit"362 delegate_param.source = None363 assert delegate_param.label == "delegatelabel"364 assert delegate_param.unit == "delegateunit"365def test_cache_invalidation():366 value = 10367 p = BetterGettableParam('testparam', set_cmd=None, get_cmd=None)368 d = DelegateParameter('test_delegate_parameter', p,369 initial_cache_value=value)370 assert p._get_count == 0371 assert d.cache.get() == value372 assert p._get_count == 0373 assert d.cache.valid is True374 assert p.cache.valid is True375 d.cache.invalidate()376 assert d.cache.valid is False377 assert p.cache.valid is False378 d.cache.get()379 assert p._get_count == 1380 assert d.cache.valid is True381 assert p.cache.valid is True382def test_cache_no_source():383 d = DelegateParameter('test_delegate_parameter', source=None)384 assert d.cache.valid is False385 assert d.cache.timestamp is None386 assert d.cache.max_val_age is None387 with pytest.raises(388 TypeError,389 match="Cannot get the cache of a "390 "DelegateParameter that delegates to None"):391 d.cache.get()392 d.cache.invalidate()393def test_underlying_instrument_property_for_delegate_parameter():394 p = BetterGettableParam('testparam', set_cmd=None, get_cmd=None)395 d = DelegateParameter('delegate_parameter_with_source', p)396 assert d.underlying_instrument is p.root_instrument397 d = DelegateParameter('delegate_parameter_without_source', source=None)...

Full Screen

Full Screen

delegatecreateseditor_test.py

Source:delegatecreateseditor_test.py Github

copy

Full Screen

1#!/usr/bin/python2# Copyright (C) 2022 The Qt Company Ltd.3# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.04import os5import sys6import unittest7from pathlib import Path8sys.path.append(os.fspath(Path(__file__).resolve().parents[1]))9from init_paths import init_test_paths10init_test_paths(True)11from helper.usesqapplication import UsesQApplication12from testbinding import TestView13from PySide6.QtCore import Qt14from PySide6.QtGui import QStandardItem, QStandardItemModel15from PySide6.QtWidgets import (QAbstractItemDelegate, QComboBox,16 QSpinBox, QStyledItemDelegate,17 QStyleOptionViewItem, QWidget)18id_text = 'This is me'19class DelegateDoesntKeepReferenceToEditor(QAbstractItemDelegate):20 def createEditor(self, parent, option, index):21 comboBox = QComboBox(parent)22 comboBox.addItem(id_text)23 return comboBox24class DelegateKeepsReferenceToEditor(QAbstractItemDelegate):25 def __init__(self, parent=None):26 QAbstractItemDelegate.__init__(self, parent)27 self.comboBox = QComboBox()28 self.comboBox.addItem(id_text)29 def createEditor(self, parent, option, index):30 self.comboBox.setParent(parent)31 return self.comboBox32class EditorCreatedByDelegateTest(UsesQApplication):33 def testDelegateDoesntKeepReferenceToEditor(self):34 view = TestView(None)35 delegate = DelegateDoesntKeepReferenceToEditor()36 view.setItemDelegate(delegate)37 editor = view.getEditorWidgetFromItemDelegate()38 self.assertEqual(type(editor), QComboBox)39 self.assertEqual(editor.count(), 1)40 self.assertEqual(editor.itemData(0, Qt.DisplayRole), id_text)41 editor.metaObject()42 def testDelegateKeepsReferenceToEditor(self):43 view = TestView(None)44 delegate = DelegateKeepsReferenceToEditor()45 view.setItemDelegate(delegate)46 editor = view.getEditorWidgetFromItemDelegate()47 self.assertEqual(type(editor), QComboBox)48 self.assertEqual(editor.count(), 1)49 self.assertEqual(editor.itemData(0, Qt.DisplayRole), id_text)50 editor.metaObject()51 def testIntDelegate(self):52 """PYSIDE-1250: When creating a QVariant, use int instead of long long53 for anything that fits into a int. Verify by checking that a spin54 box is created as item view editor for int."""55 item = QStandardItem()56 item.setData(123123, Qt.EditRole) # <-- QVariant conversion here57 model = QStandardItemModel()58 model.appendRow(item)59 style_option = QStyleOptionViewItem()60 delegate = QStyledItemDelegate()61 editor = delegate.createEditor(None, style_option, model.index(0, 0))62 self.assertEqual(type(editor), QSpinBox)63if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run hypothesis 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