Best Python code snippet using play_selenium_python
conditionCollection.unit.js
Source:conditionCollection.unit.js
1import ConditionCollection from 'handsontable-pro/plugins/filters/conditionCollection';2import { conditions } from 'handsontable-pro/plugins/filters/conditionRegisterer';3import { OPERATION_AND, OPERATION_OR } from 'handsontable-pro/plugins/filters/constants';4import { operations } from 'handsontable-pro/plugins/filters/logicalOperationRegisterer';5describe('ConditionCollection', () => {6 it('should be initialized and accessible from the plugin', () => {7 expect(ConditionCollection).toBeDefined();8 });9 it('should create empty bucket for conditions, columnTypes and empty orderStack', () => {10 const conditionCollection = new ConditionCollection();11 expect(conditionCollection.conditions).toEqual(jasmine.any(Object));12 expect(Object.keys(conditionCollection.conditions)).toEqual(Object.keys(operations));13 expect(conditionCollection.orderStack).toEqual(jasmine.any(Array));14 expect(conditionCollection.columnTypes).toEqual(jasmine.any(Object));15 });16 describe('isEmpty', () => {17 it('should return `true` when order stack is equal to 0', () => {18 const conditionCollection = new ConditionCollection();19 expect(conditionCollection.isEmpty()).toBe(true);20 conditionCollection.orderStack.push(1);21 expect(conditionCollection.isEmpty()).toBe(false);22 });23 });24 describe('isMatch', () => {25 it('should check is value is matched to the conditions at specified column index', () => {26 const conditionCollection = new ConditionCollection();27 conditionCollection.columnTypes = { 3: OPERATION_AND };28 const conditionMock = {};29 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(true);30 spyOn(conditionCollection, 'getConditions').and.returnValue([conditionMock]);31 const result = conditionCollection.isMatch('foo', 3);32 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);33 expect(conditionCollection.isMatchInConditions).toHaveBeenCalledWith([conditionMock], 'foo', OPERATION_AND);34 expect(result).toBe(true);35 });36 it('should check is value is matched to the conditions for all columns', () => {37 const conditionCollection = new ConditionCollection();38 conditionCollection.columnTypes = { 3: OPERATION_AND, 13: OPERATION_AND };39 const conditionMock = {};40 const conditionMock2 = {};41 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];42 conditionCollection.conditions[OPERATION_AND]['13'] = [conditionMock2];43 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(true);44 spyOn(conditionCollection, 'getConditions').and.returnValue([conditionMock]);45 const result = conditionCollection.isMatch('foo');46 expect(conditionCollection.getConditions).not.toHaveBeenCalled();47 expect(conditionCollection.isMatchInConditions.calls.argsFor(0)).toEqual([[conditionMock], 'foo', OPERATION_AND]);48 expect(conditionCollection.isMatchInConditions.calls.argsFor(1)).toEqual([[conditionMock2], 'foo', OPERATION_AND]);49 expect(result).toBe(true);50 });51 it('should break checking value when current condition is not matched to the rules', () => {52 const conditionCollection = new ConditionCollection();53 conditionCollection.columnTypes = { 3: OPERATION_AND, 13: OPERATION_AND };54 const conditionMock = {};55 const conditionMock2 = {};56 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];57 conditionCollection.conditions[OPERATION_AND]['13'] = [conditionMock2];58 spyOn(conditionCollection, 'isMatchInConditions').and.returnValue(false);59 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionMock);60 const result = conditionCollection.isMatch('foo');61 expect(conditionCollection.getConditions).not.toHaveBeenCalled();62 expect(conditionCollection.isMatchInConditions.calls.count()).toBe(1);63 expect(conditionCollection.isMatchInConditions.calls.argsFor(0)).toEqual([[conditionMock], 'foo', OPERATION_AND]);64 expect(result).toBe(false);65 });66 });67 describe('isMatchInConditions', () => {68 it('should returns `true` if passed conditions is empty', () => {69 const conditionCollection = new ConditionCollection();70 const result = conditionCollection.isMatchInConditions([], 'foo');71 expect(result).toBe(true);72 });73 describe('OPERATION_AND', () => {74 it('should check if array of conditions is matched to the value', () => {75 const conditionCollection = new ConditionCollection();76 const conditionMock = { func: () => true };77 const conditionMock2 = { func: () => true };78 spyOn(conditionMock, 'func').and.callThrough();79 spyOn(conditionMock2, 'func').and.callThrough();80 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo');81 expect(conditionMock.func.calls.count()).toBe(1);82 expect(conditionMock.func).toHaveBeenCalledWith('foo');83 expect(conditionMock2.func.calls.count()).toBe(1);84 expect(conditionMock2.func).toHaveBeenCalledWith('foo');85 expect(result).toBe(true);86 });87 it('should break checking value when condition is not matched to the value', () => {88 const conditionCollection = new ConditionCollection();89 const conditionMock = { func: () => false };90 const conditionMock2 = { func: () => true };91 spyOn(conditionMock, 'func').and.callThrough();92 spyOn(conditionMock2, 'func').and.callThrough();93 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo');94 expect(conditionMock.func.calls.count()).toBe(1);95 expect(conditionMock.func).toHaveBeenCalledWith('foo');96 expect(conditionMock2.func.calls.count()).toBe(0);97 expect(result).toBe(false);98 });99 });100 describe('OPERATION_OR', () => {101 it('should check if one of conditions is matched to the value #1', () => {102 const conditionCollection = new ConditionCollection();103 const conditionMock = { func: () => false };104 const conditionMock2 = { func: () => true };105 spyOn(conditionMock, 'func').and.callThrough();106 spyOn(conditionMock2, 'func').and.callThrough();107 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo', OPERATION_OR);108 expect(conditionMock.func.calls.count()).toBe(1);109 expect(conditionMock.func).toHaveBeenCalledWith('foo');110 expect(conditionMock2.func.calls.count()).toBe(1);111 expect(conditionMock2.func).toHaveBeenCalledWith('foo');112 expect(result).toBe(true);113 });114 it('should check if one of conditions is matched to the value #2', () => {115 const conditionCollection = new ConditionCollection();116 const conditionMock = { func: () => false };117 const conditionMock2 = { func: () => false };118 spyOn(conditionMock, 'func').and.callThrough();119 spyOn(conditionMock2, 'func').and.callThrough();120 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2], 'foo', OPERATION_OR);121 expect(conditionMock.func.calls.count()).toBe(1);122 expect(conditionMock.func).toHaveBeenCalledWith('foo');123 expect(conditionMock2.func.calls.count()).toBe(1);124 expect(conditionMock2.func).toHaveBeenCalledWith('foo');125 expect(result).toBe(false);126 });127 it('should break checking value when condition is matched to the value', () => {128 const conditionCollection = new ConditionCollection();129 const conditionMock = { func: () => false };130 const conditionMock2 = { func: () => true };131 const conditionMock3 = { func: () => false };132 spyOn(conditionMock, 'func').and.callThrough();133 spyOn(conditionMock2, 'func').and.callThrough();134 spyOn(conditionMock3, 'func').and.callThrough();135 const result = conditionCollection.isMatchInConditions([conditionMock, conditionMock2, conditionMock3], 'foo', OPERATION_OR);136 expect(conditionMock3.func.calls.count()).toBe(0);137 expect(result).toBe(true);138 });139 });140 });141 describe('addCondition', () => {142 beforeEach(() => {143 conditions.eq = {144 condition: () => {},145 descriptor: {},146 };147 conditions.contains = {148 condition: () => {},149 descriptor: {},150 };151 });152 afterEach(() => {153 delete conditions.eq;154 delete conditions.contains;155 });156 it('should trigger `beforeAdd` and `afterAdd` hook on adding condition', () => {157 const conditionCollection = new ConditionCollection();158 const conditionMock = { args: [], command: { key: 'eq' } };159 const hookBeforeSpy = jasmine.createSpy('hookBefore');160 const hookAfterSpy = jasmine.createSpy('hookAfter');161 conditionCollection.addLocalHook('beforeAdd', hookBeforeSpy);162 conditionCollection.addLocalHook('afterAdd', hookAfterSpy);163 conditionCollection.addCondition(3, conditionMock);164 expect(hookBeforeSpy).toHaveBeenCalledWith(3);165 expect(hookAfterSpy).toHaveBeenCalledWith(3);166 });167 it('should add column index to the orderStack without duplicate values', () => {168 const conditionCollection = new ConditionCollection();169 const conditionMock = { args: [], command: { key: 'eq' } };170 conditionCollection.addCondition(3, conditionMock);171 conditionCollection.addCondition(3, conditionMock);172 conditionCollection.addCondition(3, conditionMock);173 expect(conditionCollection.orderStack).toEqual([3]);174 });175 it('should add condition to the collection at specified column index.', () => {176 const conditionCollection = new ConditionCollection();177 const conditionMock = { args: [1], command: { key: 'eq' } };178 conditionCollection.addCondition(3, conditionMock);179 expect(conditionCollection.conditions[OPERATION_AND]['3'].length).toBe(1);180 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].name).toBe('eq');181 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].args).toEqual([1]);182 expect(conditionCollection.conditions[OPERATION_AND]['3'][0].func instanceof Function).toBe(true);183 });184 it('should allow to add few condition under the same name and column index #160', () => {185 const conditionCollection = new ConditionCollection();186 const conditionMock = { args: ['A'], command: { key: 'contains' } };187 const conditionMock2 = { args: ['B'], command: { key: 'contains' } };188 const conditionMock3 = { args: ['C'], command: { key: 'contains' } };189 conditionCollection.addCondition(3, conditionMock);190 conditionCollection.addCondition(3, conditionMock2);191 conditionCollection.addCondition(3, conditionMock3);192 expect(conditionCollection.conditions[OPERATION_AND]['3'].length).toBe(3);193 });194 it('should allow to add few condition under the same column index ' +195 'only when they are related to the same operation (throw exception otherwise) #160', () => {196 const conditionCollection = new ConditionCollection();197 const conditionMock = { args: ['A'], command: { key: 'contains' } };198 const conditionMock2 = { args: ['B'], command: { key: 'contains' } };199 const conditionMock3 = { args: ['C'], command: { key: 'contains' } };200 conditionCollection.addCondition(3, conditionMock, OPERATION_AND);201 conditionCollection.addCondition(3, conditionMock2, OPERATION_AND);202 expect(() => {203 conditionCollection.addCondition(3, conditionMock3, OPERATION_OR);204 }).toThrow(/has been already applied/);205 });206 it('should allow to add conditions only when they are related to the known operation ' +207 '(throw exception otherwise) #174', () => {208 const conditionCollection = new ConditionCollection();209 const conditionMock = { args: ['A'], command: { key: 'contains' } };210 expect(() => {211 conditionCollection.addCondition(3, conditionMock, 'unknownOperation');212 }).toThrow(/Unexpected operation/);213 });214 });215 describe('exportAllConditions', () => {216 it('should return an empty array when no conditions was added', () => {217 const conditionCollection = new ConditionCollection();218 conditionCollection.orderStack = [];219 const exportedConditions = conditionCollection.exportAllConditions();220 expect(exportedConditions.length).toBe(0);221 });222 it('should return conditions as an array of objects for all column in the same order as it was added', () => {223 const conditionCollection = new ConditionCollection();224 const conditionMock = { name: 'begins_with', args: ['c'] };225 const conditionMock1 = { name: 'date_tomorrow', args: [] };226 const conditionMock2 = { name: 'eq', args: ['z'] };227 conditionCollection.orderStack = [6, 1, 3];228 conditionCollection.columnTypes = { 1: OPERATION_AND, 3: OPERATION_AND, 6: OPERATION_AND };229 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];230 conditionCollection.conditions[OPERATION_AND]['6'] = [conditionMock1];231 conditionCollection.conditions[OPERATION_AND]['1'] = [conditionMock2];232 const exportedConditions = conditionCollection.exportAllConditions();233 expect(exportedConditions.length).toBe(3);234 expect(exportedConditions[0].column).toBe(6);235 expect(exportedConditions[0].conditions[0].name).toBe('date_tomorrow');236 expect(exportedConditions[0].conditions[0].args).toEqual([]);237 expect(exportedConditions[1].column).toBe(1);238 expect(exportedConditions[1].conditions[0].name).toBe('eq');239 expect(exportedConditions[1].conditions[0].args).toEqual(['z']);240 expect(exportedConditions[2].column).toBe(3);241 expect(exportedConditions[2].conditions[0].name).toBe('begins_with');242 expect(exportedConditions[2].conditions[0].args).toEqual(['c']);243 });244 });245 describe('getConditions', () => {246 it('should return conditions at specified index otherwise should return empty array', () => {247 const conditionCollection = new ConditionCollection();248 conditionCollection.columnTypes = { 3: OPERATION_AND };249 const conditionMock = {};250 conditionCollection.conditions[OPERATION_AND]['3'] = [conditionMock];251 expect(conditionCollection.getConditions(2)).toEqual([]);252 expect(conditionCollection.getConditions(3)).toEqual([conditionMock]);253 });254 });255 describe('removeConditions', () => {256 it('should trigger `beforeRemove` and `afterRemove` hook on removing conditions', () => {257 const conditionCollection = new ConditionCollection();258 const conditionMock = {};259 conditionCollection.orderStack = [3];260 conditionCollection.conditions['3'] = [conditionMock];261 const hookBeforeSpy = jasmine.createSpy('hookBefore');262 const hookAfterSpy = jasmine.createSpy('hookAfter');263 conditionCollection.addLocalHook('beforeRemove', hookBeforeSpy);264 conditionCollection.addLocalHook('afterRemove', hookAfterSpy);265 conditionCollection.removeConditions(3);266 expect(hookBeforeSpy).toHaveBeenCalledWith(3);267 expect(hookAfterSpy).toHaveBeenCalledWith(3);268 });269 it('should remove condition from collection and column index from orderStack', () => {270 const conditionCollection = new ConditionCollection();271 const conditionMock = {};272 spyOn(conditionCollection, 'clearConditions');273 conditionCollection.orderStack = [3];274 conditionCollection.conditions['3'] = [conditionMock];275 conditionCollection.removeConditions(3);276 expect(conditionCollection.orderStack).toEqual([]);277 expect(conditionCollection.clearConditions).toHaveBeenCalledWith(3);278 });279 });280 describe('clearConditions', () => {281 it('should trigger `beforeClear` and `afterClear` hook on clearing conditions', () => {282 const conditionCollection = new ConditionCollection();283 const hookBeforeSpy = jasmine.createSpy('hookBefore');284 const hookAfterSpy = jasmine.createSpy('hookAfter');285 conditionCollection.addLocalHook('beforeClear', hookBeforeSpy);286 conditionCollection.addLocalHook('afterClear', hookAfterSpy);287 conditionCollection.clearConditions(3);288 expect(hookBeforeSpy).toHaveBeenCalledWith(3);289 expect(hookAfterSpy).toHaveBeenCalledWith(3);290 });291 it('should clear all conditions at specified column index', () => {292 const conditionCollection = new ConditionCollection();293 const conditionsMock = [{}, {}];294 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);295 conditionCollection.clearConditions(3);296 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);297 expect(conditionsMock.length).toBe(0);298 });299 });300 describe('hasConditions', () => {301 it('should return `true` if at specified column index condition were found', () => {302 const conditionCollection = new ConditionCollection();303 conditionCollection.columnTypes = { 3: OPERATION_AND };304 const conditionsMock = [{}, {}];305 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);306 const result = conditionCollection.hasConditions(3);307 expect(result).toBe(true);308 });309 it('should return `false` if at specified column index no conditions were found', () => {310 const conditionCollection = new ConditionCollection();311 const conditionsMock = [];312 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);313 const result = conditionCollection.hasConditions(3);314 expect(result).toBe(false);315 });316 it('should return `true` if at specified column index condition were found under its name', () => {317 const conditionCollection = new ConditionCollection();318 conditionCollection.columnTypes = { 3: OPERATION_AND };319 const conditionsMock = [{ name: 'lte' }, { name: 'eq' }];320 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);321 const result = conditionCollection.hasConditions(3, 'eq');322 expect(result).toBe(true);323 });324 it('should return `false` if at specified column index no conditions were found under its name', () => {325 const conditionCollection = new ConditionCollection();326 conditionCollection.columnTypes = { 3: OPERATION_AND };327 const conditionsMock = [{ name: 'lte' }, { name: 'eq' }];328 spyOn(conditionCollection, 'getConditions').and.returnValue(conditionsMock);329 const result = conditionCollection.hasConditions(3, 'between');330 expect(conditionCollection.getConditions).toHaveBeenCalledWith(3);331 expect(result).toBe(false);332 });333 });334 describe('clean', () => {335 it('should trigger `beforeClean` and `afterClean` hook on cleaning conditions', () => {336 const conditionCollection = new ConditionCollection();337 conditionCollection.conditions = { 0: [] };338 conditionCollection.conditions = [1, 2, 3, 4];339 const hookBeforeSpy = jasmine.createSpy('hookBefore');340 const hookAfterSpy = jasmine.createSpy('hookAfter');341 conditionCollection.addLocalHook('beforeClean', hookBeforeSpy);342 conditionCollection.addLocalHook('afterClean', hookAfterSpy);343 conditionCollection.clean();344 expect(hookBeforeSpy).toHaveBeenCalled();345 expect(hookAfterSpy).toHaveBeenCalled();346 });347 it('should clear condition collection and orderStack', () => {348 const conditionCollection = new ConditionCollection();349 conditionCollection.conditions = { 0: [] };350 conditionCollection.conditions = [1, 2, 3, 4];351 conditionCollection.clean();352 expect(conditionCollection.conditions).toEqual(jasmine.any(Object));353 expect(Object.keys(conditionCollection.conditions)).toEqual(Object.keys(operations));354 expect(conditionCollection.orderStack.length).toBe(0);355 });356 });357 describe('destroy', () => {358 it('should nullable all properties', () => {359 const conditionCollection = new ConditionCollection();360 conditionCollection.conditions[OPERATION_AND] = { 0: [], 2: [] };361 conditionCollection.conditions[OPERATION_OR] = { 3: [], 4: [] };362 conditionCollection.orderStack = [1, 2, 3, 4];363 conditionCollection.destroy();364 expect(conditionCollection.conditions).toBeNull();365 expect(conditionCollection.orderStack).toBeNull();366 expect(conditionCollection.columnTypes).toBeNull();367 });368 });...
control.py
Source:control.py
1## @package control2# Module caffe2.python.control3"""4Implement functions for controlling execution of nets and steps, including5 Do6 DoParallel7 For-loop8 While-loop9 Do-While-loop10 Switch11 If12"""13from __future__ import absolute_import14from __future__ import division15from __future__ import print_function16from __future__ import unicode_literals17from caffe2.python import core18from future.utils import viewitems19# Used to generate names of the steps created by the control functions.20# It is actually the internal index of these steps.21_current_idx = 122_used_step_names = set()23def _get_next_step_name(control_name, base_name):24 global _current_idx, _used_step_names25 concat_name = '%s/%s' % (base_name, control_name)26 next_name = concat_name27 while next_name in _used_step_names:28 next_name = '%s_%d' % (concat_name, _current_idx)29 _current_idx += 130 _used_step_names.add(next_name)31 return next_name32def _MakeList(input):33 """ input is a tuple.34 Example:35 (a, b, c) --> [a, b, c]36 (a) --> [a]37 ([a, b, c]) --> [a, b, c]38 """39 if len(input) == 0:40 raise ValueError(41 'input cannot be empty.')42 elif len(input) == 1:43 output = input[0]44 if not isinstance(output, list):45 output = [output]46 else:47 output = list(input)48 return output49def _IsNets(nets_or_steps):50 if isinstance(nets_or_steps, list):51 return all(isinstance(n, core.Net) for n in nets_or_steps)52 else:53 return isinstance(nets_or_steps, core.Net)54def _PrependNets(nets_or_steps, *nets):55 nets_or_steps = _MakeList((nets_or_steps,))56 nets = _MakeList(nets)57 if _IsNets(nets_or_steps):58 return nets + nets_or_steps59 else:60 return [Do('prepend', nets)] + nets_or_steps61def _AppendNets(nets_or_steps, *nets):62 nets_or_steps = _MakeList((nets_or_steps,))63 nets = _MakeList(nets)64 if _IsNets(nets_or_steps):65 return nets_or_steps + nets66 else:67 return nets_or_steps + [Do('append', nets)]68def GetConditionBlobFromNet(condition_net):69 """70 The condition blob is the last external_output that must71 be a single bool72 """73 assert len(condition_net.Proto().external_output) > 0, (74 "Condition net %s must has at least one external output" %75 condition_net.Proto.name)76 # we need to use a blob reference here instead of a string77 # otherwise, it will add another name_scope to the input later78 # when we create new ops (such as OR of two inputs)79 return core.BlobReference(condition_net.Proto().external_output[-1])80def BoolNet(*blobs_with_bool_value):81 """A net assigning constant bool values to blobs. It is mainly used for82 initializing condition blobs, for example, in multi-task learning, we83 need to access reader_done blobs before reader_net run. In that case,84 the reader_done blobs must be initialized.85 Args:86 blobs_with_bool_value: one or more (blob, bool_value) pairs. The net will87 assign each bool_value to the corresponding blob.88 returns89 bool_net: A net assigning constant bool values to blobs.90 Examples:91 - BoolNet((blob_1, bool_value_1), ..., (blob_n, bool_value_n))92 - BoolNet([(blob_1, net1), ..., (blob_n, bool_value_n)])93 - BoolNet((cond_1, bool_value_1))94 """95 blobs_with_bool_value = _MakeList(blobs_with_bool_value)96 bool_net = core.Net('bool_net')97 for blob, bool_value in blobs_with_bool_value:98 out_blob = bool_net.ConstantFill(99 [],100 [blob],101 shape=[],102 value=bool_value,103 dtype=core.DataType.BOOL)104 bool_net.AddExternalOutput(out_blob)105 return bool_net106def NotNet(condition_blob_or_net):107 """Not of a condition blob or net108 Args:109 condition_blob_or_net can be either blob or net. If condition_blob_or_net110 is Net, the condition is its last external_output111 that must be a single bool.112 returns113 not_net: the net NOT the input114 out_blob: the output blob of the not_net115 """116 if isinstance(condition_blob_or_net, core.Net):117 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)118 else:119 condition_blob = condition_blob_or_net120 not_net = core.Net('not_net')121 out_blob = not_net.Not(condition_blob)122 not_net.AddExternalOutput(out_blob)123 return not_net, out_blob124def _CopyConditionBlobNet(condition_blob):125 """Make a condition net that copies the condition_blob126 Args:127 condition_blob is a single bool.128 returns129 not_net: the net NOT the input130 out_blob: the output blob of the not_net131 """132 condition_net = core.Net('copy_condition_blob_net')133 out_blob = condition_net.Copy(condition_blob)134 condition_net.AddExternalOutput(out_blob)135 return condition_net, out_blob136def MergeConditionNets(name, condition_nets, relation):137 """138 Merge multi condition nets into a single condition nets.139 Args:140 name: name of the new condition net.141 condition_nets: a list of condition nets. The last external_output142 of each condition net must be single bool value.143 relation: can be 'And' or 'Or'.144 Returns:145 - A new condition net. Its last external output is relation of all146 condition_nets.147 """148 if not isinstance(condition_nets, list):149 return condition_nets150 if len(condition_nets) <= 1:151 return condition_nets[0] if condition_nets else None152 merged_net = core.Net(name)153 for i in range(len(condition_nets)):154 net_proto = condition_nets[i].Proto()155 assert net_proto.device_option == merged_net.Proto().device_option156 assert net_proto.type == merged_net.Proto().type157 merged_net.Proto().op.extend(net_proto.op)158 merged_net.Proto().external_input.extend(net_proto.external_input)159 # discard external outputs as we're combining them together160 curr_cond = GetConditionBlobFromNet(condition_nets[i])161 if i == 0:162 last_cond = curr_cond163 else:164 last_cond = merged_net.__getattr__(relation)([last_cond, curr_cond])165 # merge attributes166 for k, v in viewitems(condition_nets[i]._attr_dict):167 merged_net._attr_dict[k] += v168 merged_net.AddExternalOutput(last_cond)169 return merged_net170def CombineConditions(name, condition_nets, relation):171 """172 Combine conditions of multi nets into a single condition nets. Unlike173 MergeConditionNets, the actual body of condition_nets is not copied into174 the combine condition net.175 One example is about multi readers. Each reader net has a reader_done176 condition. When we want to check whether all readers are done, we can177 use this function to build a new net.178 Args:179 name: name of the new condition net.180 condition_nets: a list of condition nets. The last external_output181 of each condition net must be single bool value.182 relation: can be 'And' or 'Or'.183 Returns:184 - A new condition net. Its last external output is relation of all185 condition_nets.186 """187 if not condition_nets:188 return None189 if not isinstance(condition_nets, list):190 raise ValueError('condition_nets must be a list of nets.')191 if len(condition_nets) == 1:192 condition_blob = GetConditionBlobFromNet(condition_nets[0])193 condition_net, _ = _CopyConditionBlobNet(condition_blob)194 return condition_net195 combined_net = core.Net(name)196 for i in range(len(condition_nets)):197 curr_cond = GetConditionBlobFromNet(condition_nets[i])198 if i == 0:199 last_cond = curr_cond200 else:201 last_cond = combined_net.__getattr__(relation)(202 [last_cond, curr_cond])203 combined_net.AddExternalOutput(last_cond)204 return combined_net205def Do(name, *nets_or_steps):206 """207 Execute the sequence of nets or steps once.208 Examples:209 - Do('myDo', net1, net2, ..., net_n)210 - Do('myDo', list_of_nets)211 - Do('myDo', step1, step2, ..., step_n)212 - Do('myDo', list_of_steps)213 """214 nets_or_steps = _MakeList(nets_or_steps)215 if (len(nets_or_steps) == 1 and isinstance(216 nets_or_steps[0], core.ExecutionStep)):217 return nets_or_steps[0]218 else:219 return core.scoped_execution_step(220 _get_next_step_name('Do', name), nets_or_steps)221def DoParallel(name, *nets_or_steps):222 """223 Execute the nets or steps in parallel, waiting for all of them to finish224 Examples:225 - DoParallel('pDo', net1, net2, ..., net_n)226 - DoParallel('pDo', list_of_nets)227 - DoParallel('pDo', step1, step2, ..., step_n)228 - DoParallel('pDo', list_of_steps)229 """230 nets_or_steps = _MakeList(nets_or_steps)231 if (len(nets_or_steps) == 1 and isinstance(232 nets_or_steps[0], core.ExecutionStep)):233 return nets_or_steps[0]234 else:235 return core.scoped_execution_step(236 _get_next_step_name('DoParallel', name),237 nets_or_steps,238 concurrent_substeps=True)239def _RunOnceIf(name, condition_blob_or_net, nets_or_steps):240 """241 Execute nets_or_steps once if condition_blob_or_net evaluates as true.242 If condition_blob_or_net is Net, the condition is its last external_output243 that must be a single bool. And this net will be executed before244 nets_or_steps so as to get the condition.245 """246 condition_not_net, stop_blob = NotNet(condition_blob_or_net)247 if isinstance(condition_blob_or_net, core.Net):248 nets_or_steps = _PrependNets(249 nets_or_steps, condition_blob_or_net, condition_not_net)250 else:251 nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)252 def if_step(control_name):253 return core.scoped_execution_step(254 _get_next_step_name(control_name, name),255 nets_or_steps,256 should_stop_blob=stop_blob,257 only_once=True,258 )259 if _IsNets(nets_or_steps):260 bool_net = BoolNet((stop_blob, False))261 return Do(name + '/_RunOnceIf',262 bool_net, if_step('_RunOnceIf-inner'))263 else:264 return if_step('_RunOnceIf')265def _RunOnceIfNot(name, condition_blob_or_net, nets_or_steps):266 """267 Similar to _RunOnceIf() but Execute nets_or_steps once if268 condition_blob_or_net evaluates as false.269 """270 if isinstance(condition_blob_or_net, core.Net):271 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)272 nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)273 else:274 copy_net, condition_blob = _CopyConditionBlobNet(condition_blob_or_net)275 nets_or_steps = _PrependNets(nets_or_steps, copy_net)276 return core.scoped_execution_step(277 _get_next_step_name('_RunOnceIfNot', name),278 nets_or_steps,279 should_stop_blob=condition_blob,280 only_once=True,281 )282def For(name, nets_or_steps, iter_num):283 """284 Execute nets_or_steps iter_num times.285 Args:286 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or287 a list nets.288 iter_num: the number times to execute the nets_or_steps.289 Returns:290 A ExecutionStep instance.291 """292 init_net = core.Net('init-net')293 iter_cnt = init_net.CreateCounter([], init_count=iter_num)294 iter_net = core.Net('For-iter')295 iter_done = iter_net.CountDown([iter_cnt])296 for_step = core.scoped_execution_step(297 _get_next_step_name('For-inner', name),298 _PrependNets(nets_or_steps, iter_net),299 should_stop_blob=iter_done)300 return Do(name + '/For',301 Do(name + '/For-init-net', init_net),302 for_step)303def While(name, condition_blob_or_net, nets_or_steps):304 """305 Execute nets_or_steps when condition_blob_or_net returns true.306 Args:307 condition_blob_or_net: If it is an instance of Net, its last308 external_output must be a single bool.309 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or310 a list nets.311 Returns:312 A ExecutionStep instance.313 """314 condition_not_net, stop_blob = NotNet(condition_blob_or_net)315 if isinstance(condition_blob_or_net, core.Net):316 nets_or_steps = _PrependNets(317 nets_or_steps, condition_blob_or_net, condition_not_net)318 else:319 nets_or_steps = _PrependNets(nets_or_steps, condition_not_net)320 def while_step(control_name):321 return core.scoped_execution_step(322 _get_next_step_name(control_name, name),323 nets_or_steps,324 should_stop_blob=stop_blob,325 )326 if _IsNets(nets_or_steps):327 # In this case, while_step has sub-nets:328 # [condition_blob_or_net, condition_not_net, nets_or_steps]329 # If stop_blob is pre-set to True (this may happen when While() is330 # called twice), the loop will exit after executing331 # condition_blob_or_net. So we use BootNet to set stop_blob to332 # False.333 bool_net = BoolNet((stop_blob, False))334 return Do(name + '/While', bool_net, while_step('While-inner'))335 else:336 return while_step('While')337def Until(name, condition_blob_or_net, nets_or_steps):338 """339 Similar to While() but execute nets_or_steps when340 condition_blob_or_net returns false341 """342 if isinstance(condition_blob_or_net, core.Net):343 stop_blob = GetConditionBlobFromNet(condition_blob_or_net)344 nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net)345 else:346 stop_blob = core.BlobReference(str(condition_blob_or_net))347 return core.scoped_execution_step(348 _get_next_step_name('Until', name),349 nets_or_steps,350 should_stop_blob=stop_blob)351def DoWhile(name, condition_blob_or_net, nets_or_steps):352 """353 Execute nets_or_steps when condition_blob_or_net returns true. It will354 execute nets_or_steps before evaluating condition_blob_or_net.355 Args:356 condition_blob_or_net: if it is an instance of Net, tts last external_output357 must be a single bool.358 nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or359 a list nets.360 Returns:361 A ExecutionStep instance.362 """363 condition_not_net, stop_blob = NotNet(condition_blob_or_net)364 if isinstance(condition_blob_or_net, core.Net):365 nets_or_steps = _AppendNets(366 nets_or_steps, condition_blob_or_net, condition_not_net)367 else:368 nets_or_steps = _AppendNets(nets_or_steps, condition_not_net)369 # If stop_blob is pre-set to True (this may happen when DoWhile() is370 # called twice), the loop will exit after executing the first net/step371 # in nets_or_steps. This is not what we want. So we use BootNet to372 # set stop_blob to False.373 bool_net = BoolNet((stop_blob, False))374 return Do(name + '/DoWhile', bool_net, core.scoped_execution_step(375 _get_next_step_name('DoWhile-inner', name),376 nets_or_steps,377 should_stop_blob=stop_blob,378 ))379def DoUntil(name, condition_blob_or_net, nets_or_steps):380 """381 Similar to DoWhile() but execute nets_or_steps when382 condition_blob_or_net returns false. It will execute383 nets_or_steps before evaluating condition_blob_or_net.384 Special case: if condition_blob_or_net is a blob and is pre-set to385 true, then only the first net/step of nets_or_steps will be executed and386 loop is exited. So you need to be careful about the initial value the387 condition blob when using DoUntil(), esp when DoUntil() is called twice.388 """389 if not isinstance(condition_blob_or_net, core.Net):390 stop_blob = core.BlobReference(condition_blob_or_net)391 return core.scoped_execution_step(392 _get_next_step_name('DoUntil', name),393 nets_or_steps,394 should_stop_blob=stop_blob)395 nets_or_steps = _AppendNets(nets_or_steps, condition_blob_or_net)396 stop_blob = GetConditionBlobFromNet(condition_blob_or_net)397 # If stop_blob is pre-set to True (this may happen when DoWhile() is398 # called twice), the loop will exit after executing the first net/step399 # in nets_or_steps. This is not what we want. So we use BootNet to400 # set stop_blob to False.401 bool_net = BoolNet((stop_blob, False))402 return Do(name + '/DoUntil', bool_net, core.scoped_execution_step(403 _get_next_step_name('DoUntil-inner', name),404 nets_or_steps,405 should_stop_blob=stop_blob,406 ))407def Switch(name, *conditions):408 """409 Execute the steps for which the condition is true.410 Each condition is a tuple (condition_blob_or_net, nets_or_steps).411 Note:412 1. Multi steps can be executed if their conditions are true.413 2. The conditions_blob_or_net (if it is Net) of all steps will be414 executed once.415 Examples:416 - Switch('name', (cond_1, net_1), (cond_2, net_2), ..., (cond_n, net_n))417 - Switch('name', [(cond_1, net1), (cond_2, net_2), ..., (cond_n, net_n)])418 - Switch('name', (cond_1, net_1))419 """420 conditions = _MakeList(conditions)421 return core.scoped_execution_step(422 _get_next_step_name('Switch', name),423 [_RunOnceIf(name + '/Switch', cond, step) for cond, step in conditions])424def SwitchNot(name, *conditions):425 """426 Similar to Switch() but execute the steps for which the condition is False.427 """428 conditions = _MakeList(conditions)429 return core.scoped_execution_step(430 _get_next_step_name('SwitchNot', name),431 [_RunOnceIfNot(name + '/SwitchNot', cond, step)432 for cond, step in conditions])433def If(name, condition_blob_or_net,434 true_nets_or_steps, false_nets_or_steps=None):435 """436 condition_blob_or_net is first evaluated or executed. If the condition is437 true, true_nets_or_steps is then executed, otherwise, false_nets_or_steps438 is executed.439 If condition_blob_or_net is Net, the condition is its last external_output440 that must be a single bool. And this Net will be executred before both441 true/false_nets_or_steps so as to get the condition.442 """443 if not false_nets_or_steps:444 return _RunOnceIf(name + '/If',445 condition_blob_or_net, true_nets_or_steps)446 if isinstance(condition_blob_or_net, core.Net):447 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)448 else:449 condition_blob = condition_blob_or_net450 return Do(451 name + '/If',452 _RunOnceIf(name + '/If-true',453 condition_blob_or_net, true_nets_or_steps),454 _RunOnceIfNot(name + '/If-false', condition_blob, false_nets_or_steps)455 )456def IfNot(name, condition_blob_or_net,457 true_nets_or_steps, false_nets_or_steps=None):458 """459 If condition_blob_or_net returns false, executes true_nets_or_steps,460 otherwise executes false_nets_or_steps461 """462 if not false_nets_or_steps:463 return _RunOnceIfNot(name + '/IfNot',464 condition_blob_or_net, true_nets_or_steps)465 if isinstance(condition_blob_or_net, core.Net):466 condition_blob = GetConditionBlobFromNet(condition_blob_or_net)467 else:468 condition_blob = condition_blob_or_net469 return Do(470 name + '/IfNot',471 _RunOnceIfNot(name + '/IfNot-true',472 condition_blob_or_net, true_nets_or_steps),473 _RunOnceIf(name + '/IfNot-false', condition_blob, false_nets_or_steps)...
aws.pyi
Source:aws.pyi
...117 "StringLike",118 "StringNotLike",119]120_condition_qualifier_strings = ["ForAnyValue", "ForAllValues"]121def make_condition(type_name: str, condition_name: str) -> None: ...122class ArnEquals(ConditionElement): ...123class ArnNotEquals(ConditionElement): ...124class ArnLike(ConditionElement): ...125class ArnNotLike(ConditionElement): ...126class Bool(ConditionElement): ...127class DateEquals(ConditionElement): ...128class DateNotEquals(ConditionElement): ...129class DateLessThan(ConditionElement): ...130class DateLessThanEquals(ConditionElement): ...131class DateGreaterThan(ConditionElement): ...132class DateGreaterThanEquals(ConditionElement): ...133class IpAddress(ConditionElement): ...134class NotIpAddress(ConditionElement): ...135class Null(ConditionElement): ......
test_condition.py
Source:test_condition.py
...23 return factories.RangeFactory(24 name="Some products", products=products_some25 )26@pytest.fixture27def count_condition(range_all):28 return models.CountCondition(range=range_all, type="Count", value=2)29@pytest.fixture30def value_condition(range_all):31 return models.ValueCondition(range=range_all, type="Value", value=D("10.00"))32@pytest.fixture33def coverage_condition(range_some):34 return models.CoverageCondition(range=range_some, type="Coverage", value=2)35@pytest.fixture36def empty_basket():37 return factories.create_basket(empty=True)38@pytest.fixture39def partial_basket(empty_basket):40 basket = empty_basket41 add_product(basket)42 return basket43@pytest.fixture44def mock_offer():45 return mock.Mock()46@pytest.mark.django_db47class TestCountCondition:48 @pytest.fixture(autouse=True)49 def setUp(self, mock_offer):50 self.offer = mock_offer51 def test_description(self, count_condition):52 assert count_condition.description53 def test_is_not_satisfied_by_empty_basket(self, count_condition, empty_basket):54 assert count_condition.is_satisfied(self.offer, empty_basket) is False55 def test_not_discountable_product_fails_condition(56 self, count_condition, empty_basket57 ):58 basket = empty_basket59 prod1, prod2 = factories.create_product(), factories.create_product()60 prod2.is_discountable = False61 prod2.save()62 add_product(basket, product=prod1)63 add_product(basket, product=prod2)64 assert count_condition.is_satisfied(self.offer, basket) is False65 def test_empty_basket_fails_partial_condition(self, count_condition, empty_basket):66 assert count_condition.is_partially_satisfied(self.offer, empty_basket) is False67 def test_smaller_quantity_basket_passes_partial_condition(68 self, count_condition, empty_basket69 ):70 basket = empty_basket71 add_product(basket)72 assert count_condition.is_partially_satisfied(self.offer, basket)73 assert count_condition._num_matches == 174 def test_smaller_quantity_basket_upsell_message(75 self, count_condition, empty_basket76 ):77 basket = empty_basket78 add_product(basket)79 assert "Buy 1 more product from " in count_condition.get_upsell_message(80 self.offer, basket81 )82 def test_matching_quantity_basket_fails_partial_condition(83 self, count_condition, empty_basket84 ):85 basket = empty_basket86 add_product(basket, quantity=2)87 assert count_condition.is_partially_satisfied(self.offer, basket) is False88 def test_matching_quantity_basket_passes_condition(89 self, count_condition, empty_basket90 ):91 basket = empty_basket92 add_product(basket, quantity=2)93 assert count_condition.is_satisfied(self.offer, basket)94 def test_greater_quantity_basket_passes_condition(95 self, count_condition, empty_basket96 ):97 basket = empty_basket98 add_product(basket, quantity=3)99 assert count_condition.is_satisfied(self.offer, basket)100 def test_consumption(self, count_condition, empty_basket):101 basket = empty_basket102 add_product(basket, quantity=3)103 count_condition.consume_items(self.offer, basket, [])104 assert 1 == basket.all_lines()[0].quantity_without_discount105 def test_is_satisfied_accounts_for_consumed_items(106 self, count_condition, empty_basket107 ):108 basket = empty_basket109 add_product(basket, quantity=3)110 count_condition.consume_items(self.offer, basket, [])111 assert count_condition.is_satisfied(self.offer, basket) is False112@pytest.mark.django_db113class TestValueCondition:114 @pytest.fixture(autouse=True)115 def setUp(self, empty_basket, value_condition, mock_offer):116 self.basket = empty_basket117 self.condition = value_condition118 self.offer = mock_offer119 self.item = factories.create_product(price=D("5.00"))120 self.expensive_item = factories.create_product(price=D("15.00"))121 def test_description(self, value_condition):122 assert value_condition.description123 def test_empty_basket_fails_condition(self):124 assert self.condition.is_satisfied(self.offer, self.basket) is False125 def test_empty_basket_fails_partial_condition(self):126 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False127 def test_less_value_basket_fails_condition(self):128 add_product(self.basket, D("5"))129 assert self.condition.is_satisfied(self.offer, self.basket) is False130 def test_not_discountable_item_fails_condition(self):131 product = factories.create_product(is_discountable=False)132 add_product(self.basket, D("15"), product=product)133 assert self.condition.is_satisfied(self.offer, self.basket) is False134 def test_upsell_message(self):135 add_product(self.basket, D("5"))136 assert "Spend" in self.condition.get_upsell_message(self.offer, self.basket)137 def test_matching_basket_fails_partial_condition(self):138 add_product(self.basket, D("5"), 2)139 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False140 def test_less_value_basket_passes_partial_condition(self):141 add_product(self.basket, D("5"), 1)142 assert self.condition.is_partially_satisfied(self.offer, self.basket)143 def test_matching_basket_passes_condition(self):144 add_product(self.basket, D("5"), 2)145 assert self.condition.is_satisfied(self.offer, self.basket)146 def test_greater_than_basket_passes_condition(self):147 add_product(self.basket, D("5"), 3)148 assert self.condition.is_satisfied(self.offer, self.basket)149 def test_consumption(self):150 add_product(self.basket, D("5"), 3)151 self.condition.consume_items(self.offer, self.basket, [])152 assert 1 == self.basket.all_lines()[0].quantity_without_discount153 def test_consumption_with_high_value_product(self):154 add_product(self.basket, D("15"), 1)155 self.condition.consume_items(self.offer, self.basket, [])156 assert 0 == self.basket.all_lines()[0].quantity_without_discount157 def test_is_consumed_respects_quantity_consumed(self):158 add_product(self.basket, D("15"), 1)159 assert self.condition.is_satisfied(self.offer, self.basket)160 self.condition.consume_items(self.offer, self.basket, [])161 assert self.condition.is_satisfied(self.offer, self.basket) is False162@pytest.mark.django_db163class TestCoverageCondition:164 @pytest.fixture(autouse=True)165 def setUp(self, range_some, products_some, empty_basket, coverage_condition):166 self.products = products_some167 self.range = range_some168 self.basket = empty_basket169 self.condition = coverage_condition170 self.offer = mock.Mock()171 def test_empty_basket_fails(self):172 assert self.condition.is_satisfied(self.offer, self.basket) is False173 def test_empty_basket_fails_partial_condition(self):174 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False175 def test_single_item_fails(self):176 add_product(self.basket, product=self.products[0])177 assert self.condition.is_satisfied(self.offer, self.basket) is False178 def test_not_discountable_item_fails(self):179 self.products[0].is_discountable = False180 self.products[0].save()181 add_product(self.basket, product=self.products[0])182 add_product(self.basket, product=self.products[1])183 assert self.condition.is_satisfied(self.offer, self.basket) is False184 def test_single_item_passes_partial_condition(self):185 add_product(self.basket, product=self.products[0])186 assert self.condition.is_partially_satisfied(self.offer, self.basket)187 def test_upsell_message(self):188 add_product(self.basket, product=self.products[0])189 assert "Buy 1 more" in self.condition.get_upsell_message(190 self.offer, self.basket191 )192 def test_duplicate_item_fails(self):193 add_product(self.basket, quantity=2, product=self.products[0])194 assert self.condition.is_satisfied(self.offer, self.basket) is False195 def test_duplicate_item_passes_partial_condition(self):196 add_product(self.basket, quantity=2, product=self.products[0])197 assert self.condition.is_partially_satisfied(self.offer, self.basket)198 def test_covering_items_pass(self):199 add_product(self.basket, product=self.products[0])200 add_product(self.basket, product=self.products[1])201 assert self.condition.is_satisfied(self.offer, self.basket)202 def test_covering_items_fail_partial_condition(self):203 add_product(self.basket, product=self.products[0])204 add_product(self.basket, product=self.products[1])205 assert self.condition.is_partially_satisfied(self.offer, self.basket) is False206 def test_covering_items_are_consumed(self):207 add_product(self.basket, product=self.products[0])208 add_product(self.basket, product=self.products[1])209 self.condition.consume_items(self.offer, self.basket, [])210 assert 0 == self.basket.num_items_without_discount211 def test_consumed_items_checks_affected_items(self):212 # Create new offer213 range = models.Range.objects.create(214 name="All products", includes_all_products=True215 )216 cond = models.CoverageCondition(range=range, type="Coverage", value=2)217 # Get 4 distinct products in the basket218 self.products.extend([factories.create_product(), factories.create_product()])219 for product in self.products:220 add_product(self.basket, product=product)221 assert cond.is_satisfied(self.offer, self.basket)222 cond.consume_items(self.offer, self.basket, [])223 assert 2 == self.basket.num_items_without_discount224 assert cond.is_satisfied(self.offer, self.basket)225 cond.consume_items(self.offer, self.basket, [])226 assert 0 == self.basket.num_items_without_discount227@pytest.mark.django_db228class TestConditionProxyModels(object):229 def test_name_and_description(self, range):230 """231 Tests that the condition proxy classes all return a name and232 description. Unfortunately, the current implementations means233 a valid range and value are required.234 """235 for type, __ in models.Condition.TYPE_CHOICES:236 condition = models.Condition(type=type, range=range, value=5)237 assert all([condition.name, condition.description, str(condition)])238 def test_proxy(self, range):239 for type, __ in models.Condition.TYPE_CHOICES:240 condition = models.Condition(type=type, range=range, value=5)241 proxy = condition.proxy()242 assert condition.type == proxy.type243 assert condition.range == proxy.range244 assert condition.value == proxy.value245class TestCustomCondition(TestCase):246 def setUp(self):247 self.condition = custom.create_condition(BasketOwnerCalledBarry)248 self.offer = models.ConditionalOffer(condition=self.condition)249 self.basket = Basket()250 def test_is_not_satisfied_by_non_match(self):251 self.basket.owner = factories.UserFactory(first_name="Alan")252 assert self.offer.is_condition_satisfied(self.basket) is False253 def test_is_satisfied_by_match(self):254 self.basket.owner = factories.UserFactory(first_name="Barry")...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!