How to use _assertion method in pyshould

Best Python code snippet using pyshould_python

KeyReportAssertions.py

Source:KeyReportAssertions.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# -*- mode: Python -*-3# Leidokos-Python -- Wraps Kaleidoscope modules' c++4# code to be available in Python programs.5# Copyright (C) 2017 noseglasses <shinynoseglasses@gmail.com>6#7# This program is free software: you can redistribute it and/or modify8# it under the terms of the GNU General Public License as published by9# the Free Software Foundation, either version 3 of the License, or10# (at your option) any later version.11#12# This program is distributed in the hope that it will be useful,13# but WITHOUT ANY WARRANTY; without even the implied warranty of14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the15# GNU General Public License for more details.16#17# You should have received a copy of the GNU General Public License18# along with this program. If not, see <http://www.gnu.org/licenses/>.19#20# For documentation style see http://www.sphinx-doc.org/en/stable/ext/napoleon.html21import kaleidoscope22from kaleidoscope import *23from _Assertion import _Assertion24class ReportKeyActive(_Assertion):25 """ Asserts that a specific key is active in the keyboard report.26 27 Args:28 key (Key): The key tested for being active.29 """30 31 def __init__(self, key):32 _Assertion.__init__(self)33 self.key = key34 35 def _description(self):36 return "Key %s active" % str(kaleidoscope.keyToName(self.key))37 def _evalInternal(self, keyReport):38 return keyReport.isKeyActive(self.key)39 40class ReportKeyInactive(_Assertion):41 """ Asserts that a specific key is inactive in the keyboard report.42 43 Args:44 key (Key): The key tested for being inactive.45 """46 47 def __init__(self, key):48 _Assertion.__init__(self)49 self.key = key50 51 def _description(self):52 return "Key %s inactive" % str(kaleidoscope.Key.keyToName(self.key))53 def _evalInternal(self, keyReport):54 return not keyReport.isKeyActive(self.key)55 56class ReportKeycodeActive(_Assertion):57 """ Asserts that a specific keycode is active in the keyboard report.58 59 Args:60 keycode (int): The keycode tested for being active.61 """62 63 def __init__(self, keycode):64 _Assertion.__init__(self)65 self.keycode = keycode66 67 def _description(self):68 return "Keycode %s active" % str(kaleidoscope.Key.keycodeToName(self.keycode))69 def _evalInternal(self, keyReport):70 return keyReport.isKeycodeActive(self.keycode)71 72class ReportKeycodeInactive(_Assertion):73 """ Asserts that a specific key is inactive in the keyboard report.74 75 Args:76 keycode (int): The key tested for being inactive.77 """78 79 def __init__(self, keycode):80 _Assertion.__init__(self)81 self.keycode = keycode82 83 def _description(self):84 return "Keycode %s inactive" % str(kaleidoscope.Key.keycodeToName(self.keycode))85 def _evalInternal(self, keyReport):86 return not keyReport.isKeycodeActive(self.keycode)87 88class ReportKeysActive(_Assertion):89 """ Asserts that a specific list of keys is active in the keyboard report.90 91 Args:92 keys (list): A list of keys tested for being active.93 exclusively (boolean): It True, no other keycodes than the ones supplied 94 are tolerated active.95 """96 97 def __init__(self, keys, exclusively = True):98 _Assertion.__init__(self)99 self.keys = keys100 self.exclusively = exclusively101 102 def _description(self):103 return "Keys active (%s)" % " ".join("'%s\'" % kaleidoscope.keyToName(x) for x in self.keys)104 def _evalInternal(self, keyReport):105 106 activeKeycodes = keyReport.getActiveKeycodes()107 108 for key in self.keys:109 if key.keyCode not in activeKeycodes:110 return False111 112 if self.exclusively:113 if len(activeKeycodes) != len(self.keys):114 return False115 116 return True117 118class ReportModifierActive(_Assertion):119 """ Asserts that a specific modifier is active in the keyboard report.120 121 Args:122 modifier (int): The modifier tested for being active.123 """124 125 def __init__(self, modifier):126 _Assertion.__init__(self)127 self.modifier = modifier128 129 def _description(self):130 return "Modifier %s active" % str(kaleidoscope.modifierKeyToName(self.modifier))131 def _evalInternal(self, keyReport):132 return keyReport.isModifierActive(self.modifier)133 134class ReportModifierInactive(_Assertion):135 """ Asserts that a specific modifier is inactive in the keyboard report.136 137 Args:138 modifier (int): The modifier tested for being inactive.139 """140 141 def __init__(self, modifier):142 _Assertion.__init__(self)143 self.modifier = modifier144 145 def _description(self):146 return "Modifier %s inactive" % str(kaleidoscope.modifierKeyToName(self.modifier))147 def _evalInternal(self, keyReport):148 return not keyReport.isModifierActive(self.modifier)149 150class ReportAnyModifiersActive(_Assertion):151 """ Asserts that any modifiers are active in a key report.152 """153 154 def _description(self):155 return "Any modifiers active"156 def _evalInternal(self, keyReport):157 return keyReport.isAnyModifierActive()158 159class ReportAllModifiersInactive(_Assertion):160 """ Asserts that all modifiers are inactive in a key report.161 """162 163 def _description(self):164 return "All modifiers inactive"165 def _evalInternal(self, keyReport):166 return not keyReport.isAnyModifierActive()167 168class ReportModifiersActive(_Assertion):169 """ Asserts that a specific list of modifiers is active in the keyboard report.170 171 Args:172 modifierKeys (list): A list of modifiers keys tested for being active.173 exclusively (boolean): It True, no other modifiers than the ones supplied 174 are tolerated active.175 """176 177 def __init__(self, modifierKeys, exclusively = True):178 _Assertion.__init__(self)179 self.modifierKeys = modifierKeys180 self.exclusively = exclusively181 182 def _description(self):183 return "Modifiers active (%s)" % " ".join(kaleidoscope.modifierKeyToName(x) for x in self.modifierKeys)184 def _evalInternal(self, keyReport):185 186 activeModifiers = keyReport.getActiveModifiers()187 188 for mod in self.modifierKeys:189 if mod.keyCode not in activeModifiers:190 return False191 192 if self.exclusively:193 if len(activeModifiers) != len(self.modifierKeys):194 return False195 196 return True197 198class ReportAnyKeysActive(_Assertion):199 """ Asserts that any keys are active in a key report.200 """201 202 def _description(self):203 return "Any keys active"204 def _evalInternal(self, keyReport):205 return keyReport.isAnyKeyActive()206 207class ReportAllKeysInactive(_Assertion):208 """ Asserts that all keys are inactive in a key report.209 """210 211 def _description(self):212 return "All keys inactive"213 def _evalInternal(self, keyReport):214 return not keyReport.isAnyKeyActive()215 216class ReportEmpty(_Assertion):217 """ Asserts that a key report is empty.218 """219 220 def _description(self):221 return "Report empty"222 def _evalInternal(self, keyReport):223 return keyReport.isEmpty()224 225class ReportNotEmpty(_Assertion):226 """ Asserts that a key report is notempty.227 """228 229 def _description(self):230 return "Report not empty"231 def _evalInternal(self, keyReport):232 return not keyReport.isEmpty()233 234class ReportNthInCycle(_Assertion):235 """ Asserts that a report is the nth in its current cycle.236 237 Args:238 n (int): The report count.239 """240 241 def __init__(self, n):242 _Assertion.__init__(self)243 self.n = n244 245 def _description(self):246 return "Is %d. report in cycle" % self.n247 def _evalInternal(self, keyReport):248 return self._getTestDriver().nReportsInCycle == self.n249 250 def _actualState(self):251 return "%d. report in cycle" % self._getTestDriver().nReportsInCycle252 253class DumpReport(_Assertion):254 """ Dumps the current keyboard report. """255 256 def _evalInternal(self, keyReport):257 self.keyReport = keyReport258 return True259 260 def _description(self):...

Full Screen

Full Screen

magic.py

Source:magic.py Github

copy

Full Screen

1from IPython.core.magic import magics_class, line_cell_magic, Magics2from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring3import warnings4from .rules_utils import quick_assert_fact, quick_retract_fact, quick_post_event, _delete_state5# TO DO - things are passed in from the magic as strings6# Should we try to cast them to eg int, float, list, tuple, dict?7@magics_class8class DurableRulesMagic(Magics):9 def __init__(self, shell, cache_display_data=False):10 super(DurableRulesMagic, self).__init__(shell)11 self.graph = None12 self.RULESET = None13 @line_cell_magic14 @magic_arguments()15 @argument('--ruleset', '-r', default='', help='Ruleset name.')16 @argument('--no-reset', action='store_false', help='Disable automatic state deletion.')17 def assert_facts(self, line, cell):18 "Assert and/or retract several facts."19 args = parse_argstring(self.assert_facts, line)20 if not args.ruleset and self.RULESET is None:21 warnings.warn("You must provide a ruleset reference (--ruleset/-r RULESET).")22 return23 elif args.ruleset:24 self.RULESET = self.shell.user_ns[args.ruleset]25 _ruleset = self.RULESET26 #print(_ruleset)27 if args.no_reset:28 _delete_state(_ruleset)29 for _assertion in cell.split('\n'):30 if _assertion.startswith('-'):31 quick_retract_fact(_ruleset, _assertion.lstrip('-'))32 elif not _assertion.startswith('#'):33 quick_assert_fact(_ruleset, _assertion)34 @line_cell_magic35 @magic_arguments()36 @argument('--ruleset', '-r', default='', help='Ruleset name.')37 @argument('--no-reset', action='store_false', help='Disable automatic state deletion.')38 def retract_facts(self, line, cell):39 "Retract and/or assert several facts."40 args = parse_argstring(self.retract_facts, line)41 if not args.ruleset and self.RULESET is None:42 warnings.warn("You must provide a ruleset reference (--ruleset/-r RULESET).")43 return44 elif args.ruleset:45 self.RULESET = self.shell.user_ns[args.ruleset]46 _ruleset = self.RULESET47 #print(_ruleset)48 if args.no_reset:49 _delete_state(_ruleset)50 for _assertion in cell.split('\n'):51 if _assertion.startswith('*'):52 quick_assert_fact(_ruleset, _assertion.lstrip('-'))53 elif not _assertion.startswith('#'):54 quick_retract_fact(_ruleset, _assertion)55 @line_cell_magic56 @magic_arguments()57 @argument('--ruleset', '-r', default='', help='Ruleset name.')58 @argument('--no-reset', action='store_false', help='Disable automatic state deletion.')59 def post_events(self, line, cell):60 "Post several events."61 args = parse_argstring(self.post_events, line)62 if not args.ruleset and self.RULESET is None:63 warnings.warn("You must provide a ruleset reference (--ruleset/-r RULESET).")64 return65 elif args.ruleset:66 self.RULESET = self.shell.user_ns[args.ruleset]67 _ruleset = self.RULESET68 #print(_ruleset)69 if args.no_reset:70 _delete_state(_ruleset)71 for _assertion in cell.split('\n'):72 if not _assertion.startswith('#'):73 quick_post_event(_ruleset, _assertion)74 @line_cell_magic75 @magic_arguments()76 @argument('--ruleset', '-r', default='', help='Ruleset name.')77 @argument('--no-reset', action='store_false', help='Disable automatic state deletion.')78 def facts_and_events(self, line, cell):79 "Assert and/or retract several facts and/or post several events."80 args = parse_argstring(self.facts_and_events, line)81 if not args.ruleset and self.RULESET is None:82 warnings.warn("You must provide a ruleset reference (--ruleset/-r RULESET).")83 return84 elif args.ruleset:85 self.RULESET = self.shell.user_ns[args.ruleset]86 _ruleset = self.RULESET87 #print(_ruleset)88 if args.no_reset:89 _delete_state(_ruleset)90 for _assertion in cell.split('\n'):91 if _assertion.startswith('-'):92 quick_retract_fact(_ruleset, _assertion.lstrip('-'))93 elif _assertion.startswith('*'):94 quick_assert_fact(_ruleset, _assertion.lstrip('*'))95 elif _assertion.startswith('%'):...

Full Screen

Full Screen

ResponseDecoder.py

Source:ResponseDecoder.py Github

copy

Full Screen

1from base64 import b64decode2import xmltodict3from .constants import *4class ResponseDecoder:5 """ Decode SAMLResponse data for convenient access """6 def __init__(self, response_data, sp, israw=True):7 if israw:8 # Must be b64decoded9 if type(response_data) is str:10 response_data.encode('utf-8')11 response_data = b64decode(response_data)12 13 self.response_data = response_data14 15 self.root = xmltodict.parse(16 response_data,17 process_namespaces=True,18 namespaces=SamlNS,19 )20 self.sp = sp21 self.resp = self.root['samlp:Response']22 self.status = self.resp['samlp:Status']23 if self.version != '2.0':24 mess = f'SAML version error: {self.version} != v2.0'25 raise Exception(f'Incorrect response: version "{self.version}" - expected "2.0"')26 if self.status_ok:27 # Only valid for a Success Response28 self._assertion = self.resp['saml:Assertion']29 self._subject = self._assertion['saml:Subject']30 self._subjectConfData = self._subject['saml:SubjectConfirmation']['saml:SubjectConfirmationData']31 self._conditions = self._assertion['saml:Conditions']32 self._attributeStatement = self._assertion.get('saml:AttributeStatement')33 def assertion_error(self):34 short_status = self.statusCode.split(':')[-1]35 raise Exception(f'Method invalid for Error Response: {short_status} - {self.statusMessage}')36 @property 37 def version(self):38 return self.resp['@Version']39 @property40 def responseId(self):41 return self.resp['@ID']42 @property43 def status_ok(self):44 return self.statusCode == SamlStatusSuccess45 @property46 def signed_ok(self):47 return self.validate_saml_signing(noexcept=True)48 @property49 def statusCode(self):50 return self.status['samlp:StatusCode']['@Value']51 @property52 def statusMessage(self):53 element = self.status.get('samlp:StatusMessage')54 return element if type(element) is str or element is None else element['#text']55 #56 # The following are only availiale for successful responses57 #58 @property59 def inResponseTo(self):60 return self._subjectConfData['@InResponseTo']61 @property62 def recipient(self):63 return self._subjectConfData['@Recipient']64 @property65 def audience(self):66 return self._conditions['saml:AudienceRestriction']['saml:Audience'] 67 68 @property69 def issuer(self):70 return self._assertion['saml:Issuer']71 72 @property73 def instanceIssued(self):74 return self._assertion['@IssueInstant']75 76 @property77 def notBefore(self):78 return self._conditions['@NotBefore']79 @property80 def notOnOrAfter(self):81 return self._conditions['@NotOnOrAfter']82 83 @property84 def nameID(self):85 return self._subject['saml:NameID']['#text']86 87 @property88 def nameID_format(self):89 return self._subject['saml:NameID']['@Format']90 @property91 def attributeStatement(self):92 # Attributes are optional (i.e. nameid alone could be used for auth)93 data = {}94 if self._attributeStatement is None:95 return data96 attr_elements = self._attributeStatement.get('saml:Attribute',[])97 98 if type(attr_elements) is not list:99 attr_elements = [attr_elements]100 101 for element in attr_elements: 102 attr = element['@Name']103 vals = element['saml:AttributeValue']104 105 if isinstance(vals,dict) and '#text' in vals:106 vals = vals['#text']107 data[attr] = vals108 109 return data 110 def validate_saml_signing(self, noexcept=False):111 112 return self.sp.validateSignedResponse(self.response_data, noexcept)...

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 pyshould 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