Best Python code snippet using autotest_python
poll.js
Source:poll.js
1const Polling = artifacts.require("Polling");2/*3 * uncomment accounts to access the test accounts made available by the4 * Ethereum client5 * See docs: https://www.trufflesuite.com/docs/truffle/testing/writing-tests-in-javascript6 */7const truffleAssert = require('truffle-assertions');8contract("Polling", function (accounts) {9 const TEST_TOPIC = "TEST_TOPIC";10 const TEST_DESCRIPTION = "TEST_DESCRIPTION";11 let TEST_OPTION = [12 '~100',13 '101~200',14 '201~300',15 '300~',16 ]17 let testSponsor, testVoter, testExpiredBlock;18 let pollContractInstance;19 let finalPollList;20 before(async () => {21 testSponsor = accounts[0];22 testVoter = accounts[1];23 testExpiredBlock = 999999999;24 pollContractInstance = await Polling.deployed();25 console.log({26 contractAddress: pollContractInstance.address,27 testSponsor,28 testVoter,29 testExpiredBlock,30 })31 TEST_OPTION = TEST_OPTION.map(e => {32 // return web3.utils.hexToBytes(web3.utils.utf8ToHex(e));33 return web3.utils.utf8ToHex(e);34 })35 console.log({ TEST_OPTION })36 })37 it("should successfully create a poll", async function () {38 let pollList, pollIdOfSponsor;39 pollList = await pollContractInstance.getPollList();40 pollIdOfSponsor = await pollContractInstance.getSponsorsPollList({ from: testSponsor });41 assert.strictEqual(pollList.length, 0, "Polling Contract: invalid poll list length before first polling");42 assert.strictEqual(pollIdOfSponsor.length, 0, "Polling Contract: invalid poll length of sponsor before first polling");43 await pollContractInstance.sponsorRaisesAPoll(44 TEST_TOPIC,45 TEST_DESCRIPTION,46 TEST_OPTION,47 testExpiredBlock,48 { from: testSponsor }49 );50 pollList = await pollContractInstance.getPollList();51 pollIdOfSponsor = await pollContractInstance.getSponsorsPollList({ from: testSponsor });52 assert.strictEqual(pollList.length, 1, "Polling Contract: invalid poll list length after first polling");53 assert.strictEqual(pollIdOfSponsor.length, 1, "Polling Contract: invalid poll length of sponsor after first polling");54 await pollContractInstance.sponsorRaisesAPoll(55 TEST_TOPIC,56 TEST_DESCRIPTION,57 TEST_OPTION,58 testExpiredBlock,59 { from: testSponsor }60 );61 pollList = await pollContractInstance.getPollList();62 pollIdOfSponsor = await pollContractInstance.getSponsorsPollList({ from: testSponsor });63 assert.strictEqual(pollList.length, 2, "Polling Contract: invalid poll list length after second polling");64 assert.strictEqual(pollIdOfSponsor.length, 2, "Polling Contract: invalid poll length of sponsor after second polling");65 await pollContractInstance.sponsorRaisesAPoll(66 TEST_TOPIC,67 TEST_DESCRIPTION,68 TEST_OPTION,69 testExpiredBlock,70 { from: accounts[3] }71 );72 pollList = await pollContractInstance.getPollList();73 pollIdOfSponsor = await pollContractInstance.getSponsorsPollList({ from: accounts[3] });74 assert.strictEqual(pollList.length, 3, "Polling Contract: invalid poll list length after third polling");75 assert.strictEqual(pollIdOfSponsor.length, 1, "Polling Contract: invalid poll length of sponsor after third polling");76 let registryStatus = await pollContractInstance.isOptionBelongToPoll(pollList[0], TEST_OPTION[0])77 assert.isTrue(registryStatus, "Polling Contract: should be true");78 registryStatus = await pollContractInstance.isOptionBelongToPoll(pollList[0], TEST_OPTION[1])79 assert.isTrue(registryStatus, "Polling Contract: should be true");80 registryStatus = await pollContractInstance.isOptionBelongToPoll(pollList[0], TEST_OPTION[2])81 assert.isTrue(registryStatus, "Polling Contract: should be true");82 registryStatus = await pollContractInstance.isOptionBelongToPoll(pollList[0], TEST_OPTION[3])83 assert.isTrue(registryStatus, "Polling Contract: should be true");84 registryStatus = await pollContractInstance.isOptionBelongToPoll(pollList[0], TEST_OPTION[3] + "123")85 assert.isFalse(registryStatus, "Polling Contract: should be false");86 finalPollList = pollList;87 return true;88 });89 it("should fail to create a poll", async function () {90 truffleAssert.fails(91 pollContractInstance.sponsorRaisesAPoll(92 TEST_TOPIC,93 TEST_DESCRIPTION,94 TEST_OPTION,95 1,96 { from: testSponsor }97 ),98 truffleAssert.ErrorType.REVERT,99 "Invalid expired block",100 "Polling Contract: should provide correct expired block number",101 );102 let pollList = await pollContractInstance.getPollList();103 return assert.strictEqual(pollList.length, 3, "Polling Contract: invalid poll list length after failing to create a poll");104 });105 it("should successfully vote to a poll", async function () {106 let pollId = finalPollList[0];107 let status, pollIdOfVoter, choice, isVoted, selected;108 status = await pollContractInstance.getPollInformation(pollId);109 choice = TEST_OPTION[0];110 pollIdOfVoter = await pollContractInstance.getVotersPollList({ from: testVoter });111 // assert.strictEqual(status._voters, undefined, "Polling Contract: invalid voter length of poll before first voting at 0");112 assert.strictEqual(pollIdOfVoter.length, 0, "Polling Contract: invalid poll length of voter before first voting at 0");113 await pollContractInstance.voterVotesAPoll(114 pollId, choice,115 { from: testVoter }116 );117 status = await pollContractInstance.getPollInformation(pollId);118 pollIdOfVoter = await pollContractInstance.getVotersPollList({ from: testVoter });119 isVoted = await pollContractInstance.isVoted(pollId, { from: testVoter });120 assert.strictEqual(status._voters.length, 1, "Polling Contract: invalid voter length of poll after first voting at 0");121 assert.strictEqual(pollIdOfVoter.length, 1, "Polling Contract: invalid poll length of voter after first voting at 0");122 assert.isTrue(isVoted, "Polling Contract: should be true");123 await pollContractInstance.voterVotesAPoll(124 pollId, choice,125 { from: accounts[2] }126 );127 status = await pollContractInstance.getPollInformation(pollId);128 pollIdOfVoter = await pollContractInstance.getVotersPollList({ from: accounts[2] });129 isVoted = await pollContractInstance.isVoted(pollId, { from: accounts[2] });130 assert.strictEqual(status._voters.length, 2, "Polling Contract: invalid voter length of poll after second voting at 0");131 assert.strictEqual(pollIdOfVoter.length, 1, "Polling Contract: invalid poll length of voter after second voting at 0");132 assert.isTrue(isVoted, "Polling Contract: should be true");133 pollId = finalPollList[1];134 choice = TEST_OPTION[1];135 await pollContractInstance.voterVotesAPoll(136 pollId, choice,137 { from: testVoter }138 );139 status = await pollContractInstance.getPollInformation(pollId);140 pollIdOfVoter = await pollContractInstance.getVotersPollList({ from: testVoter });141 isVoted = await pollContractInstance.isVoted(pollId, { from: testVoter });142 assert.strictEqual(status._voters.length, 1, "Polling Contract: invalid voter length of poll after first voting at 1");143 assert.strictEqual(pollIdOfVoter.length, 2, "Polling Contract: invalid poll length of voter after first voting at 1");144 assert.isTrue(isVoted, "Polling Contract: should be true");145 pollId = finalPollList[2];146 choice = TEST_OPTION[2];147 await pollContractInstance.voterVotesAPoll(148 pollId, choice,149 { from: testVoter }150 );151 status = await pollContractInstance.getPollInformation(pollId);152 pollIdOfVoter = await pollContractInstance.getVotersPollList({ from: testVoter });153 isVoted = await pollContractInstance.isVoted(pollId, { from: testVoter });154 assert.strictEqual(status._voters.length, 1, "Polling Contract: invalid voter length of poll after first voting at 1");155 assert.strictEqual(pollIdOfVoter.length, 3, "Polling Contract: invalid poll length of voter after first voting at 1");156 assert.isTrue(isVoted, "Polling Contract: should be true");157 return true;158 });159 it("should fail to vote again", async function () {160 truffleAssert.fails(161 pollContractInstance.voterVotesAPoll(162 finalPollList[0], TEST_OPTION[0],163 { from: testVoter }164 ),165 truffleAssert.ErrorType.REVERT,166 "You've polled for this",167 "Polling Contract: should not be voted again at 0",168 );169 truffleAssert.fails(170 pollContractInstance.voterVotesAPoll(171 finalPollList[1], TEST_OPTION[1],172 { from: testVoter }173 ),174 truffleAssert.ErrorType.REVERT,175 "You've polled for this",176 "Polling Contract: should not be voted again at 1",177 );178 truffleAssert.fails(179 pollContractInstance.voterVotesAPoll(180 finalPollList[1], TEST_OPTION[1] + "123",181 { from: testVoter }182 ),183 truffleAssert.ErrorType.REVERT,184 "Poll doesn't have such choice",185 "Polling Contract: inexisted option should not be choiced",186 );187 truffleAssert.fails(188 pollContractInstance.voterVotesAPoll(189 finalPollList[2], TEST_OPTION[2],190 { from: testVoter }191 ),192 truffleAssert.ErrorType.REVERT,193 "You've polled for this",194 "Polling Contract: should not be voted again at 2",195 );196 let status;197 status = await pollContractInstance.getPollInformation(finalPollList[0]);198 assert.strictEqual(status._voters.length, 2, "Polling Contract: invalid voter length at 0");199 status = await pollContractInstance.getPollInformation(finalPollList[1]);200 assert.strictEqual(status._voters.length, 1, "Polling Contract: invalid voter length at 1");201 status = await pollContractInstance.getPollInformation(finalPollList[2]);202 assert.strictEqual(status._voters.length, 1, "Polling Contract: invalid voter length at 2");203 });204 it("should fail to vote inexisted option", async function () {205 truffleAssert.fails(206 pollContractInstance.voterVotesAPoll(207 finalPollList[0], TEST_OPTION[0] + "123",208 { from: accounts[9] }209 ),210 truffleAssert.ErrorType.REVERT,211 "Poll doesn't have such choice",212 "Polling Contract: should not be voted to an inexisted option",213 );214 let status = await pollContractInstance.getPollInformation(finalPollList[0]);215 assert.strictEqual(status._voters.length, 2, "Polling Contract: invalid voter length at 0");216 });217 it("should fail to vote an expired option", async function () {218 const _blockNumber = (await web3.eth.getBlockNumber()) + 2;219 await pollContractInstance.sponsorRaisesAPoll(220 TEST_TOPIC,221 TEST_DESCRIPTION,222 TEST_OPTION,223 _blockNumber,224 { from: testSponsor }225 );226 let pollList = await pollContractInstance.getPollList();227 truffleAssert.fails(228 pollContractInstance.voterVotesAPoll(229 pollList[3], TEST_OPTION[0],230 { from: accounts[9] }231 ),232 truffleAssert.ErrorType.REVERT,233 "Poll is expired",234 "Polling Contract: should not be voted to an expired option",235 );236 let status = await pollContractInstance.getPollInformation(pollList[3]);237 assert.strictEqual(status._voters.length, 0, "Polling Contract: invalid voter length at 0");238 });239 it("should fail to vote a inexisted poll", async function () {240 truffleAssert.fails(241 pollContractInstance.voterVotesAPoll(242 "0x7e313030", TEST_OPTION[0],243 { from: testVoter }244 ),245 truffleAssert.ErrorType.REVERT,246 "Poll isn't existed",247 "Polling Contract: inexisted poll should not be voted",248 );249 });...
dcs_cn0435.py
Source:dcs_cn0435.py
1"""PLC MODBUS module.2This module provide a simple terminal interface to easy interact with:3 - CN0414 - Analog input and HART for PLC/DCS systems4 - CN0418 - Analog output and HART for PLC/DCS systems5 - CN0416 - RS485 transceiver6Only one comunication port is used and a single MODBUS node.7This application also allows to switch between MODBUS nodes if are available.8"""9__version__ = '0.1'10__author__ = 'Mihai Ionut Suciu'11__status__ = 'Development'12from itertools import zip_longest13from colorama import init, Fore14import minimalmodbus15from tabulate import tabulate16import dcs_cn0435_utilities as utilities17import dcs_cn0414_utilities as cn041418import dcs_cn0418_utilities as cn041819init(autoreset=True)20def read_adc_data(test_option: str) -> None:21 """Read ADC data.22 Args:23 test_option: Option value (number or letter)24 Returns:25 None26 """27 if test_option == '1':28 cn0414.read_device_voltage_channel(GLOBAL_DATA)29 elif test_option == '2':30 cn0414.read_device_current_channel(GLOBAL_DATA)31 elif test_option == '3':32 cn0414.read_board_voltage_channels(GLOBAL_DATA)33 elif test_option == '4':34 cn0414.read_board_current_channels(GLOBAL_DATA)35 elif test_option == '5':36 cn0414.read_instrument_voltage_channels(GLOBAL_DATA)37 elif test_option == '6':38 cn0414.read_instrument_current_channels(GLOBAL_DATA)39 else:40 pass41def read_registers(test_option: str) -> None:42 """Read analog input or output holding registers.43 Args:44 test_option: Option value (number or letter)45 Returns:46 None47 """48 if test_option == 'o':49 utilities.read_common_analog_input_regs(GLOBAL_DATA, debug=True)50 elif test_option == 'p':51 utilities.read_common_output_holding_regs(GLOBAL_DATA, debug=True)52 elif test_option == 'r':53 utilities.read_analog_input_regs_from_sys_config(GLOBAL_DATA)54 elif test_option == 's':55 utilities.read_output_holding_regs_from_sys_config(GLOBAL_DATA)56 else:57 pass58def run_selected_function(test_option: str) -> None:59 """Run selected function.60 Args:61 test_option: Option value (number or letter)62 Returns:63 None64 """65 options = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',66 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',67 'p', 'r', 's', 't', 'q']68 if test_option in options:69 read_registers(test_option)70 set_adc_parametters(test_option)71 read_adc_data(test_option)72 write_dac_data(test_option)73 set_hart(test_option)74 if test_option == 't':75 utilities.scan_system_config(PORT_NUMBER, DELAY)76 elif test_option == 'q':77 print(Fore.CYAN + "\nExit... Good Bye!")78 exit(1)79 else:80 pass81 else:82 print(Fore.RED + 'No valid option selected!')83def set_adc_parametters(test_option: str) -> None:84 """Set ADC parametters.85 Args:86 test_option: Option value (number or letter)87 Returns:88 None89 """90 if test_option == '7':91 cn0414.set_adc_output_code(GLOBAL_DATA)92 elif test_option == '8':93 cn0414.set_adc_filter(GLOBAL_DATA)94 elif test_option == '9':95 cn0414.set_adc_postfilter(GLOBAL_DATA)96 elif test_option == 'a':97 cn0414.set_adc_output_data_rate(GLOBAL_DATA)98 elif test_option == 'b':99 cn0414.set_adc_open_wire_detection(GLOBAL_DATA)100 else:101 pass102def set_hart(test_option: str) -> None:103 """Send HART command 0 or select HART channel.104 Args:105 test_option: Option value (number or letter)106 Returns:107 None108 """109 if test_option == 'c':110 cn0414.send_hart_command_0(GLOBAL_DATA)111 elif test_option == 'd':112 cn0414.select_hart_channel(GLOBAL_DATA)113 elif test_option == 'm':114 cn0418.send_hart_command_0(GLOBAL_DATA)115 elif test_option == 'n':116 cn0418.select_hart_channel(GLOBAL_DATA)117 else:118 pass119def test_options() -> str:120 """Print test options.121 Args:122 None123 Returns:124 Keyboard input125 """126 cn0435_options = [127 Fore.GREEN + 'o - Read common analog input registers',128 Fore.GREEN + 'p - Read common output holding registers',129 Fore.GREEN + 'r - Read analog input registers',130 Fore.GREEN + 's - Read output holding registers',131 Fore.GREEN + 't - Detect system configuration',132 Fore.GREEN + '',133 Fore.GREEN + '',134 Fore.GREEN + '',135 Fore.GREEN + '',136 Fore.GREEN + '',137 Fore.GREEN + '',138 Fore.GREEN + '',139 Fore.YELLOW + 'q - Quit']140 cn0414_options = [141 Fore.GREEN + '1 - Read device voltage channel',142 Fore.GREEN + '2 - Read device current channel',143 Fore.GREEN + '3 - Read board voltage channels',144 Fore.GREEN + '4 - Read board current channels',145 Fore.GREEN + '5 - Read instrument voltage channels',146 Fore.GREEN + '6 - Read instrument current channels',147 Fore.GREEN + '7 - Set ADC output code',148 Fore.GREEN + '8 - Set ADC filter',149 Fore.GREEN + '9 - Set ADC postfilter',150 Fore.GREEN + 'a - Set ADC output data rate',151 Fore.GREEN + 'b - Set ADC open wire detection state',152 Fore.GREEN + 'c - Send HART command zero',153 Fore.GREEN + 'd - Select HART channel']154 cn0418_options = [155 Fore.GREEN + 'e - Set DAC channel 1 output',156 Fore.GREEN + 'f - Set DAC channel 2 output',157 Fore.GREEN + 'g - Set DAC channel 3 output',158 Fore.GREEN + 'h - Set DAC channel 4 output',159 Fore.GREEN + 'i - Set DAC channel 1 range',160 Fore.GREEN + 'j - Set DAC channel 2 range',161 Fore.GREEN + 'k - Set DAC channel 3 range',162 Fore.GREEN + 'l - Set DAC channel 4 range',163 Fore.GREEN + 'm - Send HART command zero',164 Fore.GREEN + 'n - Select HART channel']165 print(Fore.CYAN + "\nUse CTRL+C to end a process or switch between nodes.")166 print(tabulate(167 headers=[Fore.YELLOW + 'CN0414',168 Fore.YELLOW + 'CN0418',169 Fore.YELLOW + 'CN0435'],170 tabular_data=list(171 zip_longest(cn0414_options, cn0418_options, cn0435_options))))172 print(Fore.CYAN + "\nEnter Option: ", end='')173 return input()174def write_dac_data(test_option: str) -> None:175 """Write DAC data.176 Args:177 test_option: Option value (number or letter)178 Returns:179 None180 """181 if test_option == 'e':182 cn0418.select_channel_range(GLOBAL_DATA, 1)183 elif test_option == 'f':184 cn0418.select_channel_range(GLOBAL_DATA, 2)185 elif test_option == 'g':186 cn0418.select_channel_range(GLOBAL_DATA, 3)187 elif test_option == 'h':188 cn0418.select_channel_range(GLOBAL_DATA, 4)189 elif test_option == 'i':190 cn0418.set_channel_output(GLOBAL_DATA, 1)191 elif test_option == 'j':192 cn0418.set_channel_output(GLOBAL_DATA, 2)193 elif test_option == 'k':194 cn0418.set_channel_output(GLOBAL_DATA, 3)195 elif test_option == 'l':196 cn0418.set_channel_output(GLOBAL_DATA, 4)197 else:198 pass199if __name__ == "__main__":200 DATA = utilities.request_info()201 PORT_NUMBER, MODBUS_ADDRESS = DATA[0], DATA[1]202 MODBUS_TIMEOUT, DELAY = DATA[2], DATA[3]203 VALID_CS, BOARDS = DATA[4], DATA[5]204 while True:205 try:206 INSTRUMENT = minimalmodbus.Instrument(PORT_NUMBER, MODBUS_ADDRESS)207 INSTRUMENT.serial.timeout = MODBUS_TIMEOUT208 GLOBAL_DATA = {209 "INSTRUMENT": INSTRUMENT,210 "MODBUS_ADDRESS": MODBUS_ADDRESS,211 "DELAY": DELAY,212 "VALID_CS": VALID_CS,213 "BOARDS": BOARDS214 }215 while True:216 try:217 run_selected_function(test_options())218 except OSError as error_message:219 print(Fore.RED + 'Timeout error!', error_message)220 except ValueError as error_message:221 print(Fore.RED + 'Register operation error!',222 error_message)223 except KeyboardInterrupt:224 print(Fore.CYAN + "\nSwitch to a new MODBUS address... ")225 NEW_DATA = utilities.switch_modbus_address(226 PORT_NUMBER, MODBUS_TIMEOUT)227 MODBUS_ADDRESS = NEW_DATA[0]...
utest-python-options.py
Source:utest-python-options.py
...5def check_option(comp, optname, value):6 print 'option', optname, 'for component', comp.uri(), 'has value', comp.options()[optname], 'and should be', value7 if comp.options()[optname] != value:8 raise Exception('Bad option value')9def test_option(comp, optname, value):10 comp.options().set(optname, value)11 check_option(comp, optname, value)12opts01 = root.create_component('opts01', 'cf3.python.TestAllOptions')13test_option(opts01, 'string', 'teststring')14test_option(opts01, 'real', 2.)15test_option(opts01, 'real', 2)16test_option(opts01, 'int', 3)17test_option(opts01, 'uint', 4)18test_option(opts01, 'bool', True)19test_option(opts01, 'uri', opts01.uri())20test_option(opts01, 'generic_component', opts01)21test_option(opts01, 'group_component', root)22test_option(opts01, 'string_vector', ['a', 'b', 'c'])23test_option(opts01, 'int_vector', [0, 1, 2])24test_option(opts01, 'uint_vector', [0, 1, 2])25test_option(opts01, 'real_vector', [0, 1.2, 2.9])26test_option(opts01, 'real_vector', [0, 1, 2])27test_option(opts01, 'bool_vector', [False, True, False])28test_option(opts01, 'generic_component_vector', [opts01, root])29test_option(opts01, 'group_component_vector', [root, root])30print '########################### Testing global config ##########################'31# test configure signal32testgrp = opts01.create_component('testgrp', 'cf3.common.Group')33testgen = opts01.create_component('testgen', 'cf3.common.Component')34opts01.configure(string = 'global_config', real = 4, int = 5, uint = 6, bool = False, uri = testgen.uri(), generic_component = testgen, group_component = testgrp, string_vector = ['d', 'e'], int_vector = [3, 4, 5], uint_vector = [3, 4, 5], real_vector = [6, 7.2, 8.3], bool_vector = [True, False, True], generic_component_vector = [opts01, testgen], group_component_vector = [testgrp, root])35check_option(opts01, 'string', 'global_config')36check_option(opts01, 'real', 4.)37check_option(opts01, 'int', 5)38check_option(opts01, 'uint', 6)39check_option(opts01, 'bool', False)40check_option(opts01, 'uri', testgen.uri())41check_option(opts01, 'generic_component', testgen)42check_option(opts01, 'group_component', testgrp)43check_option(opts01, 'string_vector', ['d', 'e'])...
filter-on-regex.ts
Source:filter-on-regex.ts
...29 // 4. Text is preceeded by any non-alphanumeric char30 const r4 = new RegExp(`[^\w]${esc_text}`, "i");31 const matches = options32 // filter out options that don't match at all33 .filter(opt => test_option(opt, rA))34 // get the score for each option35 .map((opt: T) => {36 if (test_option(opt, r0)) {37 return { score: 5, opt };38 }39 if (test_option(opt, r1)) {40 return { score: 4, opt };41 }42 if (test_option(opt, r2)) {43 return { score: 3, opt };44 }45 if (test_option(opt, r3)) {46 return { score: 2, opt };47 }48 if (test_option(opt, r4)) {49 return { score: 1, opt };50 }51 return { score: 0, opt };52 });53 // sort by score (descending) and return the result54 return matches.sort(comparator("score", "desc"));55};56export const filter_options = <T>(57 text: string,58 options: readonly T[],59 test_option: RegexFilterFunction<T>60): T[] =>61 filter_options_with_score(text, options, test_option).map(({ opt }) => opt);62export const filter_options_by_props = <T extends object>(...
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!!